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

...
Автор SHA1 Повідомлення Дата
Deng Liu 5487609512 fix(macos): suppress Siri Writing Tools affordance on macOS 27
PR #6274 set WKWebViewConfiguration.writingToolsBehavior to
NSWritingToolsBehaviorNone, which disables Writing Tools on macOS 15/26.
On macOS 27 (WebKit bug 327446), WKWebView enables the embedder feature
TextInputClientSelectionUpdatesEnabled by default and sends selection
updates to NSTextInputContext without checking writingToolsBehavior ==
None, while -[WKWebView allowsWritingToolsAffordance] also returns YES
regardless of writingToolsBehavior.

Work around both sides when disabling Writing Tools:
- Disable TextInputClientSelectionUpdatesEnabled on WKPreferences (while
  keeping inputContext active for editable IME composition and dictation).
- Override allowsWritingToolsAffordance to return NO on the WKWebView
  subclass (WryWebView) without modifying the base WKWebView class.

Copilot-Session: f623556d-6ac4-4834-a4e5-92b98a5c8055
2026-11-27 23:17:44 -08:00
rolicon 4fb1cae917 fix(java): stop legacy launch records from forcing Maven builds after delegation is off (#6556)
A Maven launch record served both as a reusable snapshot and as the signal to keep delegating to Maven. A failed build left a null record that could not be reused but, because the file existed, kept overriding delegateBuild=false. The need to clean mixed-language output is now persisted on its own (java-launch/delegation): a plain Java build failure or an unpublished snapshot no longer forces later launches through Maven, while a pending cleanup survives failures and restarts and is cleared after a successful Maven clean build. Legacy null and old snapshot records migrate conservatively (no output directory: no cleanup needed). Normal launches and shared Maven builds use the same check, and main launches ignore records kept only for test output.

Closes #5538

Co-authored-by: rolicon <[email protected]>
2026-11-28 14:58:51 +08:00
LU XIANGRUIтаwildcatDownstairs 23bbed8bfe fix(notebook): keep the Jupyter Variables read cheap and out of the way of runs (#6643)
Follow-up to #6517. The Variables read shortens bytes, bytearray and str subclasses without building the full repr, and is interrupted after 5 seconds instead of dropped, so a run waiting behind it gets a drained kernel; a read interrupted for its time limit keeps the kernel. Interrupt, restart and close reach an in-flight read, and several reads can be in flight while a run waits for them.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:58:28 +08:00
LU XIANGRUIтаwildcatDownstairs 1880ac541c fix(python): fixture usages and rename follow pytest's files and Python's names (#6655)
Follow-up to #6520. Find Usages, Go to Declaration and Rename of a pytest fixture now search where pytest would look: the defining test module, the test files below a conftest.py, or the project's test files for a plugin or pytest_plugins module, with test files taken from python_files in the configuration file pytest reads. A fixture imported into a conftest or test module is that module's own. Rename merges the language server's rename of the fixture function, refuses names that clash with a parameter or body name, an override or another fixture in scope, and invalid identifiers, and reads of a parameter skip nested scopes that rebind it.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:58:10 +08:00
LU XIANGRUIтаwildcatDownstairs d698b50361 fix(python): respect inherited MPLBACKEND and tidy plot files (#6653)
Follow-up to #6529. A run that inherits the IDE's environment now keeps an MPLBACKEND set in the login shell or the project's .envrc instead of replacing it with the Plots backend; debug launches get the backend too, unless their own environment names one. Figures dropped from the Plots tool window are deleted from the project's plots folder (plots_delete, limited to finished figures in that folder, compared canonicalized), and the watcher reports a figure once it is renamed into place.

Refs #6514

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:57:42 +08:00
LU XIANGRUIтаwildcatDownstairs d5ba63e333 fix(python): accept direct references and bzr+lp URLs, report a missing path, and keep editable cleared after an archive (#6650)
Follow-up to #6617. The version control dialog now accepts pip's direct references (name @ git+https://..., with extras) and bzr+lp:project. Installing from a local path that does not exist fails before pip runs, with the path in the message; a trailing [extras] is not part of the path, and a folder whose name has brackets is still a folder. Typing an archive path clears the editable choice, so a directory typed after it starts unticked.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:57:21 +08:00
l0ng-ai 8108b440a6 fix(dotnet): detect Microsoft.Testing.Platform test projects without the test SDK (#6671)
Run configuration detection treated a .NET project as a test project only when it referenced Microsoft.NET.Test.Sdk, so an xUnit v3 project on Microsoft.Testing.Platform (OutputType Exe, no test SDK) got only a .NET Project configuration and the gutter found nothing to run for its tests. parse_project now uses the evaluated project model's rules: IsTestProject true; a Testing Platform property on (IsTestingPlatformApplication, TestingPlatformDotnetTestSupport, EnableMSTestRunner, UseMicrosoftTestingPlatformRunner) or an xunit.v3.mtp-* package; or, unless IsTestProject is false, MSTest.Sdk or a test framework package (Microsoft.NET.Test.Sdk, MSTest, NUnit, xunit, xunit.v3, TUnit).

Fixes #6602
2026-11-28 14:49:16 +08:00
audichuang 4401ed3119 fix(clipboard): allow clipboard_text in Restricted Mode, like the other clipboard reads (#6658)
clipboard_text was the only clipboard command declared trusted, so in Restricted Mode the native read was refused and readClipboardPlainText() fell back to the WebView's own read: WebKit's Paste callout on macOS (and WebView2's prompt on Windows) appeared for the editor's right-click Paste. Reading the clipboard runs nothing from the project, and clipboard_image, clipboard_file_list and clipboard_has_* are already always. clipboard_text is now always too, as is the web shell's stub; a test pins all clipboard reads to always. Plugins still read through plugin_answer_clipboard, which stays trusted.

Co-authored-by: audichuang <[email protected]>
2026-11-28 14:46:43 +08:00
Deng Liuтаdengliu dbbdc4a085 fix(github): route gh commands through ide-host for remote projects (#6649)
The Pull Requests tool window failed in SSH, WSL and dev-container windows with "no project is open in this window": the gh_* commands were desktop commands in src-tauri and ran on the desktop, while the project lives on the remote host. The 11 gh_* commands move to crates/ide-host/src/ops/github.rs as project_host commands, so remote windows route them to openidea-server, where the repository, gh CLI and project-scoped GH_TOKEN are. gh_account_repos becomes outside_restricted so Clone Repository > GitHub keeps working without an open project, and the streaming gh_pr_* output channels are cleaned up as finite channels when the remote reply completes.

Co-authored-by: dengliu <[email protected]>
2026-11-28 14:44:06 +08:00
LU XIANGRUIтаwildcatDownstairs 85456e6930 fix(python): find conda outside PATH when creating environments (#6661)
Creating a conda environment failed with "conda is not installed" whenever conda was not on PATH (the Windows installers' default), even though the IDE listed that installation's environments. conda is now resolved from the base interpreter's own installation, then PATH, CONDA_EXE, the default install folders (including %ProgramData%) and the installations behind ~/.conda/environments.txt. On Windows it runs with the installation's DLL folders on PATH, as activation would. Discovery and terminal activation use the same lookup.

Closes #6652

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 14:36:59 +08:00
HandsomeXi b4d2859277 fix(build): give cmake --build one job per logical CPU (#6629)
Build Project, Build <target>, Rebuild and the generated CMake Build run configurations ran `cmake --build` without a job count, so the default Makefile generator compiled one file at a time. Every cmake build step now gets `-j <logical CPUs>` before a `--` separator; a count the profile's build arguments already set (-j, -jN, --parallel, --jobs) is left alone. CTest steps are unchanged.

Co-authored-by: HandsomeXi <[email protected]>
2026-11-28 14:36:10 +08:00
l0ng-ai ba880dac06 chore: v0.1.55 2026-11-28 11:10:37 +08:00
LU XIANGRUIтаwildcatDownstairs 0b1a675fab fix(python): install from disk never falls back to PyPI, editable only for a local directory (#6617)
Install from Disk resolved only paths starting with '.', and pip runs in a temporary folder, so a bare name like 'mylib' installed the PyPI package of that name. A typed relative path is now sent as './...' (resolved against the project) and '~/' expands to the home folder, so pip always gets an absolute path. Editable installs are offered and accepted only for a local directory: an editable clone of a repository would land in pip's temporary folder. The version control dialog accepts only vcs+scheme:// URLs, and an archive disables editable.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 11:09:48 +08:00
Vladislav Kuzmin 0b06d3313f test(ssh): send POSIX shell test scripts through stdin (#6620)
The POSIX command round-trip test passed the script to the local sh as an argument; on windows-latest that is Git for Windows' sh, whose argument handling dropped the a\b sample. The test now feeds the program to sh -s through stdin on every platform, still checking all samples and the exact stdout bytes, and reports the exit status and stderr when sh fails.

Fixes #6619

Co-authored-by: principalwater <[email protected]>
2026-11-28 11:09:33 +08:00
l0ng-ai ddaee1f5ce fix(host): keep a command's last output lines after it exits (#6625)
run_command stopped reading a finished command's output after 100 ms without a line, so on a busy machine the last lines (often the error a failed worktree setup script printed) were lost. It now reads until the pipes close, for at most a second. Sibling output loops already wait for the pipes to close.
2026-11-28 11:03:31 +08:00
Vladislav Kuzmin 623f1fa4e7 fix(ci): run language smoke for refactor providers (#6552)
src/editor/api.ts imports src/editor/refactorProviders.ts since #6520, so the frontend smoke loads it. Add it to the Language smoke push/pull_request paths and to the Changes step's smoke pattern so a change to it runs every language.

Co-authored-by: principalwater <[email protected]>
2026-11-28 11:01:33 +08:00
l0ng-ai 79f6476d52 fix: unique menu row keys, backend-only plugin points, Debug Server host hint (#6623)
Menu rows of one action repeated with object args (Run with Coverage, Profile... via run.withExecutor) shared a React key; repeated keys now get a suffix. The client defines the backend-only runConfigurations and locales plugin points so plugins contributing them no longer log 'has no client projection'. The Python Debug Server host hint now says loopback hosts listen on loopback only, matching how the listener binds.
2026-11-28 10:55:14 +08:00
Vladislav Kuzmin bd396485c2 feat(database): support DuckDB SQL and browse attached catalogs (#6254)
DuckDB sources get DuckDB's SQL dialect (highlighting, completion, formatting and resolution) and the database tree lists attached catalogs with their schemas, tables and columns. The JDBC bridge gains a catalogs command and catalog-scoped schema and table metadata, matched by exact catalog and schema names; tables in another catalog open and page through the source session. DDL that attaches, detaches or changes a catalog refreshes the tree.

Co-authored-by: principalwater <[email protected]>
2026-11-28 09:07:53 +08:00
Vladislav Kuzmin c04d9381be feat(database): add a Database Output tool window for SQL consoles (#6243)
SQL consoles and files get a Database Output bottom tool window. It follows the active editor, keeps result tabs and errors scoped to each console, and has a client selector (file name with its data source) for looking at another run, plus a button to open that client in its editor. Run and Explain reveal the current client's results while keeping editor focus; background completions and late Explain responses leave the selected client in view. Switching clients or destinations never re-runs SQL. Settings > Tools > Database can send results to Services instead.

Closes #6176

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:56:19 +08:00
Vladislav Kuzmin 45f6366b92 feat(database): explain queries on named DuckDB sources (#6244)
Explain Plan now works for DuckDB data sources connected through JDBC. The statement runs as EXPLAIN (FORMAT JSON) in the console's session (so temporary tables resolve), and the physical plan is shown, falling back to the optimized or logical plan when explain_output asks for those; operator details become node properties. A script with several statements is checked with json_serialize_plan first and refused. Other custom JDBC sources still have no Explain Plan.

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:49:45 +08:00
l0ng-ai fb0b2d6a5f fix(ssh): run remote commands with sh whatever the login shell (#6612)
sshd runs every exec request through the account's login shell. The commands the IDE sends (server probe and install, connection test, run targets, command tunnels) are POSIX shell, so with fish as the login shell they failed with stderr only and opening a remote project never got past the probe.

Exec requests now send sh -c '<script>', a plain command to every shell, quoted so that fish reads the same text as a POSIX shell (quotes and backslashes written outside the single quotes). The login shell still starts first, so its environment is inherited; interactive terminals keep the login shell itself.

Fixes #6200
2026-11-28 08:44:47 +08:00
LU XIANGRUIтаwildcatDownstairs ddea7e5ec5 feat(python): install packages from version control or a local directory (#6601)
A + button in the Python Packages tool window offers Install from Version Control… and Install from Disk… (with Browse), both with Install as editable (-e). A plain https://, ssh://, git:// or git@host:path URL gets pip's git+ form; git+… and other vcs+ URLs pass as they are. sdk_python_pip takes an editable flag that adds -e (pip and uv pip); text starting with - is still refused, so no other pip option can be passed.

Closes #6531

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 08:37:01 +08:00
LU XIANGRUIтаwildcatDownstairs 3747a8a63f feat(python): show package documentation in the Python Packages tool window (#6600)
When the pane has a package's PyPI details (a search result, or an installed package after Show PyPI Details), it also shows the project's links (its PyPI page, home_page and project_urls; http(s) only, duplicates dropped) and its long description: rendered Markdown (sanitized, as in hover docs) when description_content_type is Markdown, plain text otherwise. Links open in the browser. Everything comes from the JSON API response the pane already loads.

Closes #6530

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 08:31:32 +08:00
l0ng-ai 0a8fea1876 fix(agents): take one lock at a time when checking for pending input (#6610)
emit_attention_if_input_pending held the permissions guard, a temporary living to the end of the statement, while taking the task state lock. approve_pending takes them the other way round, so a permission request and a bypass-approvals config change on another thread could deadlock. The check now releases the permissions lock before reading the status.
2026-11-28 08:29:23 +08:00
Deng Liuтаdengliu ccc0eb1f54 fix(agents): settle in-flight turns cleanly on manager shutdown (#6606)
Closing a project or quitting while an agent turn was in flight left the task Failed with "The agent process exited.": shutdown killed the peer, and the still-running turn then woke up, failed the task and overwrote what shutdown had saved. Restart only normalizes Running/NeedsInput/Starting, so the Failed state stuck.

A shutdown epoch on the manager now marks work started before a shutdown (turns, session opens, permission and form requests, notifications, delayed saves); that work exits quietly instead of failing the task or rewriting its file. A peer still mid-handshake is tracked and killed by shutdown, and interrupted tasks settle to Ready. The manager stays usable after a shutdown (trust revoked and granted again).

Co-authored-by: dengliu <[email protected]>
2026-11-28 08:28:11 +08:00
l0ng-ai 54dadc4605 fix(vcs): keep a diff tab's scroll position across tab switches (#6609)
Switching away from a Show Diff tab unmounted the diff viewer, so switching back rebuilt it at the top. The single-file and combined diff kinds are now kept alive like other recently used tabs, so they come back where they were left (scroll, caret, expanded lines) without reloading the revisions.

Fixes #6394
2026-11-28 08:25:26 +08:00
l0ng-ai 6fba4671e6 fix(editor): drop Pinyin syllable spaces when the input source switches mid-composition (#6608)
Switching macOS Pinyin to English while composing commits the composition as displayed, with the spaces the IME shows between syllables, so typing nihao left "ni hao" in the editor. When the commit is exactly the ASCII composition text, the editor now rewrites it to the letters typed, at every cursor that took it, in the same undo step. Candidate commits are unchanged. The commit rule moves to platform/ime so the terminal and the editor share it.

Fixes #6393
2026-11-28 08:16:39 +08:00
l0ng-ai d5058b930b fix(macos): stop restoring full screen from saved window state (#6607)
Window state is kept per label, and project-N labels are reused by other projects. A full-screen flag saved once came back on every later project window, each claiming its own Space, some while still hidden and blank. macOS no longer saves or restores the full-screen flag; a window that was full screen comes back maximized. Windows and Linux are unchanged.

Fixes #6430
2026-11-28 08:14:13 +08:00
l0ng-ai 44aab11296 fix(java): open output-directory class files decompiled (#6605)
Opening a .class under target/classes or build/classes jumped to the project .java it was built from. The resolver now returns the class document itself, so the compiled class opens read-only as decompiled text. Library classes in archives are unchanged.

Fixes #6410
2026-11-28 08:11:48 +08:00
l0ng-ai fcd24885c1 fix(build): select Maven projects by coordinates when processing launch resources (#6604)
The launch resources step selected changed modules by their Maven basedir relative to the reactor root. On Windows the basedir need not share a spelling with the opened folder, so the absolute path reached -pl and Maven could not find the project in the reactor. It now selects them by groupId:artifactId.

Fixes #6409
2026-11-28 08:08:24 +08:00
Vladislav Kuzmin 4b3717618f fix(database): isolate JDBC console sessions (#6553)
Two SQL consoles on one JDBC data source waited on the same connection, so a long query, cancellation or close in one blocked the other. The JDBC bridge now multiplexes one connection per console inside the existing bridge JVM (capped at 32, with bounded reply buffers), and result reads, cancel and close are routed to the originating console's connection. DuckDB console connections share the database and its attachments with separate temporary tables and session settings; anonymous SQLite and H2 databases keep one shared connection so their contents stay visible.

Fixes #6484

Co-authored-by: principalwater <[email protected]>
2026-11-28 08:05:59 +08:00
Vladislav Kuzmin 8fd5ee382d fix(database): isolate PostgreSQL manual transactions by SQL console (#6482)
Two PostgreSQL consoles on the same data source shared one manual transaction, so one console could see and commit the other's pending work. Each console now owns its manual transaction: Commit, Roll Back, Stop, result reads and close act on the originating console, retained results keep their transaction until the last reference closes, and a statement for a lost transaction fails before executing. The pool reserves capacity for ordinary work; up to two manual transactions can hold a connection per target, and a third gets a message on how to free a slot. Auto-commit and the transaction-pooler read-only path are unchanged.

Fixes #6445

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:57:17 +08:00
Vladislav Kuzmin 3a3b2e424a perf(remote): reuse the verified release archive for SSH installs (#6288)
The first SSH install recompressed the unpacked server with fast gzip before uploading it. The release download now keeps its gzip next to the cached binary, and the SSH install sends that archive when it decodes to exactly the selected binary (size and BLAKE3 hash); custom binaries and missing or mismatched archives fall back to the existing upload. Container and WSL installs are unchanged. For the Linux arm64 payload this sends about 51 MB instead of 66 MB.

Fixes #6283

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:44:18 +08:00
Vladislav Kuzmin b9d0e28f7a fix(database): bound idle waits for ClickHouse HTTP responses (#6456)
A ClickHouse HTTP response that stalled (a relay holding the reply, a dropped connection) left the console showing Running forever. The built-in driver now stops waiting after 600 seconds without response data and reports that the outcome is unknown, with the query_id; it does not replay or cancel the statement. Reading another chunk restarts the timer, and the Advanced property http_read_timeout (seconds) changes the interval.

Fixes #6435

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:39:50 +08:00
Vladislav Kuzmin 53627ea2e9 fix(database): reject session SET on stateless ClickHouse HTTP (#6442)
ClickHouse accepts a standalone SET over HTTP, but without a session the setting is gone before the next request, so a console script silently ran its later statements with other settings. With use_http_session=false the driver now refuses a session-scoped SET before sending it and says to use a session or query-level SETTINGS; named sessions, SETTINGS clauses and SET DEFAULT ROLE are unchanged. The ClickHouse splitter now also treats # line comments and nested block comments as comments.

Fixes #6432

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:38:29 +08:00
Vladislav Kuzmin 55366a2a31 test(build): report Gradle output when fixture preparation fails (#6564)
When the Gradle model fixture could not be prepared, the test panicked with only the unsupported reason and hid the build error. It now appends the last 150 lines of the build output from both streams, with a unit test for the tail.

Fixes #6555

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:37:09 +08:00
Deng Liuтаdengliu 0b9610fe69 feat(appearance): add a project color strength setting (#6592)
Settings › Appearance › Use project colors in main toolbar gains a Project color strength slider (10–70%) that scales the header's project colour wash. The default stays at today's 22%, so nothing changes unless the slider is moved.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:34:23 +08:00
l0ng-ai 43e3575eb2 test(settings): expect the Thymeleaf inspection group (#6599)
#6598 added the Thymeleaf inspection group; the inspections tree test still listed the old groups.
2026-11-28 07:33:01 +08:00
Deng Liuтаdengliu bc4a422424 feat(remote-dev): show the remote host in grouped project window tabs (#6577)
Window group tabs of remote development windows now show a flat 'SSH · host' (WSL, Dev Container) label after the project name, with the full host and remote path in the tab's tooltip, and take their name from the remote project's display name instead of the window title. WindowTab carries the connection's host, and remote connections keep the project's display name.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:26:55 +08:00
Deng Liuтаdengliu 7ccaa10496 feat(remote-dev): distinguish remote windows and project switcher entries (#6557)
Remote projects in the project switcher and the welcome screen's recent list now carry a server badge on their avatar and an 'SSH · host' (WSL, Dev Container) label above the remote path, with search highlights split between host and path. The Remote Host status bar item gains the remote icon, and shows its disconnected state as a warning-coloured label.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:21:32 +08:00
Deng Liuтаdengliu b5e45ca98b feat(agents): consolidate session stats into a Session Info popover (#6563)
The agent status strip showed context usage, last-turn tokens, every usage-limit window and session cost inline. It now shows the context ring and percentage, plus any usage limit at 80% or more in its warning tone; everything else moves into one Session Info popover with a Context Window bar (reserved-for-response segment, System and User Context breakdown with token counts on hover), the last turn's tokens, usage limits and cost. Free space and deferred categories are skipped by name for Claude Code.

GitHub Copilot sessions now report a context breakdown through _openidea/context_usage (session.metadata.getContextAttribution, with contextInfo and usage_info fallbacks), accumulate AI-credit spend across turns and subagents, keep session cost across usage updates without cost, map /compact to session.history.compact, and label quota windows Chat, Completions and Premium requests.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:19:50 +08:00
Deng Liuтаdengliu 6faff1b1a8 feat(agents): autocomplete slash command arguments and show inline hints (#6567)
Typing a slash command and a space (/skills, /sandbox, /remote, Codex's /goal) now offers its subcommands with descriptions, chains /skills info and /skills remove into the session's active skills, and shows a muted inline argument hint after /command until an argument is typed. AgentCommand keeps structured choices from Copilot's commands.list, Codex builtins and ACP available_commands_update, with a fallback that parses literal [a|b|c] hints. Enter on /skills and /mcp still opens the session pickers; Tab or a trailing space enters subcommands.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:14:43 +08:00
Vladislav Kuzmin 1edfa9180b test(profiler): wait for profiled loop work before stopping (#6588)
a_stopped_run_still_writes_its_profile sent SIGINT right after the fixture printed done, which could land before the loop ran, so the profile held only the initial fib(22) calls and the 'the loop ran' assertion failed. The fixture now prints looped after its first fib(18), and the test stops the run only after reading it, then checks for both completed passes.

Fixes #6585

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:09:47 +08:00
Vladislav Kuzmin b15c56cdb0 test(project): wait for the updated attached-root index (#6587)
attached_projects_keep_their_own_excluded_folders waited for the attached project's exclusion settings to change, then for the index to go idle. The settings become visible before the background refresh queues the rescan, so the index could be idle with its previous results. The test now waits for the newly included file to appear in the index.

Fixes #6584

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:09:15 +08:00
audichuang 91ff5c8a15 feat(thymeleaf): warn on fragment expressions naming a missing template or fragment (#6598)
Templates under src/main/resources/templates get a warning (underline and Problems) on a fragment expression whose template does not exist or does not define the fragment, as the inspection Thymeleaf > Unresolved template and fragment references. A fragment counts as defined by th:fragment, th:ref, an element of that name, or an id. It stays silent where names cannot be resolved as Spring Boot's defaults do: spring.thymeleaf.prefix or suffix set in application.properties / .yml, missing templates outside the project folder's own templates directory, ~{_}, ?: fallbacks, expression names, relative names and comments. Template names get .html unless they end in an extension Thymeleaf recognizes, which also fixes Go to Declaration on names with a dot.

Part of #2889

Co-authored-by: audichuang <[email protected]>
2026-11-28 07:07:06 +08:00
Vladislav Kuzmin 929b6837f9 fix(agents): keep archived tasks from resuming on a permission reply (#6586)
Archiving a task cancels its pending permission request. The reply handler checked whether to resume the task, released the state lock, then reacquired it to write Running; an archive finishing in between left running on disk, so the task came back outside the archive after a restart. The handler now records the answer and resumes the task under the same state lock, so a later archive still takes effect. A regression test overlaps settlement with archiving and checks the persisted Archived status and the recorded answer.

Fixes #6583

Co-authored-by: principalwater <[email protected]>
2026-11-28 07:05:44 +08:00
Deng Liuтаdengliu d1af5f656a fix(windows): include remote development windows in Merge All Project Windows (#6593)
Merge All Project Windows only collected windows with a local project, so remote development windows were left out. Candidates now include every local or remote project window (welcome and LightEdit windows stay out), selected by a unit-tested merge_candidates helper in ide-workspace. A member that shares a native tab group or frame with a window outside the merge is split from it first, so that window is neither pulled in nor left hidden.

Co-authored-by: dengliu <[email protected]>
2026-11-28 07:02:55 +08:00
audichuang 604e9348f2 fix(vcs): offer New Changelist and Move under Group By Staging State (#6596)
With the staging area off and the Commit tool window grouped by Staging State, the Staged / Unstaged nodes carry no changelist, so Move to Another Changelist… was hidden and New Changelist… (only on changelist headers) was unreachable. Their nodes and files now offer Move to Another Changelist… in the first group and New Changelist… next to Create Patch and Shelve. Nothing changes with the staging area on.

Fixes #6422

Co-authored-by: audichuang <[email protected]>
2026-11-28 07:01:37 +08:00
audichuang 9592b9ee1b fix(vcs): Jump to Source in the comparison window opens the file in the project window (#6595)
Jump to Source from a diff in the Compare with Branch window went to the comparison window's own editor area, which stays hidden until Show Diff, so nothing appeared. The comparison window now hands openFile to the project window's editor, as the diff window does, for files in any folder of the project (workspace projects included); files outside the project still open in the comparison window.

Fixes #6405

Co-authored-by: audichuang <[email protected]>
2026-11-28 06:59:28 +08:00
Paweł SzymańskiтаPawelSzymanski89 c658b3eb88 fix(notifications): stop leaking a thread per macOS system toast (#6597)
With an action handler registered, tauri-plugin-notification shows every macOS toast on a thread of its own that waits for a click. Toasts that are never clicked keep their thread and NSUserNotificationCenter work alive, so the app slowly gets laggy.

macOS now skips the action handler, so toasts are delivered without tracking; clicking one activates the app instead of focusing the exact window that raised it. Windows and Linux keep per-window focus.

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-28 06:57:19 +08:00
audichuang cc5d9d95e4 feat(vcs): bold the current revision's lines in the annotate gutter (#6594)
Lines last changed by the file's current revision are drawn bold in a last-commit colour in the Annotate gutter. The current revision is the last commit to the file at HEAD, or at the annotated revision for Annotate Revision and the diff/merge panes; it is read with vcs_log after the gutter paints and again when HEAD moves. The colour is a new token, --git-annotations-last-commit, listed under Color Scheme > Git > Annotations > Last commit and imported/exported as ANNOTATIONS_LAST_COMMIT_COLOR.

Refs #6397

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:55:03 +08:00
Vladislav Kuzmin 75a15b7eed fix(database): isolate ClickHouse console sessions (#6455)
The built-in ClickHouse HTTP driver gives each SQL console its own named session: a second console finishes while the first one runs, and repeated statements in one console keep their SET values and temporary tables. Result paging, Explain and Stop use the same console identity, and closing the console's last editor or result releases it. Requests without a console stay stateless and can run concurrently. The PR also carries the TODO layout and bookmarks fixture fixes from #6507/#6458.

Closes #6433

Co-authored-by: principalwater <[email protected]>
2026-11-28 05:50:23 +08:00
audichuang b2998cb37a fix(project-tree): scroll the inline name field into view when it starts (#6590)
In a folder scrolled so its top was out of view, New > File / Directory / Package showed no name field and keystrokes went to the tree's speed search: the tree is virtualized and the placeholder row was never mounted. Starting an inline edit (new item or rename) now scrolls its row into view through a new TreeHandle.scrollIntoView, leaving the viewport alone when the row is already visible.

Closes #6461

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:43:05 +08:00
audichuang 5c131edb7e feat(http-client): go to the Spring endpoint from a RestTemplate or WebClient URL (#6581)
Go to Declaration on a literal URL in a RestTemplate, WebClient or RestClient call (the *For* methods, put, delete, exchange with HttpMethod.X, and the fluent .get()/.method(HttpMethod.X).uri(...)) in Java and Kotlin now opens the matching controller method, reusing the Feign controller index, path matching and service filtering. A bare host narrows the targets to that spring.application.name, and falls back to every matching endpoint when no module has that name. With no match, Cmd-click still opens the URL.

Refs #3882

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:41:20 +08:00
audichuang bb8906edb8 feat(vcs): Colors submenu in the Annotate Options menu (#6582)
The Annotate gutter's Options menu gets a Colors submenu with Author, Order (the default, tint by commit order) and Hide. Author gives the authors, sorted by name, the palette colours in turn. The choice is kept in localStorage and applies to every annotated editor, like the column and Names options.

Refs #6397

Co-authored-by: audichuang <[email protected]>
2026-11-28 05:40:40 +08:00
Deng Liuтаdengliu 2e3b087db7 fix(remote-dev): apply custom project color on remote windows and tabs (#6576)
Change Project Color… did nothing in a remote development window: the window group's tab had no root, because it only looked up local projects. Remote windows now report their remote location (ssh://host/path) as the tab root, and the workbench reads the custom colour under the same key the project popup, Welcome and the window tabs store it, so the tab, title bar avatar and frame tint update. Window tabs refresh when a remote session connects or disconnects.

Co-authored-by: dengliu <[email protected]>
2026-11-28 05:38:40 +08:00
l0ng-ai 0c5f1ffabf fix(ci): rebuild the execution-output plugin component after formatting its source (#6591)
#6572 rustfmt-formatted the fixture's source, which changes its source fingerprint, so plugins/build.sh --check reported dist/plugin.wasm as stale. Rebuilt with plugins/build.sh.

Refs #6569
2026-11-28 05:35:34 +08:00
Vladislav Kuzmin 0a9055b40d test(clipboard): serialize Windows clipboard fixtures in Nextest (#6574)
Nextest runs each test in its own process, so the per-process SERIAL mutex of the three Windows clipboard tests from #6549 did not keep them from writing the system clipboard at the same time. A Nextest test group with one slot runs them in turn while other tests stay parallel.

Closes #6571

Co-authored-by: principalwater <[email protected]>
2026-11-28 05:32:15 +08:00
Bert Verhelstтаbertyhell 8776bf536f feat(database): add and drop keys and indexes from Modify Table (#6578)
Modify Table can change an existing table's primary key, add and drop unique keys, and create and drop indexes, each statement shown in the Preview. The index catalog query now marks the indexes that enforce a primary or unique key (DbIndexInfo.key), so they are listed under Keys and dropped with their constraint instead of a drop index the server rejects. Engines that cannot express a change don't offer it (SQLite: indexes only; Snowflake: primary key only). Existing keys and indexes are kept or dropped, not edited. The tree's Drop of a SQL Server index now emits drop index ix on schema.table.

Part of #6307

Co-authored-by: bertyhell <[email protected]>
2026-11-28 04:19:28 +08:00
Vladislav Kuzmin 9cc781717d fix(coverage): align headers while the tree scrolls (#6506)
#6468 increased the Tree's end inset while its scrollbar is visible, so in a narrow Coverage dock the percentage cells shifted 2 px from their headings. The Coverage header now uses the matching inset.

Closes #6499

Co-authored-by: principalwater <[email protected]>
2026-11-28 04:14:12 +08:00
Vladislav Kuzmin 8f1e95e5a2 test(diff): align navigation fixtures with the initial difference (#6505)
#6471 opens a diff at its first change when the caller gives no line, so the cross-file navigation test clicked Next once too often before checking the boundary hint. The tests that navigate from the top now pass an explicit starting line.

Closes #6500

Co-authored-by: principalwater <[email protected]>
2026-11-28 04:14:03 +08:00
l0ng-ai e49c634064 fix(ci): expect commit fixOnCommit in default settings and format the execution-output fixture (#6572)
#6540 added vcs.commit.fixOnCommit, so the defaults JSON shape test now lists it. #5131 left the execution-output plugin fixture unformatted, which failed the plugin crates' cargo fmt --check.
2026-11-28 03:38:37 +08:00
Vadim LazukтаInf1mum 4e82599c49 feat(dotnet): show solution tree discovery states (#6566)
While the .NET workspace scan runs, or after it failed, the Project view showed nothing where the solutions would appear. One placeholder .NET root now carries the state as grey detail text (Scanning… / Scan failed); idle and empty still registers no root, and a failed scan still retries on next use.

Refs #5635

Co-authored-by: Inf1mum <[email protected]>
2026-11-28 03:26:26 +08:00
Akbar Husain e08de6771d feat(mcp): add optimize_imports tool (#6562)
reformat_file's description pointed agents at an optimize_imports tool for import-only cleanup, but none was registered. optimize_imports runs the existing organize-imports path (including the Ruff fallback for Python) on the given files without reformatting and returns the same capped unified diff as reformat_file. Documented in the English and Chinese MCP guides.

Co-authored-by: akbar1214 <[email protected]>
2026-11-28 02:24:34 +08:00
Bert Verhelstтаbertyhell d31a22b5dd perf(editor): let Alt+Enter and refactorings go before Code Vision usage counts (#6560)
Code Vision usage counts run project-wide searches on the same language server and only gave way to Go to Declaration, so Alt+Enter, Refactor menu actions, Refactor This, code actions by kind and Apply Quick Fix queued behind them on a busy server (jdtls on a large project).

The foreground mark now covers every request the user waits for: those requests mark themselves while they ask the server, and the usage counts and implementation gutter markers cancel in-flight work and resume afterwards. Refactor menu actions show a pending hint while the server is busy.

Refs #6381

Co-authored-by: bertyhell <[email protected]>
2026-11-28 02:20:06 +08:00
Bert Verhelstтаbertyhell cead5f08f7 fix(terminal): expand ~ to the remote home in remote windows (#6559)
In a remote window (WSL, SSH, dev container), a ~/ path in the terminal never became a Ctrl+hover link, and a ~/...:12 link opened only through the project-wide basename search, so it could open a same-named file in the project. Terminal links took ~ from the desktop's home only, and had no home at all in a remote window. Both now use the home of the machine the shell runs on: the desktop's home in a local window, and $HOME (else %USERPROFILE%) of the project host in a remote window, read through run_system_env, which runs on that host.

Closes #6246

Co-authored-by: bertyhell <[email protected]>
2026-11-28 02:13:02 +08:00
l0ng-ai 1fc9a9f5d5 feat(vcs): settings to hide the change markers in the gutter and on the scrollbar (#6558)
Editor > General gets a Gutter section with "Highlight modified lines in the gutter" and, under it, "Highlight modified lines in error stripe on the scrollbar". Both are on by default; turning off the first hides the scrollbar marks too, and the change applies to open editors right away through a changeMarkerDisplay facet set from the prefs compartment.

Fixes #6539
2026-11-28 02:01:47 +08:00
Deng Liuтаdengliu 11a8152988 feat(remote-dev): show used and total disk space in resources dashboard (#6554)
The Disk card in Remote Host Resources replaced total capacity with live read/write throughput once disk I/O counters arrived, leaving only the free space in its header. The header now shows used / total like the Memory card, and the subtitle and status bar tooltip keep the free space beside the read/write rates (or the used percentage when I/O counters are unavailable).

Co-authored-by: dengliu <[email protected]>
2026-11-28 01:53:16 +08:00
LU XIANGRUIтаwildcatDownstairs 10b459268e feat(python): set Django up in the Python Console of a Django project (#6543)
In a Django project the Python Console started a plain interpreter, so importing models failed with ImproperlyConfigured. When the project's manage.py sets DJANGO_SETTINGS_MODULE, the console now starts in manage.py's directory and its driver calls django.setup() with that settings module (one already in the environment wins, as for manage.py). On Django 5.2+ it also defines what manage.py shell imports automatically (the models, settings, timezone, ...) and keeps those names out of the Variables pane. The header shows the Django version; if setup fails, the traceback is printed and the console works as before.

Closes #6536

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:51:13 +08:00
LU XIANGRUIтаwildcatDownstairs 382c22cfc3 feat(python): complete Django field lookups and offer django-types for model typing (#6545)
In Model.objects.filter( (and exclude, get, get_or_create, update_or_create, also after other queryset calls) the keyword completes the model's fields: pk, fields inherited from project base models, and reverse relations by related_name or the lowercase model name. __ follows a relation, and after a plain field come its lookups, with date and time transforms for date fields. Models are read from the project's models.py files and read again when one changes.

When the project's interpreter has Django but neither django-types nor django-stubs, a banner on Python files offers to install django-types (pip as a background task, then the type checker restarts), so basedpyright types managers and model fields.

The stubs check and the manage.py, URL-name and model lookups run again once indexing ends, since on a fresh open they can run before the index has the project's files.

Closes #6541

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:50:02 +08:00
LU XIANGRUIтаwildcatDownstairs 7bb69e353d feat(python): complete and navigate Django URL names in reverse() calls (#6544)
In Python files, the first string argument of reverse(, reverse_lazy(, redirect( and resolve_url( completes URL names, and Go to Declaration on it opens the path(..., name=...) entry. Names come from the project's urls.py files under their module's app_name (shop:product), with the file shown beside each, and are read again when a urls.py changes. They rank above the parameter names the language server suggests in the string.

Closes #6537

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:48:54 +08:00
LU XIANGRUIтаwildcatDownstairs 988f93be46 feat(python): run manage.py tasks from Run Anything with command completion (#6542)
Adds Run manage.py Task… (django.runManageTask), which opens Run Anything with manage.py typed. A Run Anything provider recognises manage.py lines (also ./manage.py and python manage.py), completes the command word from manage.py help (read once per project, shown with the app that defines each command), and runs the line with the project interpreter in manage.py's directory in a terminal-emulating Run tab, so createsuperuser and shell can prompt. runAnything.show now takes an optional initial line.

Closes #6535

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 01:48:00 +08:00
Muuтаmuutot 494dd61193 feat(settings): import JetBrains live templates (#6546)
Import Settings now reads templates/*.xml from a JetBrains settings archive or settings folder and, after confirmation, merges the templates (group, abbreviation, description, body, variables and defaults, contexts, deactivated state) into the custom live templates under stable jetbrains.* ids, so importing again updates rather than duplicates. Built-in and unrelated custom templates are kept.

Contexts are read as IDEA writes them: the full context id first (JAVA_SCRIPT, SHELL_SCRIPT), then its shorter prefixes down to the language (JAVA_STATEMENT, Python_Class, JS_STATEMENT, KOTLIN_TOPLEVEL), OTHER as everywhere, and comment or string contexts expand outside code. Templates whose contexts don't map to a language are listed as not imported, never made global; expressions OpenIDEA can't evaluate are listed and kept as text.

Co-authored-by: muutot <[email protected]>
2026-11-28 01:39:19 +08:00
audichuang cbabb5e9b5 fix(debug): cancel pending debug builds and launches when closing a project (#6282)
Closing a project while a debug launch was still starting (a Cargo build before CodeLLDB, or the adapter spawning and connecting) didn't stop it, so the adapter started for the closed project once the build finished: nothing between debug_start and session registration was tied to the project's lifetime.

Project now has a closed token that debug_start passes down. Closing the project cancels the Cargo build (killing its process tree, through a Job object on Windows) and the adapter launch.

Co-authored-by: audichuang <[email protected]>
2026-11-28 01:35:15 +08:00
GuoYuтаguoyucode 75997ae0ee fix(clipboard): read and write the Windows clipboard one call at a time (#6549)
Concurrent clipboard reads from the project tree raced on the Windows clipboard, which only one caller can open at a time, so a paste could fail with an access error. All Windows clipboard functions now hold a process-wide lock, and the project tree joins an OS clipboard refresh that is still running instead of starting another read.

Fixes #6388

Co-authored-by: guoyucode <[email protected]>
2026-11-28 01:25:36 +08:00
Muuтаmuutot 81df8f2649 feat(python): apply Ruff safe fixes on save and commit (#6540)
Adds a "Fix safe lint issues on save" Ruff setting that runs ruff check --fix-only on Python files when saving, and a commit check that applies the same safe fixes before committing. Safe fixes run separately from formatting and Format on save.

Also translates the new "No safe lint fixes to apply" message and drops the replaced on-save hint from the ko/ru/tr catalogs.

Co-authored-by: muutot <[email protected]>
2026-11-28 01:23:52 +08:00
l0ng-ai 26992ec4ce fix(syntax): comments between a start tag's attributes are not XML syntax errors (#6551)
Without an XML language server, the built-in parser's syntax check flagged a comment inside a start tag, which is read as whitespace. For the XML grammar the check now runs on the text with such comments blanked (lines and UTF-16 columns kept); an unclosed comment or an unterminated tag still reports.
2026-11-28 01:03:23 +08:00
Akbar Husain 2c22574be0 fix(lsp): drop LemMinX's comment-in-start-tag error in XML (#6548)
XML files can keep attributes commented out inside a start tag (JGroups' configs do). Such a comment is accepted as whitespace, but LemMinX (Xerces) stops at <!-- and reports the whole tag as ElementUnterminated. That diagnostic is now dropped only when the reported tag is well-formed with its comments removed; real parser and schema errors stay.

Co-authored-by: akbar1214 <[email protected]>
2026-11-28 01:00:09 +08:00
LU XIANGRUIтаwildcatDownstairs 93368d4379 feat(profiler): profile Python runs with cProfile (#6512)
Profile on a Python configuration runs it under cProfile from the standard library when py-spy can't sample without root (always on macOS), or when Settings > Python > Profiler chooses cProfile. Scripts, modules and pytest configurations run with their own interpreter; stopping the run still writes the snapshot, which opens in the profiler view.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 00:54:42 +08:00
l0ng-ai 14741101bd perf(agents): don't keep the slash command list of archived tasks (#6528)
Each saved task kept the slash commands its agent last offered (up to ~200 entries) in memory and in the task list, archived ones included. Archiving now drops the list and tasks loaded archived start without it; completion for a task without a list uses what its agent last offered in the project.
2026-11-28 00:47:38 +08:00
l0ng-ai db60deede5 perf(agents): read a task's conversation from disk when it is first needed (#6527)
Opening a project parsed every saved agent task in full and kept every conversation in memory for the whole session, archived ones included. Startup now decodes only each task's own fields; the conversation and turn checkouts are read from the task file on first use. A conversation that cannot be read shows empty and is never saved over. agent_entries runs on the blocking pool since its first call parses the file.
2026-11-28 00:46:31 +08:00
l0ng-ai ab2a7767c7 feat(plugins): plugin commands can run a configuration through the plugin's executor (#6547)
The Run/Debug with <title> actions of a plugin executor took only an object argument, while a plugin command passes text, so a plugin's own entry could start a configuration only as a plain run without the executor's Java agent. They now take a configuration id, or a services.context / services.toolbar command's argument as it came (the first selected service's configuration).

Fixes #6516
2026-11-28 00:20:48 +08:00
LU XIANGRUIтаwildcatDownstairs 49c917880d feat(python): find usages and rename for pytest fixtures (#6520)
Find Usages and Rename on a pytest fixture (its definition or a test parameter that requests it) now cover every test and fixture that requests it by parameter name, including conftest.py fixtures used across the directory tree, overrides and usefixtures markers.

Closes #6513

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-28 00:15:16 +08:00
l0ng-ai f0db09aca5 fix(java): remove jdtls temporary files left in the workspace by earlier versions (#6538)
A workspace whose path has a space (every workspace on macOS) keeps jdtls' temporary files in the system temp folder, but the old <workspace>/.tmp was never read again, and a workspace in use is never removed as unused. Each jdtls start now removes that folder when the temporary files live elsewhere.

Fixes #6515
2026-11-27 23:54:53 +08:00
LU XIANGRUIтаwildcatDownstairs 979cce1175 feat(python): show matplotlib figures in a Plots tool window (#6529)
Python runs, debug sessions and the Python Console get MPLBACKEND pointing at a small bundled Agg backend (unless the run or the environment already sets it). plt.show() saves each open figure as a PNG in the project's cache folder; a watcher sends PlotAdded and the Plots tool window lists the figures with thumbnails, the image viewer, save, copy and delete. Settings > Python > Plots turns it off.

Closes #6514

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 23:53:40 +08:00
Muuтаmuutot faa7571038 feat(scratch): add New Scratch Buffer (#6525)
New Scratch Buffer (NewScratchBuffer, no default shortcut) cycles through buffer1.txt to buffer5.txt in the scratches folder: an existing buffer is opened with its contents (matched case-insensitively), a missing one is created empty. Listed in the keymap presets and the scratch guide.

Co-authored-by: muutot <[email protected]>
2026-11-27 23:40:52 +08:00
Deng Liuтаdengliu 264bf6969f feat(remote-dev): add remote host resource indicator and dashboard (#6425)
A remote window (SSH, WSL, Dev Container) shows a compact CPU and memory indicator beside the connection status; network and disk badges appear only when saturated. Clicking it, or Show Remote Host Resources, opens a dashboard with 60-second sparklines for CPU (cores, load), memory, network (with RPC round-trip latency) and disk (I/O and free space), the OpenIDEA processes on the host grouped by kind, and the top other host processes.

End Process asks for confirmation naming the process and PID, and ends only processes in the backend's own tree. Linux /proc and cgroup v2 limits are read for containers.

Co-authored-by: dengliu <[email protected]>
2026-11-27 23:34:21 +08:00
Vadim LazukтаInf1mum 66e17df216 feat(dotnet): show discovered solutions and projects as project-view tree nodes (#6224)
The Project view lists the discovered .NET workspace above the project folder: a Solution '<name>' group per solution with a leaf per project, and standalone projects as roots of their own. Each leaf is the real project file, so run/debug, build, selection and Select In work on it, and the same file still shows in its own folder.

The shared workspace scan starts only when the file index holds .sln, .slnx or project files; the check retries once the index settles, so a fresh open still gets the nodes, and a workspace without .NET is never scanned at open. Project view roots gain an optional file leaf for this.

Co-authored-by: Inf1mum <[email protected]>
2026-11-27 23:17:00 +08:00
LU XIANGRUIтаwildcatDownstairs 4ff5739854 feat(notebook): show the running kernel's variables in a Jupyter Variables tool window (#6517)
A Jupyter Variables tool window (bottom, under the stripe's overflow until first opened; also in Find Action) lists the variables of the last active notebook's kernel: name, type and a truncated repr, hiding private names, modules and IPython's own names. It refreshes after a run, a kernel restart and a switch of notebook, and never starts a kernel.

The variables are read with a silent execute_request carrying a user expression (no output, history, execution count or busy/idle status), only while the kernel is idle; a run started meanwhile waits for it, bounded to 10 seconds. A notebook tab restored at startup picks up its session once it opens.

Closes #6508

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 23:02:19 +08:00
Muuтаmuutot a0c03447a0 feat(editor): add Transpose action (#6524)
Transpose (EditorTranspose, no default shortcut) swaps the code points before and after each caret and moves the caret past them; at a line end it swaps the line's last two code points. With several selections it rotates their texts (the rightmost moves to the leftmost) and keeps each replacement selected; mixed carets and selections do nothing. Listed in the IntelliJ and VS Code keymap presets and documented in the editor guide.

Co-authored-by: muutot <[email protected]>
2026-11-27 22:51:50 +08:00
Vladislav Kuzmin c4e0900485 test: keep the stale Replace All buffer outside the project watcher and fix Windows path tests (#6498)
The Replace All fixture wrote its external change inside the watched project, so the watcher sometimes refreshed the clean buffer before the stale-buffer path ran. The stale file now lives just outside the project and is reached through a directory search scope; the test also checks the unsaved replacement text.

Includes the Windows fixes from #6459/#6460: Cobertura keeps rooted (drive-less) paths instead of joining them onto the checkout's drive, and the tsconfig plugin shim test compares the decoded path.

Closes #6494

Co-authored-by: principalwater <[email protected]>
2026-11-27 22:36:22 +08:00
Dimas Avrian Fachriza a42f13edc2 fix(editor): keep color swatches while typing so the gutter doesn't shift (#6519)
Language server and plugin color fields were cleared on every document change, so the color gutter collapsed on each keystroke until the debounced documentColor request answered, shifting the code left and right. Existing colors are now mapped through the change; only a color whose text the edit touches is dropped until the provider answers again.

Closes #6518

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 22:33:39 +08:00
l0ng-ai 18d6041f2f fix(ci): run language smoke when LSP snippet conversion changes (#6523)
The breakpoint condition completion (#6509) imports src/editor/lsp/snippet.ts from the debugger code the frontend smoke loads, so scripts/smoke-paths.test.ts failed on main. The file is now in the workflow's paths and the Changes step's smoke pattern.
2026-11-27 22:31:46 +08:00
l0ng-ai 15c5e921df feat(agents): show links in the composer as chips and reference pasted GitHub file links (#6470)
Bare https URLs and [label](url) links show as chips in the agent composer and in sent messages: issues and pull requests as repo#12 (GitLab repo!3, Linear ENG-42), commits as repo@abc1234, other pages as host and path. A click opens the page; the text sent to the agent is unchanged. A link stays text while the caret is at its end, and a URL ends at CJK text and full-width punctuation.

Pasting a URL over selected text on one line makes [text](url). A pasted GitHub blob or tree link into this repository (matched against the git remotes, refs with / resolved) becomes an @path:lines or @dir/ reference when the file exists; other links paste as the URL.
2026-11-27 22:30:09 +08:00
LU XIANGRUIтаwildcatDownstairs bc64188c38 feat(python): go to definition and completion for pytest fixtures (#6510)
A fixture parameter of a test or fixture now resolves to the fixture that pytest would inject: the nearest definition in the same class or module, then the conftest.py chain up to the root, pytest_plugins modules, pytest11 entry points and the _pytest builtins. Go to Declaration opens it, and completion in a test's parameter list offers the fixtures in scope with their source file. Named fixtures (name=...) and usefixtures("...") strings are covered; the fixture layers are cached by file mtime.

Closes #6490

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:12:59 +08:00
LU XIANGRUIтаwildcatDownstairs a3c819e064 feat(debugger): complete breakpoint conditions from the language server (#6509)
The Condition field and the {...} parts of the log message in breakpoint properties offer code completion without a debug session. The expression is spliced on its own line before the breakpoint's line, indented like it, and a new lsp_snapshot_completion command asks the language server on a transient snapshot of the file, so locals in scope, fields and members after . are offered while the open document and its diagnostics stay untouched. The popup and keys are those of Evaluate; the field claims Ctrl+Space so the non-modal popover doesn't also run the editor's completion.

Fixes #6403

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:05:41 +08:00
audichuang 1f2e92b433 feat(project-tree): copy a Java class's fully qualified name from Copy Path/Reference… (#6503)
The Project view's Copy Path/Reference… chooser gains a Reference row, backed by a project.copyReference action: com.example.App for App.java and the package name for a folder under a JVM source or test root. The name comes from the path below the source root, so no file is read. The row is left out where there is no valid name: other files, package-info.java / module-info.java, folders that aren't Java identifiers, the source root itself, non-JVM roots, library files and selections that are only partly Java.

Closes #6495

Co-authored-by: audichuang <[email protected]>
2026-11-27 21:58:36 +08:00
LU XIANGRUIтаwildcatDownstairs 8dfca955a5 fix(profiler): harden the pstats reader (#6511)
A pstats file can point many functions at one stats tuple by marshal reference, so a few kilobytes could unfold into millions of caller edges; the reader now refuses a file whose callers tables add up to more edges than it has bytes. The format is decided by content first, so a V8 profile saved as cpu.prof opens as V8 instead of a broken cProfile snapshot. A function recorded under two names of one file is now one method row with its stats and edges added up. Open Snapshot also offers .pstat and All files.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 21:53:52 +08:00
l0ng-ai 91aba61c97 fix(agents): keep the caret in the composer after Quote (#6419)
Choosing Quote on a conversation selection focused the composer, but when the context menu closed it put the conversation's text selection back (a WebKit workaround), after the chosen row had moved focus into the composer, so the caret was lost. The context menu now leaves the selection alone when focus has moved into an editable element.
2026-11-27 20:57:12 +08:00
l0ng-ai 1fb4135b5b fix(ui): keep context menu labels whole when the menu meets the window edge (#6497)
A context menu a few pixels taller than the room below its point was capped and scrolled, and in WebKit the scrollbar that appeared took its width from the popup's content, so labels were cut. A popup opened at a point now moves up to fit the window before it is capped, and a capped popup always shows its scrollbar so the popup widens instead of cutting its labels.
2026-11-27 20:49:21 +08:00
LU XIANGRUIтаwildcatDownstairs 24598e0dae feat(notebook): convert a notebook to a Python script and back (#6491)
Adds Convert to Python File to the Project view context menu of a .ipynb and Convert to Jupyter Notebook to that of a .py file, both also in Find Action for the active editor.

The script uses # %% cell markers; Markdown and raw cells become commented # %% [markdown] / # %% [raw] cells, and IPython-only lines (%magic, !shell) and whole %%cell-magic cells are commented out so the script runs with plain python. The result is written next to the source without overwriting (<name>-1.py, ...) and opened; an open notebook or script is converted as shown, unsaved edits included. Back to a notebook gives nbformat 4.5 with a Python 3 kernelspec, where # %% / #%% lines start cells and a script without markers becomes one code cell. A notebook that is not nbformat 4 reports an error and writes nothing.

Closes #6372

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:42:23 +08:00
Bake Yam 2436ad6fe9 fix(notebook): give a cell the intentions menu a text editor has (#6492)
Alt+Enter in a notebook code cell offered only the server's code actions and the inspection controls: cellLspExtensions never included intentionsExtension, so a language's own intentions and quick fixes (Python's create function / class) were missing in cells. Cells now get the same intention providers as a text editor, looked up by the cell document's language; each cell is its own document, so the edits stay in the cell.

Part of #5846

Co-authored-by: Renjiankang <[email protected]>
2026-11-27 20:41:53 +08:00
LU XIANGRUIтаwildcatDownstairs c2c6931f0e feat(database): open .csv / .tsv files as a table (#6493)
.csv and .tsv files now open with Text / Data tabs under the editor. Data shows the file as a read-only table in the result grid, with header sort, the local column filter and search. The delimiter (comma, semicolon, tab or pipe) is guessed from the first 64 KB (.tsv is always tab), and the header row is guessed with a First row is header override. Quoted fields, line breaks inside quotes and a UTF-8 BOM are handled; ragged rows are padded, unnamed columns numbered and repeated names suffixed. Parsing runs in a Web Worker and the table re-reads the editor text (debounced) only while Data is shown; Text stays mounted so undo history and unsaved edits are kept.

visibleRows also computes each row's sort key once instead of per comparison, which speeds up local sorting of query results too.

Closes #6368

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:38:44 +08:00
Dimas Avrian Fachriza 2e0c8dd527 perf(editor): prune huge completion lists before mapping (#6477)
Tailwind answers every completion request with its full utility list (about 26k items), and each item was mapped to a CodeMirror option and re-filtered on every keystroke, which showed as input lag.

Lists above 2000 items now keep only the items whose filter text contains the typed token as a subsequence, before mapping. That is a superset of what CodeMirror's fuzzy matcher can show for text that grows from the token, so typing forward loses nothing; the pruned list stays valid only while the text still starts with that token, so backspacing asks the server again.

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 20:33:39 +08:00
faysouтаfaysou f4be752dda fix(markdown): keep reading position when toggling Structure (#6483)
Showing or hiding a docked Structure pane changes the Markdown editor's width. CodeMirror could keep an old pixel offset within a wrapped line, and the preview measured its position after some blocks had already reflowed, so both jumped. The source view now anchors the first visible character across a side-dock change and restores it in the resize frame; the preview remembers its line and offset on scroll, pauses following the source while blocks reflow, and restores the position once the width settles. A navigation made while paused is applied on resume. Works in all three Markdown modes.

Co-authored-by: faysou <[email protected]>
2026-11-27 20:32:41 +08:00
LU XIANGRUIтаwildcatDownstairs a52a639b8e fix(coverage): import coverage.py data below fail_under and in monorepo members (#6478)
coverage xml (import) and coverage lcov (Run with Coverage) exit 2 when the data misses a [report] fail_under, which failed the import and lost the run's report; both now get --fail-under=0.

coverage.py now runs in the nearest folder above the data file with a coverage.py configuration (.coveragerc, setup.cfg, tox.ini, pyproject.toml), else the project root, so a monorepo member's [paths] and relative_files apply. Files without source come from the combined data's measured_files() instead of parsing warnings, and Python runs with -W ignore, so disable_warnings and PYTHONWARNINGS=error no longer drop files or fail the import. coverage.py runs with a 10-minute timeout, and coverage.py 4 data or a coverage.py older than 6.3 get clear errors.

Closes #6474

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:30:50 +08:00
LU XIANGRUIтаwildcatDownstairs 1b0bf4d741 fix(python): fix edge cases of import updates on module moves (#6479)
Fixes for the Python import updates on module and package moves:

- Nested attribute chains got overlapping edits and the move failed; each expression now gets one edit, on its longest moved prefix.
- Cancelling ends the request after the import scan and returns cancelled instead of partial edits.
- In monorepos, module names come only from Python roots (detected from a Python project file or marked by the user), a moved folder counts only when it holds .py/.pyi files, and an import is left alone when the importing file's own root has a module of that name.
- Files are read through the documents layer, so a BOM or another encoding no longer shifts the edits.
- Moving a .pyi stub without its .py changes no imports.
- Rewriting import pkg.models keeps pkg bound when the file still uses pkg.helper().
- Statements sharing a line stay valid, and moved names are removed line by line, keeping the remaining names' layout and comments.

Closes #6475

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:29:48 +08:00
LU XIANGRUIтаwildcatDownstairs 13597e40a1 fix(debugger): keep Python's debugpy config and pick Django or Jinja templates by language (#6476)
django-html declared a debugpy [debugger], and find_config takes the first language declaring an adapter, so a user's languages/python.toml debugger override no longer applied. The block is gone; breakpoint placement accepts Django Templates by language instead.

django: true came only from manage.py / -m django / django-admin, so template breakpoints never stopped under uvicorn, gunicorn, daphne or pytest-django, and the templates/*.html rule sent jinja: true for them. At debug start each file with an enabled breakpoint (other than .py) is asked for its language with the editor's detection: a Django Template turns on django, other templates turn on jinja. Disabled breakpoints no longer turn either on, and templates/*.txt and *.xml accept breakpoints.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:26:34 +08:00
LU XIANGRUIтаwildcatDownstairs aa1aa91b0d fix(debugger): keep Python Debug Server loopback hosts on loopback (#6487)
The port check retried every bind error for 5 s; it now retries only AddrInUse (the previous adapter still shutting down) and reports any other bind error at once.

Every loopback form of the host (127.1, LOCALHOST, 0:0:0:0:0:0:0:1, ::ffff:127.0.0.1) is normalised with the URL parser and stays on loopback: localhost and IPv6 loopback listen on 127.0.0.1, since debugpy's adapter before 1.8 listens on IPv4 only, and the connect line and waiting note say 127.0.0.1 then. Another 127.x address listens on itself. Docs explain that an imported VS Code listen.host of 0.0.0.0 becomes localhost and how to reach the IDE from a container.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:25:27 +08:00
LU XIANGRUIтаwildcatDownstairs 032a3b0453 fix(python): correct doctest results, module imports and docstring detection (#6489)
Skipped examples, examples after a first failure under REPORT_ONLY_FIRST_FAILURE, and examples after a FAIL_FAST stop were all reported as passed: the reporter only kept failures and marked every other example passed. It now records each example that ran (and reports skipped ones as skipped), applying REPORT_ONLY_FIRST_FAILURE itself so later examples still reach it.

Modules are imported by their dotted name from the deepest sys.path root that holds them (working directory, PYTHONPATH, source roots), falling back to loading the file when the import fails or resolves to another module. Docstring detection now skips lines inside triple-quoted strings and no longer gives a one-line def the next object's docstring; -v is passed through to the runner.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:24:03 +08:00
LU XIANGRUIтаwildcatDownstairs 07750ad984 fix(python): Create Test keeps imports, indentation and module paths valid (#6488)
Create Test wrote invalid Python in several cases: a new import glued to a last import without a final newline; the first import above a shebang, coding line or module docstring; methods added to a tab- or differently-indented Test class in the editor's indent unit; repeated definitions (@overload, conditional) tested several times; import paths not relative to the innermost source root; and an import of a module no import can name (my-tool.py). Each is fixed: the new import gets its own line below the header, methods use the class's indentation, a name is offered once, the module path is relative to its source root (no import when it has no valid name), and an uneditable test file shows a hint.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 20:21:22 +08:00
Muuтаmuutot ba38f070d9 feat(analysis): manage a producer's suppressed rules from the problem menus (#6472)
The submenu of a problem's inspection (Alt+Enter on a fix, Problems, Inspection Results) lists the codes the inspection profile in effect turns off for that producer, each checked (unchecking removes the rule), plus Add rule… to suppress a code before it has ever reported (for example Ruff's UP045). Rules are plain profile entries, so the editor, Problems and Inspect Code hide those codes. The rows show only for inspections split by code (language servers, code-split built-ins); the input dialog is provided by the workbench.

Co-authored-by: muutot <[email protected]>
2026-11-27 20:20:12 +08:00
l0ng-ai c77f4db777 fix(usages): show what the server found in its scope before the widened search (#6485)
A project-wide usages search asks the server, then opens the other files that mention the name and asks again. Only Java's library search streamed an early answer, so for Python (pyright) and the other servers the popup waited for the second pass. The first answer is now shown while the other files are searched, for a single answering server (not the CSS server, whose answer is filtered afterwards) and for Java's sources.

Fixes #6441
2026-11-27 20:05:53 +08:00
l0ng-ai d3067c8d3a feat(database): rebuild a PostgreSQL table's comments, owner, grants and triggers in its DDL (#6481)
Go to DDL on a PostgreSQL table gave the table, its constraints and indexes only. It now also gives the table and column comments, the owner, the privileges granted beyond the owner's (none while the ACL was never changed) and the user triggers, in the order a script runs them. Views keep their single statement.

Fixes #6439
2026-11-27 20:01:33 +08:00
l0ng-ai 7bf2702565 fix(kotlin): show the Kotlin bridge build as a background task (#6480)
The Maven build that compiles a project's Kotlin for JDT (on opening the project and after saved Kotlin or POM changes) ran with no sign in the UI, for about a minute on a large project, while Java code using the Kotlin API stayed red. It now shows in the status bar as Compiling Kotlin for Java with Maven's reactor progress, and can be stopped there; the next saved change builds again.

Fixes #6434
2026-11-27 19:56:49 +08:00
Dimas Avrian Fachriza 65c45ffe05 fix(editor): complete hyphenated tokens such as Tailwind classes (#6463)
Typing a hyphenated token such as items-c never offered items-center: the server's replace range covers the whole class, but the client filtered on the last word segment (c), and CodeMirror matches a one-character pattern only at a label's start. Typing - also closed the popup and re-queried. The completion now starts where the servers' single-token replace ranges start when they reach back over hyphens (the most common start wins), and the list stays valid across - while an option still starts with the typed text. Other punctuation, and lists with no option continuing the hyphen, re-query as before. CSS properties (background-c → background-color) benefit too.

Closes #6462

Co-authored-by: FForFachriza <[email protected]>
2026-11-27 19:51:26 +08:00
LU XIANGRUIтаwildcatDownstairs 84b528f0cd feat(profiler): open cProfile snapshots (.pstats / .prof) (#6466)
Open Snapshot… and Open in Profiler accept pstats files written by cProfile / profile (and yappi's pstat export), told apart from a V8 .cpuprofile by content. The marshal'd pstats dict is read in Rust without a Python interpreter. The method list shows exact own time, total time and call counts (total/primitive for recursion); selecting a method lists its callers and callees, exact for cProfile and summed from the call tree for sampled profiles. The flame graph and call tree are rebuilt from the caller/callee totals, sharing each function's time among its callers in proportion, with a notice that they are estimated; recursion is not unfolded, roots are the strongly connected components of the call graph, and the tree is bounded in share and node count. Recorded files resolve against the project root, then the snapshot's folder, each file looked up once.

Closes #6367

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:48:03 +08:00
LU XIANGRUIтаwildcatDownstairs 8621764813 feat(python): Create Test generates pytest tests for the chosen functions and methods (#6465)
On a Python module, Create New Test… (and the new Create Test… action) opens a chooser of the module's functions and its classes' methods, preselecting the one at the caret or every method of the class there. OK writes pytest stubs (test_<name> / class Test<Class> with test_<method>, body assert False) into the module's test file, or a new test_<module>.py in the mirrored package under the test root, importing only names the file doesn't import yet. Existing tests are kept, methods go into an existing Test<Class>, and the edit is one undo step. Imports spanning several lines (parenthesized or backslash-continued) are read too, so their names are not imported again and a new import goes after them. Other languages keep the template flow.

Closes #6387

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:40:40 +08:00
rolicon 22e1c4b927 fix(run): import JetBrains Dockerfile run configurations (#6469)
JetBrains docker-deploy configurations with a dockerfile deployment were skipped as UnsupportedType. The importer now keeps the Dockerfile path, image tag, container name and server name; the Dockerfile run type completes the import through a new prepareImport hook, resolving the server name to this machine's connection (the default daemon when none is saved and the name is Docker) and generating the run and stop commands. A missing or ambiguous server is left for the user to choose and reported as unmapped; running such a configuration asks for a server instead of using the default daemon. Other deployment types are still skipped.

Co-authored-by: rolicon <[email protected]>
2026-11-27 19:30:15 +08:00
Ernstjan FreriksтаEjaYF e2817656e8 fix(ui): end tree rows at the scrollbar track (#6468)
While a tree's vertical scrollbar thumb is shown, Scrollbar sets data-scrollbar-shown on its scroller and Tree reserves 8px on the right (the 10px track minus the thumb's 2px border), clipping its rows there. Rows wider than the panel no longer show their text, selection or hover background through the translucent thumb. Trees without a vertical scrollbar keep their 6px inset.

Co-authored-by: EjaYF <[email protected]>
2026-11-27 19:26:04 +08:00
LU XIANGRUIтаwildcatDownstairs 306c71290c fix(debugger): address review of the Python Debug Server (#6464)
Follow-up to #6421. A waiting Python Debug Server no longer lends its run configuration to other debug starts: each start's configuration is kept by name and taken by its own started event. Listening again retries the port for up to 5 s while the previous adapter shuts down instead of failing with Address already in use. An IDE host of ::1 listens on ::1 (other IPv6 hosts on ::) and the connect line strips the brackets. A VS Code listen host of 0.0.0.0 imports as localhost.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 19:21:53 +08:00
l0ng-ai 51ccb68b72 fix(diff): open a diff at its first difference (#6471)
A diff opened without a line to show (double-click in the Commit tool window, Show Diff) started at the top of the file. The two-pane and staging-area diffs now open at their first difference unless a line or a remembered caret is given. The all-in-one diff opens at the first difference of the file it was opened for, once, repeating the scroll until the change is drawn since lines below the drawn ones have estimated heights.

Fixes #6427
2026-11-27 19:19:02 +08:00
l0ng-ai 2e965810e9 feat(color-scheme): Java interface, abstract class, enum and type parameter colours (#6467)
The Java colour page gets Interface name, Abstract class name, Enum name and Type parameter under Classes. jdtls's interface, enum and typeParameter tokens, and class tokens with the abstract modifier, carry their own classes, which keep the class name colour until set. INTERFACE_NAME_ATTRIBUTES, ABSTRACT_CLASS_NAME_ATTRIBUTES, ENUM_NAME_ATTRIBUTES and TYPE_PARAMETER_NAME_ATTRIBUTES in an imported .icls land on them, and the default Interface name colours Java's interface until its own key does.

Fixes #6415
2026-11-27 19:09:20 +08:00
Vladislav Kuzmin 31b70cf0ac test(e2e): use the configured shortcuts for editor zoom and aggregate copy (#6457) 2026-11-27 19:00:02 +08:00
Muuтаmuutot d0989e2a4b fix(plugins): keep line-end annotations on their line when Enter splits it (#6454)
A plugin line-end annotation is a side: 1 point widget at the end of its line, and CodeMirror maps such a widget across an insertion at its position, so Enter at the end of an annotated line carried the label into the new line and down with every further Enter. The decorations field now re-places its items on every edit: marks and hover data map with the text, while an after label re-anchors at the end of the line its range's end maps onto. An empty range stays a point before text typed at it, so its label is kept.

Co-authored-by: muutot <[email protected]>
2026-11-27 18:59:15 +08:00
LU XIANGRUIтаwildcatDownstairs d96ed8d154 feat(python): run doctests from the gutter and the context menu (#6451)
Modules, classes and functions whose docstrings have >>> examples get a gutter run icon, and a module with examples and no if __name__ == "__main__": runs its doctests from the project tree and editor context menus ("Doctests in …"). A new Python doctest run configuration takes files or file.py::Class.method targets and doctest's -o options; PyCharm Doctests configurations import as it. Runs go through a stdlib-only reporter built on DocTestFinder / DocTestRunner that reports each example as a test under its object, so gutter icons show results, failures open Expected / Got in the comparison view, and Rerun Failed Tests reruns the failed objects.

Closes #6389

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:56:35 +08:00
l0ng-ai 6b41870368 fix(agents): keep the conversation painted when sending from far up (#6446)
Sending a message while scrolled up jumps the conversation to its end. The rows there had
skipped rendering (content-visibility: auto); WebKit turned them visible but didn't repaint
them, so the view stayed blank until the reply changed the conversation. A row whose
remembered height went stale the same way also kept the end of a streaming reply out of reach.

Rows within a viewport of the view are now tracked with an IntersectionObserver (data-near)
and always render, and a programmatic jump marks the rows around its target before moving.
2026-11-27 18:54:58 +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
l0ng-ai 762ebecd86 fix(database): build the Modify Table index detail without a UI-text template (#6250)
A template literal holding "UNIQUE " read as untranslated UI text to the
catalog check (textCatalog.test.ts failed on main after #6248).
2026-11-27 04:01:45 +08:00
l0ng-ai fd4efff6e3 feat(database): group and filter the Modify Table list (#6248)
The Modify Table / Create Table list was one flat list of columns. It now
groups Columns, Keys (the primary key as edited), Foreign Keys, Indexes and
Triggers, each collapsible with its count, and a filter on its toolbar
narrows the rows by name or type. The statements the dialog runs are
unchanged.

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

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

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

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

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

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

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

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

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

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

Fixes #3809

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

Fixes #6229

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #6217

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

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

Closes #6219

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

Closes #6084

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

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

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

Closes #6086

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

Closes #6014

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

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

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

Closes #5942

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #6185

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

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

Closes #6137

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

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

Closes #4757

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

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

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

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

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

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

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

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

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

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

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

## Evidence

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

## Merge Danger

**Door:** two-way

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

**Blast Radius:** settings-UI

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

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

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

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

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

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

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

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

## How it was verified

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

## Review focus

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

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

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

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

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

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

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

Closes #4760

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

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

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

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

Part of #6012

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

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

Closes #6151

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

Co-authored-by: faysou <[email protected]>
2026-11-26 19:31:03 +08:00
l0ng-ai f90d94538d fix(debugger): use the spacing token for the frames error gap (#6172)
#6158 added a raw 6px gap to the frames error note, which the spacing scale test rejects on main; it now uses var(--space-1-5).
2026-11-26 19:27:47 +08:00
audichuang a4ad387085 perf(vcs): keep the Git Log scroll anchor fast when leading rows are dropped (#6006)
When the Git Log's commits are replaced, the list keeps the first surviving visible row in
place. Finding it searched the new list once per old row with two key strings per comparison,
so a checkout that drops tens of thousands of leading rows cost on the order of 10^8
comparisons on the main thread. Rows are now compared by id and repository directly, and
after about eight full misses the rest are looked up in a repository -> id index. The result
is the same as before (checked against the old loop on random cases).

Co-authored-by: audichuang <[email protected]>
2026-11-26 18:37:28 +08:00
audichuang f8a148c06d fix(project-tree): don't offer Python Package in a nested non-Python module's roots (#6028)
In a project with a root Python build file and a nested JavaScript app (frontend/package.json),
New inside frontend/src offered Python Package: any folder under a Python build file counted as
Python, even inside a root a deeper non-Python build file detected. The innermost claim now
wins; folders outside those roots, and roots a Python build file claimed first, keep Python
Package.

Co-authored-by: audichuang <[email protected]>
2026-11-26 18:34:37 +08:00
l0ng-ai aa1a027162 feat(plugins): a shortcut-run command gets the focused view's selected item (#6160)
A plugin command run without an argument (its shortcut, Find Action) while one of the plugin's views has the keyboard focus gets the selected item's key, the same argument as from that item's viewItem.context menu. Only commands the item's menu offers (with its when clause) get it; nothing selected or focus elsewhere gives none.

Fixes #4759
2026-11-26 18:32:57 +08:00
LU XIANGRUIтаwildcatDownstairs b30716e22c fix(debug): show Java frames when java-debug cannot describe one of them (#6158)
On Windows a Java debug session stopped in a Spring request showed no frames: with the
project's sourcePaths set, java-debug looks a CGLIB proxy frame's `<generated>` source up
there, Paths.get throws, and the adapter fails the whole stackTrace request. When that
request fails, the frames are now taken one at a time, leaving out the ones the adapter
can't describe. A stack trace failure that remains is logged and shown in Threads &
Variables with a Retry button instead of an empty list.

Fixes #6157

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 18:32:35 +08:00
l0ng-ai 7fb21003f3 fix(app): list Remote Development projects in File > Open Recent (#6159)
Manage Projects merged the frontend's recent remote projects (SSH, WSL, Dev Containers)
with the backend's local list, but Open Recent, in the macOS menu bar and the
Windows/Linux title bar menu, read only the local one. The frontend now hands its remote
list to the menu, which merges it by when each project was opened; choosing one opens it
on its host.

Fixes #6124
2026-11-26 18:29:56 +08:00
l0ng-ai ad8d32d9c7 fix(plugins): keep the annotation colour of a theme plugin's color scheme (#6156)
A theme plugin's .icls mapped DEFAULT_METADATA onto the annotation colour and ignored
ANNOTATION_NAME_ATTRIBUTES, so a scheme that only changed DEFAULT_METADATA repainted Java
annotations, which take the annotation key (Darcula's own when the file has none). Same
mapping as #6130 fixed for imported color schemes.
2026-11-26 18:20:46 +08:00
l0ng-ai 08aef06844 fix(java): skip a jdtls on PATH that runs java -jar itself (#6155)
A hand-written jdtls that starts the Equinox launcher with java -jar (opencode puts
one into a JDK's bin) knows none of the release script's options: every --jvm-arg,
the Lombok agent among them, reached jdtls as an application argument, and its own
-data came before the IDE's workspace. When the first jdtls on PATH is such a
wrapper, the next one that isn't is started instead, else the IDE's own install,
which is offered for install while missing.

Fixes #6062
2026-11-26 18:17:04 +08:00
a1oyssтаa1oyss 3d5ec8a147 fix(vcs): show a deleted file's diff with the editor's own line numbers (#6146)
The one-side viewer of a deleted file drew the deleted rows as block widgets over an
empty document, so the gutter numbered nothing but a stray 1 on the phantom line and
the rows had no context menu. A deleted file's one-sided diff now swaps its sides as a
staged deletion already did: the original text is the document and the absent side is
the diff's original, so the editor's own gutter, colours and context menu apply.
The header keeps the request's order (revision -> (deleted)).

Fixes #6145

Co-authored-by: a1oyss <[email protected]>
2026-11-26 18:11:58 +08:00
l0ng-ai 0f14314156 feat(debugger): enhanced class redefinition for Java debug sessions (#6148)
Application and Spring Boot configurations get an "Enhanced class redefinition" option. When debugging on JetBrains Runtime, the JVM starts with -XX:+AllowEnhancedClassRedefinition, so Reload Changed Classes can also apply structural changes such as added or removed methods and fields. On any other JDK (or one that can't be identified) the session starts without the flag, which those JVMs reject, and the Debug console says why. Run is unchanged.

When the JVM refuses a structural change and the session's configuration has the option off, the Hot Swap failure says how to allow such changes.

Refs #4007
2026-11-26 18:05:55 +08:00
txdywmwddhxs 2413cc4b43 fix(editor): preserve C++ namespace colors for library symbols (#6133)
clangd marks std and other standard-library namespaces with the defaultLibrary modifier, so the generic builtin (Predefined symbol) class overrode the Namespace colour. A C++ semantic hook drops the builtin class for namespace tokens only; other symbol kinds, modifiers and languages keep their styling.

Fixes #6123

Co-authored-by: txdywmwddhxs <[email protected]>
2026-11-26 18:02:58 +08:00
l0ng-ai 30291971e1 fix(remote): offer to stop another build's backend that keeps a project (#6147)
A remote daemon of another build refuses to retire while it has terminals, runs, agent sessions or unsaved changes. After an upgrade left such a daemon (its binary gone, so no build can reconnect to it), the project could not be opened and the error only asked to reconnect with the old build.

The refusal now comes back as RemoteBackendBusy and the window asks whether to stop that backend. Agreeing reconnects with `openidea-server --attach <path> --replace`, which sends the old daemon SIGTERM (its own shutdown), kills it after the shutdown timeout if needed, and starts this build's daemon. Works for SSH hosts, WSL and dev containers, and for daemons of earlier builds (found by their --daemon command line).

Fixes #6119
2026-11-26 18:00:44 +08:00
l0ng-ai 9f3d75976f fix(debugger): send each window's breakpoints only to its own sessions (#6138)
The backend kept one breakpoint table for the whole app and sent all of it to every new session. A file whose removal never reached that table (a reloaded window, or the same file recorded under another path) stayed there and was sent to every later session, so a deleted line breakpoint kept suspending the program until restart; one window's breakpoints also reached another window's sessions.

Line, method and field breakpoints are now kept per window (the session owner) and sent only to that window's sessions; a closing window drops its lists. When a window loads its project and right before each session starts, it hands its whole list to the backend (debug_replace_breakpoints), which clears the files it no longer lists in the table and in the window's live sessions.

Fixes #6116
2026-11-26 17:39:11 +08:00
l0ng-ai 72d9aad715 fix(database): complete every table of a large default schema (#6136)
SQL completion read the columns of every non-system schema in one query capped at 50,000 rows, ordered by schema and table. A schema with more columns than that (5,000+ Oracle tables) lost the columns of the tables sorting last, so they were neither completed nor resolved in the console.

completion_columns now takes a CompletionScope: the default schema is read in its own query without the shared cap, and the other schemas keep sharing it. Applies to every driver with a completion query. A PostgreSQL integration test with 52,000 columns in the default schema covers it.

Fixes #6118
2026-11-26 17:32:05 +08:00
l0ng-ai 7264e7d66d test(database): check the shown values in the numeric filter e2e (#6134)
Since #6067 a column's local filter shows the checked values instead of hiding them, so the precise-filter case of databaseNumericSort.spec.ts failed on main and on every PR's E2E leg. The spec now checks the three values it expects to see.
2026-11-26 17:25:54 +08:00
l0ng-ai 10379a54f7 fix(diff): prevent wheel scroll jump-back loop in WebKit (#6115)
Wheel-scrolling a diff in WebKit could jump scrollTop backwards and loop, so the bottom was unreachable.

- collapsedDiffLines replaced the separator row's children synchronously in docViewUpdate, before layout flushed; WebKit then clamped scrollTop back whenever a collapsed-lines separator entered the viewport. The replacement now runs in a keyed requestMeasure write phase.
- In synchronized side-by-side diffs (PaddedPanes / UnalignedPanes), the follower's measure-driven scrollTop adjustments were read as user scrolls and followed in reverse. The wheeled pane now leads for 150 ms after its last wheel event (released on pointerdown), and non-document height changes refresh the expected echo offsets.

Covers the split aligned, split unaligned and unified views.
2026-11-26 17:24:35 +08:00
LU XIANGRUIтаwildcatDownstairs 6564b9e6cb fix(vcs): resize the Repository column from log rows when Commit is first (#6125)
In a multi-root Git Log with column headers hidden (the default) and Commit as the first column (the default), nothing on a data row sat on the Repository/Commit boundary: only fixed columns draw a row resize strip, and the Repository column has no divider of its own. A leading Commit cell now carries the same strip as the header's Commit divider and resizes only the Repository column.

Fixes #6111

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 17:16:20 +08:00
l0ng-ai d437cd46f5 fix(settings): keep the annotation colour of imported color schemes (#6130)
Importing a color scheme mapped only DEFAULT_METADATA to the annotation colour. Java annotations use ANNOTATION_NAME_ATTRIBUTES, which the bundled Default and Darcula schemes set themselves, so a scheme based on them that only changes DEFAULT_METADATA lost its annotation colour on import. The importer now reads ANNOTATION_NAME_ATTRIBUTES ahead of DEFAULT_METADATA, applies the parent's value when a Default- or Darcula-based file leaves it out, and exports the colour under that key.

Fixes #6108
2026-11-26 17:08:47 +08:00
langxpтаkradme 925d474274 fix(app): resume interrupted update downloads (#5377)
An interrupted update download started again from zero on the next attempt. The update is now downloaded to a .part checkpoint in the app cache, keyed by version, target and signature so the GitHub and CNB sources share it, and later attempts resume it with an HTTP Range request. A 200 answer or a mismatched range replaces the checkpoint safely (the old bytes stay until the new download completes), a 416 for an already complete file is accepted, and the package is verified against its signature before installing; a resumed file that fails verification is discarded and downloaded again. Check and verification are cancellable, and obsolete checkpoints are removed.

Co-authored-by: kradme <[email protected]>
2026-11-26 17:03:02 +08:00
LU XIANGRUIтаwildcatDownstairs 89463afc18 fix(updates): show release notes on What's New after a Windows update (#6058)
After an in-app update on Windows, What's New always said the version had no release notes. The Windows installer ends the app inside appInstallUpdate, so the notes recorded after the call returned were never stored, and the fallback manifest read app_release_notes was trusted-only, which the project-less window the page opens in is refused. The notes are now recorded before the install starts and restored if the install fails or is cancelled, and app_release_notes is always allowed, like the update check: it reads only the public manifest.

Closes #6056

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 16:57:59 +08:00
Akbar Husainтаakbar1214 c884aa4cc6 fix(updates): cap updater connects so an unreachable CDN IP falls back (#5070)
The updater's HTTP client had no connect timeout, so an unreachable first address of the release CDN hostname held the update check until its 60 s deadline instead of falling through to the next address. The client now bounds connection setup (TCP and TLS) to 15 s, which reqwest divides across the resolved addresses.

Co-authored-by: akbar1214 <[email protected]>
2026-11-26 16:55:54 +08:00
Void Et Noxтаvoidetnox 09108e02e3 ci(release): publish the Homebrew cask to l0ng-ai/homebrew-tap (#5883)
After a stable release is published, a new homebrew job downloads both macOS DMGs, writes Casks/openidea.rb (per-arch SHA-256, auto_updates true so the in-app updater and brew upgrade don't fight, the openidea CLI as a binary, zap paths) and pushes it to l0ng-ai/homebrew-tap. It is skipped for prereleases and when HOMEBREW_TAP_TOKEN is unset, and can be run by hand for an existing tag. The README documents brew install --cask l0ng-ai/tap/openidea.

Co-authored-by: voidetnox <[email protected]>
2026-11-26 16:51:45 +08:00
Vladislav Kuzminтаprincipalwater 2b6ca90457 fix(ci): cache Maven plugins for Java build tests (#5966)
The Java build integration tests resolved maven-resources-plugin and maven-compiler-plugin from Maven Central on every run and failed when Central rate-limited the download. On GitHub-hosted runners CI now restores a dedicated local repository from cache, prepares it once with the shared jbuild-maven fixture (retrying 0/10/30 s, 5 minute limit) and saves it only after a successful preparation; both test crates use the same fixture POMs, so the cached plugins are the ones the tests need.

Closes #5964

Co-authored-by: principalwater <[email protected]>
2026-11-26 16:50:53 +08:00
audichuang 3c3681ef2b fix(clipboard): read the macOS clipboard natively for menu paste, without WebKit's Paste callout (#6061)
On macOS, WebKit asks the user to confirm execCommand("paste") and navigator.clipboard reads outside a paste event with a "Paste" callout. readClipboardPlainText fell back to navigator.clipboard.readText() whenever the native read found no text, and the terminal's menu Paste called execCommand("paste") and navigator.clipboard.read() before reading natively. On macOS a null from clipboard_text now means empty text (a refused command still falls back), and in the desktop app the terminal menu Paste reads files, text and images through the backend commands.

Co-authored-by: audichuang <[email protected]>
2026-11-26 16:42:19 +08:00
audichuang b0d7bfef24 fix(vcs): History for Selection no longer lists Local Changes when the newest commit is a merge (#6034)
History for Selection listed a Local Changes row on a clean file whenever the newest commit touching the selected lines was a merge: the list compared the current lines with the newest row's `after` block, and `git log -L` prints no patch for a merge, so that block was empty. The backend now returns HEAD's block (`BlockHistory.head`) and the list compares against it, falling back to the newest row for servers that predate the field.

Co-authored-by: audichuang <[email protected]>
2026-11-26 16:35:31 +08:00
l0ng-ai 527add030a fix(clipboard): read CF_UNICODETEXT pairs with as_chunks (#6126)
Clippy 1.100 adds chunks_exact_to_as_chunks, which failed the workspace clippy run on every PR. unicode_text now reads the UTF-16LE pairs of a CF_UNICODETEXT block with as_chunks::<2>(); behaviour is unchanged.
2026-11-26 16:32:29 +08:00
l0ng-ai 81c2fc9ace fix(vcs): scroll the changes tree horizontally instead of clipping rows (#6121)
Rows in the Commit and Local Changes trees were locked to the pane width and ellipsized, so the end of a long file name and its directory path could only be read by widening the tool window. The tree now keeps rows at their natural width and scrolls horizontally, as the Project view does.

Fixes #6080
2026-11-26 16:10:22 +08:00
1700 змінених файлів з 102850 додано та 10229 видалено

No files matched your search

+13
Переглянути файл
@@ -0,0 +1,13 @@
# Nextest runs tests in separate processes. These three tests write the same Windows clipboard.
[test-groups.windows-clipboard]
max-threads = 1
[[profile.default.overrides]]
filter = '''
package(=ide-clipboard) & (
test(=tests::text_reads_on_one_thread_do_not_corrupt_the_heap)
| test(=tests::text_reads_taking_turns_do_not_corrupt_the_heap)
| test(=tests::concurrent_text_reads_do_not_corrupt_the_heap)
)
'''
test-group = "windows-clipboard"
+38
Переглянути файл
@@ -156,6 +156,44 @@ jobs:
- run: cargo clippy --workspace --all-targets -- -D warnings
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
- name: Prepare Maven artifacts for Java build tests
id: jbuild-maven
if: runner.environment == 'github-hosted'
timeout-minutes: 5
shell: bash
env:
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
run: |
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
exit 0
fi
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
for delay in 0 10 30; do
sleep "$delay"
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
done
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
+74
Переглянути файл
@@ -0,0 +1,74 @@
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_DEPLOY_KEY secret (the private half of a write deploy key on
# l0ng-ai/homebrew-tap).
on:
workflow_call:
inputs:
tag: { type: string, required: true }
workflow_dispatch:
inputs:
tag:
description: "Published stable release to write the cask for (e.g. v0.1.51)"
required: true
permissions:
contents: read
concurrency:
group: homebrew-tap
jobs:
cask:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
TAG: ${{ inputs.tag }}
TAP: l0ng-ai/homebrew-tap
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
GH_TOKEN: ${{ github.token }}
steps:
- 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_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
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
if: steps.check.outputs.skip != 'true'
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
- name: Write the cask
if: steps.check.outputs.skip != 'true'
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
- name: Push to the tap
if: steps.check.outputs.skip != 'true'
working-directory: tap
run: |
git add Casks/openidea.rb
if git diff --cached --quiet; then
echo "the cask is already at ${TAG#v}"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -m "openidea ${TAG#v}"
git push
+3 -1
Переглянути файл
@@ -30,6 +30,7 @@ on:
- "src/ui/**"
- "src/editor/api.ts"
- "src/editor/navigationProviders.ts"
- "src/editor/refactorProviders.ts"
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
@@ -39,6 +40,7 @@ on:
- "src/editor/lsp/hint.ts"
- "src/editor/lsp/lsp.ts"
- "src/editor/lsp/positions.ts"
- "src/editor/lsp/snippet.ts"
- "src/bindings.ts"
- "src/styles/tokens.css"
- "src/test/setup.ts"
@@ -106,7 +108,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+7
Переглянути файл
@@ -178,3 +178,10 @@ jobs:
uses: ./.github/workflows/cnb-mirror.yml
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_DEPLOY_KEY.
homebrew:
needs: publish
uses: ./.github/workflows/homebrew.yml
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
Створено
+258 -198
File diff suppressed because it is too large. Load diff
+3 -2
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.53"
version = "0.1.55"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
ide-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
ide-workspace = { path = "crates/ide-workspace" }
@@ -108,7 +109,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
jupyter-protocol = "=2.0.3"
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
lsp-types = "0.97"
gix = { version = "0.89", default-features = false }
gix = { version = "0.90", default-features = false }
portable-pty = "0.9"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
+6
Переглянути файл
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
for 60+ languages. Builds for macOS, Windows and Linux.
On macOS you can also install it with Homebrew:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Benchmark
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
+6
Переглянути файл
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
macOS'ta Homebrew ile de kurabilirsiniz:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
+6
Переглянути файл
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
提供 macOS、Windows 和 Linux 版本。
在 macOS 上也可以用 Homebrew 安装:
```bash
brew install --cask l0ng-ai/tap/openidea
```
## 性能对比
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
+7
Переглянути файл
@@ -6,6 +6,12 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the
light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage).
The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html).
## Agent logos
The `src/ui/openidea/agents/` logos of agents listed in the
@@ -149,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge.
`src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration
leaf) is OpenIDEA's own drawing.
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
Err(err)
if !prefer_stored
&& crate::provider::is_copilot_provider(&spec.id)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
&& super::auth_required(0, &err) =>
{
let retry = run_once(shared, spec, true, model).await;
+48
Переглянути файл
@@ -283,6 +283,20 @@ impl AgentCatalogs {
}
}
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
let key = Self::key(shared, provider);
let mut state = self.state.lock();
if let Some(entry) = state.entries.get_mut(&key)
&& entry.flight.is_none()
&& entry.error.is_some()
{
entry.completed = None;
entry.retry_at_ms = None;
entry.error = None;
}
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_default();
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
@@ -613,6 +627,40 @@ impl crate::AgentManager {
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
}
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
.into_iter()
.find(|p| p.id == "copilot")
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
let account = account.trim();
if !account.is_empty() {
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
}
match discover(&self.shared, spec, model).await {
Ok(found) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: self.shared.config_for_new_task(found.config, "copilot"),
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
refreshing: false,
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
retry_at_ms: None,
error: None,
}),
Err(error) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: Vec::new(),
thought_levels: BTreeMap::new(),
refreshing: false,
refreshed_at_ms: None,
retry_at_ms: None,
error: Some(error),
}),
}
}
}
async fn discover(
+51 -4
Переглянути файл
@@ -2,8 +2,8 @@
//! the agent reports them over ACP.
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentTokens, AgentUsage,
AgentCommand, AgentCommandChoice, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia,
AgentCost, AgentLimit, AgentModelPricing, AgentTokens, AgentUsage,
};
use serde_json::{Value, json};
@@ -155,13 +155,14 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
/// rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
|| o.id == "service_tier"
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
@@ -277,11 +278,30 @@ pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
} else {
c.get("source").and_then(|s| serde_json::from_value(s.clone()).ok()).unwrap_or_default()
};
let mut seen_choices = std::collections::HashSet::new();
let choices = c
.pointer("/input/choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|ch| {
let choice_name =
ch.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty())?;
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
return None;
}
Some(AgentCommandChoice {
name: choice_name.to_owned(),
description: str_of(ch, "description").unwrap_or_default(),
})
})
.collect();
Some(AgentCommand {
name: name.to_owned(),
source,
description: str_of(c, "description").unwrap_or_default(),
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
choices,
})
})
.collect()
@@ -531,6 +551,15 @@ mod tests {
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
}
#[test]
fn service_tier_is_per_model() {
let options = options_of(&json!({ "configOptions": [
{ "id": "service_tier", "type": "select", "currentValue": "false",
"options": [{ "value": "false" }, { "value": "true" }] }
] }));
assert!(is_per_model_option(&options[0]));
}
#[test]
fn effort_context_and_fast_are_per_model_options() {
let mut c = options_of(&json!({
@@ -644,6 +673,7 @@ mod tests {
let old: AgentCommand =
serde_json::from_value(json!({"name": "review", "description": "Review", "hint": null})).unwrap();
assert_eq!(old.source, AgentCommandSource::Command);
assert!(old.choices.is_empty());
let skill = AgentCommand { source: AgentCommandSource::Skill, ..old };
assert_eq!(serde_json::from_value::<AgentCommand>(serde_json::to_value(&skill).unwrap()).unwrap(), skill);
}
@@ -653,13 +683,30 @@ mod tests {
let cmds = commands_of(
&json!({"availableCommands": [
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
{"name": "/init", "description": "Write CLAUDE.md", "input": null},
{"name": "skills", "description": "Manage skills", "input": {
"hint": "[list|info]",
"choices": [
{"name": "list", "description": "List all available skills"},
{"name": "LIST", "description": "Duplicate ignored"},
{"name": " ", "description": "Blank ignored"},
{"name": "info", "description": "Show details for a skill"}
]
}}
]}),
"claude",
);
assert_eq!(cmds[0].source, AgentCommandSource::Command);
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
assert!(cmds[0].choices.is_empty());
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
assert_eq!(
cmds[2].choices,
vec![
AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
]
);
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
assert_eq!((u.used, u.size), (1200, 200000));
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
File diff suppressed because it is too large. Load diff
+59 -1
Переглянути файл
@@ -255,6 +255,14 @@ pub enum AgentCommandSource {
Skill,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommandChoice {
pub name: String,
#[serde(default)]
pub description: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCommand {
@@ -265,6 +273,9 @@ pub struct AgentCommand {
pub hint: Option<String>,
#[serde(default)]
pub source: AgentCommandSource,
/// Fixed subcommand/argument choices advertised by the agent (e.g. `list`, `info` for `/skills`).
#[serde(default)]
pub choices: Vec<AgentCommandChoice>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -289,6 +300,9 @@ pub struct AgentContextUsage {
pub model: String,
pub is_auto_compact_enabled: Option<bool>,
pub auto_compact_threshold: Option<u32>,
/// Tokens reserved for model response / output buffer, when the agent reports it.
#[serde(default)]
pub reserved_tokens: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -296,13 +310,16 @@ pub struct AgentContextCategory {
pub name: String,
pub tokens: u32,
pub kind: Option<String>,
/// Visual section group (e.g. `"System"`, `"User Context"`).
#[serde(default)]
pub group: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentCost {
pub amount: f64,
/// ISO 4217 code, e.g. `USD`.
/// ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing.
pub currency: String,
}
@@ -547,6 +564,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>,
@@ -612,6 +632,9 @@ pub struct AgentProvider {
/// Executable and arguments actually launched, without flattening paths containing spaces.
pub program: String,
pub args: Vec<String>,
/// Settings-managed suffix of `args`; absent for launches that cannot be edited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub additional_args: Option<Vec<String>>,
pub default_program: Option<String>,
pub default_args: Vec<String>,
pub login_hint: Option<String>,
@@ -620,6 +643,9 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
#[serde(default)]
pub can_sign_in: bool,
/// The built-in command can be owned by a global npm package.
#[serde(default)]
pub can_check_cli_update: bool,
@@ -644,6 +670,34 @@ pub enum AgentCommandReadOnlyReason {
CustomAgent,
}
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GhAuthAccount {
pub login: String,
pub active: bool,
}
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CopilotAuthStatus {
pub authenticated: bool,
pub login: Option<String>,
pub auth_type: Option<String>,
pub status_message: Option<String>,
pub gh_installed: bool,
pub gh_accounts: Vec<GhAuthAccount>,
}
/// Output and completion of an interactive sign-in PTY started by the IDE.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum AgentLoginEvent {
Output { data: String },
Exited { code: Option<i32> },
}
/// Where an agent comes from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
@@ -700,6 +754,10 @@ pub struct NewAgentTask {
/// `!` command runs in it first.
#[serde(default)]
pub idle: bool,
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
/// restart, and the agent keeps no session history of its own for it.
#[serde(default)]
pub ephemeral: bool,
}
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
+81
Переглянути файл
@@ -30,6 +30,67 @@ pub(super) fn transcript(config_dir: &Path, cwd: &Path, id: &str) -> PathBuf {
.unwrap_or(direct)
}
/// Brings session `id` into `config_dir` when it is missing there but another Claude Code
/// configuration directory beside it (`~/.claude`, `~/.claude-work`...) has it: switching
/// `CLAUDE_CONFIG_DIR` (another account) would otherwise lose every earlier conversation.
/// Copies the transcript and its folder (subagents, tool results) under the same project
/// directory name. Returns whether the session is in `config_dir` now.
pub(super) fn adopt(config_dir: &Path, cwd: &Path, id: &str) -> bool {
if transcript(config_dir, cwd, id).exists() {
return true;
}
let file = format!("{id}.jsonl");
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
let mut homes: Vec<PathBuf> = config_dir
.parent()
.into_iter()
.chain(home.as_deref())
.flat_map(|dir| std::fs::read_dir(dir).into_iter().flatten().flatten())
.filter(|d| d.file_name().to_string_lossy().starts_with(".claude"))
.map(|d| d.path())
.filter(|p| p != config_dir && p.join("projects").is_dir())
.collect();
homes.sort();
homes.dedup();
let found = homes.iter().find_map(|other| {
let projects = other.join("projects");
let direct = projects.join(escape(cwd));
std::iter::once(direct.clone())
.chain(std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()))
.find(|dir| dir.join(&file).is_file())
});
let Some(source) = found else { return false };
let Some(name) = source.file_name() else { return false };
let target = config_dir.join("projects").join(name);
let copied = std::fs::create_dir_all(&target)
.and_then(|()| copy_tree(&source.join(id), &target.join(id)))
.and_then(|()| std::fs::copy(source.join(&file), target.join(&file)).map(drop));
match copied {
Ok(()) => true,
Err(e) => {
tracing::warn!("claude session {id}: copying it from {}: {e}", source.display());
false
}
}
}
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
if !from.is_dir() {
return Ok(());
}
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let dest = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &dest)?;
} else if !dest.exists() {
std::fs::copy(entry.path(), dest)?;
}
}
Ok(())
}
/// The project directory name Claude Code uses for `cwd`.
pub(crate) fn escape(cwd: &Path) -> String {
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
@@ -207,6 +268,26 @@ mod tests {
json!({"type": "assistant", "uuid": id, "parentUuid": parent, "message": {"role": "assistant", "content": content}})
}
#[test]
fn a_session_from_another_config_dir_is_copied_in() {
let root = tempfile::tempdir().unwrap();
let (old, new) = (root.path().join(".claude-2"), root.path().join(".claude-3"));
let cwd = Path::new("/work/app");
let project = old.join("projects").join(escape(cwd));
std::fs::create_dir_all(project.join("s1/subagents")).unwrap();
std::fs::write(project.join("s1.jsonl"), "{}\n").unwrap();
std::fs::write(project.join("s1/subagents/a.jsonl"), "{}\n").unwrap();
std::fs::create_dir_all(new.join("projects")).unwrap();
assert!(!adopt(&new, cwd, "missing"));
assert!(adopt(&new, cwd, "s1"));
let copied = new.join("projects").join(escape(cwd));
assert_eq!(transcript(&new, cwd, "s1"), copied.join("s1.jsonl"));
assert!(copied.join("s1/subagents/a.jsonl").is_file());
assert!(project.join("s1.jsonl").is_file(), "the original stays");
assert!(adopt(&new, cwd, "s1"));
}
#[test]
fn the_newest_branch_is_the_conversation() {
let entries = vec![
+53 -19
Переглянути файл
@@ -178,6 +178,8 @@ struct Session {
additional_dirs: Vec<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -334,6 +336,12 @@ impl Shim {
Some(history::transcript(self.config.config_dir.as_deref()?, cwd, id))
}
/// Whether session `id` is in the configuration directory, copied there from another one
/// if need be (see [`history::adopt`]).
fn adopt(&self, cwd: &Path, id: &str) -> bool {
self.config.config_dir.as_deref().is_some_and(|dir| history::adopt(dir, cwd, id))
}
/// The conversation a session started with `start` begins with.
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
let (id, at) = match start {
@@ -370,6 +378,7 @@ impl Shim {
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs: additional_dirs(params),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -435,10 +444,13 @@ impl Shim {
let id = params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
let cwd = self.cwd_of(&params);
let (start, pending) = match self.load_pending(id) {
Some(s) => (s, true),
None if self.transcript(&cwd, id).is_some_and(|p| p.exists()) => {
(Start::Resume { id: id.to_owned(), at: None }, false)
Some(s) => {
if let Start::Resume { id: from, .. } | Start::Fork { from, .. } = &s {
self.adopt(&cwd, from);
}
(s, true)
}
None if self.adopt(&cwd, id) => (Start::Resume { id: id.to_owned(), at: None }, false),
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
};
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
@@ -451,24 +463,43 @@ impl Shim {
Ok(json!({ "configOptions": session.st.lock().settings.options() }))
}
"session/fork" => {
let source = self.session(&params)?;
let id = new_uuid(false);
let (start, settings) = {
let st = source.st.lock();
let start = match &st.start {
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
}
Start::New { .. } => Start::New { id: id.clone() },
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
}
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
};
(start, st.settings.clone())
let source_id =
params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
let source = self.sessions.lock().get(source_id).cloned();
// The host names the fork's session id so the task knows it before the CLI
// starts; only a canonical UUID is accepted.
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
if let Some(target) = requested
&& !crate::canonical_uuid(target)
{
return Err(invalid("A fork session id must be a canonical UUID"));
}
let id = requested.map_or_else(|| new_uuid(false), str::to_owned);
if self.sessions.lock().contains_key(&id) {
return Err(invalid(format!("session {id} is already open")));
}
let cwd = source.as_ref().map_or_else(|| self.cwd_of(&params), |session| session.cwd.clone());
let (start, settings) = match &source {
Some(source) => {
let st = source.st.lock();
let start = match &st.start {
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
}
Start::New { .. } => Start::New { id: id.clone() },
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
}
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
};
(start, st.settings.clone())
}
// A recorded session is not open in this connection: the CLI forks it
// from its transcript on disk when the task's first prompt starts it.
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
};
self.save_pending(&id, Some(&start));
let session = self.add_session(&id, source.cwd.clone(), start, true, &params);
let session = self.add_session(&id, cwd, start, true, &params);
session.st.lock().settings = settings;
let options = session.st.lock().settings.options();
Ok(json!({ "sessionId": id, "configOptions": options }))
@@ -703,6 +734,9 @@ impl Session {
if let Some(settings) = &self.skills_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
+92
Переглянути файл
@@ -464,6 +464,7 @@ async fn replay_simple() {
let args = r.cli.launched.lock()[0].clone();
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
assert!(!args.contains(&"--no-session-persistence".to_owned()));
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
}
@@ -652,6 +653,84 @@ async fn replay_resume() {
assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
/// Registering a fork must not start a process: its first prompt does.
struct NoLaunch;
impl Cli for NoLaunch {
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
panic!("session/fork must not launch the CLI")
}
}
let config = tempfile::tempdir().unwrap();
let pending = tempfile::tempdir().unwrap();
let h = Harness::connect(
Arc::new(NoLaunch),
config.path().to_path_buf(),
pending.path().to_path_buf(),
std::env::temp_dir(),
Vec::new(),
)
.await;
let source = "11111111-1111-4111-8111-111111111111";
let target = "22222222-2222-4222-8222-222222222222";
let reply = h
.request(
"session/fork",
json!({
"sessionId": source,
"cwd": h.cwd,
"mcpServers": [],
"_meta": { "openidea": { "forkSessionId": target } }
}),
)
.await
.unwrap();
assert_eq!(reply["sessionId"], target);
// The host chose this id for the fork: the next process must fork the recorded
// session under exactly it.
let saved: Value =
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap();
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
struct NoLaunch;
impl Cli for NoLaunch {
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
panic!("no process")
}
}
let config = tempfile::tempdir().unwrap();
let pending = tempfile::tempdir().unwrap();
let h = Harness::connect(
Arc::new(NoLaunch),
config.path().to_path_buf(),
pending.path().to_path_buf(),
std::env::temp_dir(),
Vec::new(),
)
.await;
for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] {
let error = h
.request(
"session/fork",
json!({
"sessionId": "11111111-1111-4111-8111-111111111111",
"cwd": h.cwd,
"mcpServers": [],
"_meta": { "openidea": { "forkSessionId": rejected } }
}),
)
.await
.expect_err("only a canonical id may name the fork");
assert!(error.to_string().contains("canonical"), "{rejected}: {error}");
}
}
// ---------- recording ----------
/// Passes the real CLI's stdio through, keeping what went over it.
@@ -1350,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() {
assert_eq!(additional_dirs(&params), ["/w/web", "/w/docs"]);
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_session_is_not_saved() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({ "cwd": h.cwd, "mcpServers": [], "_meta": { "openidea": { "ephemeral": true } } });
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
}
+31 -5
Переглянути файл
@@ -8,43 +8,69 @@ pub(crate) struct BuiltinCommandSpec {
pub name: &'static str,
pub description: &'static str,
pub hint: Option<&'static str>,
pub choices: &'static [(&'static str, &'static str)],
}
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "mcp",
description: "Show the status of the MCP servers, or reconnect them.",
hint: Some("[reconnect]"),
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
BuiltinCommandSpec {
name: "status",
description: "Display session configuration and token usage.",
hint: None,
choices: &[],
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
BuiltinCommandSpec {
name: "review",
description: "Review uncommitted changes, or review with custom instructions.",
hint: Some("optional review instructions"),
choices: &[],
},
BuiltinCommandSpec {
name: "review-branch",
description: "Review changes relative to a base branch.",
hint: Some("branch name"),
choices: &[],
},
BuiltinCommandSpec {
name: "review-commit",
description: "Review a specific commit.",
hint: Some("commit sha"),
choices: &[],
},
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
BuiltinCommandSpec {
name: "compact",
description: "Summarize conversation to avoid hitting the context limit.",
hint: None,
choices: &[],
},
BuiltinCommandSpec {
name: "goal",
description: "Set a goal to keep pursuing.",
hint: Some("[<objective>|clear|pause|resume]"),
choices: &[
("clear", "Clear the current goal."),
("pause", "Pause the current goal."),
("resume", "Resume a paused goal."),
],
},
BuiltinCommandSpec {
name: "rename",
description: "Rename the current session.",
hint: Some("new name"),
choices: &[],
},
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
BuiltinCommandSpec {
name: "logout",
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
hint: None,
choices: &[],
},
];
+27 -6
Переглянути файл
@@ -14,7 +14,7 @@ mod tests;
use super::Shim;
use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec;
use crate::{AgentCommand, AgentCommandSource};
use crate::{AgentCommand, AgentCommandChoice, AgentCommandSource};
use commands::{BuiltinCommand, ParsedCommand};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::Mutex;
@@ -47,6 +47,14 @@ pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
description: command.description.to_owned(),
hint: command.hint.map(str::to_owned),
source: AgentCommandSource::Command,
choices: command
.choices
.iter()
.map(|(name, description)| AgentCommandChoice {
name: (*name).to_owned(),
description: (*description).to_owned(),
})
.collect(),
})
.collect()
}
@@ -108,7 +116,7 @@ pub(crate) async fn discover(
let options = translate::config_options(&models, &settings);
let levels = crate::config::options_of(&json!({ "configOptions": options }))
.into_iter()
.filter(|o| o.category.as_deref() == Some("thought_level"))
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
.collect();
(model.id.clone(), levels)
})
@@ -492,8 +500,14 @@ impl CodexShim {
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
request["ephemeral"] = json!(true);
}
let result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None);
let mut settings = Settings::of(&result, &models);
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
let (id, options) = self.open_thread(&result, &models, Some(settings));
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
@@ -510,7 +524,9 @@ impl CodexShim {
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
let result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None);
let mut settings = Settings::of(&result, &models);
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
let (_, options) = self.open_thread(&result, &models, Some(settings));
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
let thread = result.get("thread").unwrap_or(&Value::Null);
for update in translate::history(thread, cwd.as_deref()) {
@@ -613,6 +629,9 @@ impl CodexShim {
if let Some(effort) = &s.effort {
request["effort"] = json!(effort);
}
if let Some(tier) = s.service_tier_override(&models) {
request["serviceTier"] = json!(tier);
}
}
self.call("turn/start", request).await
}
@@ -1470,14 +1489,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
let message = translate::error_message(&e);
return match translate::classify(&e, rate_limits) {
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
Failure::UsageLimit(resets) => Err(ResponseError {
code: codes::INTERNAL_ERROR,
message,
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
}),
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
};
}
_ => "end_turn",
@@ -1595,3 +1613,6 @@ fn mcp_text(response: &Value) -> String {
.collect::<Vec<_>>();
format!("MCP servers:\n{}", lines.join("\n"))
}
#[cfg(test)]
mod reconnect_tests;
+217
Переглянути файл
@@ -0,0 +1,217 @@
//! User-facing task operations through the native shim, with a local app-server stand-in.
use super::*;
use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask};
#[derive(Default)]
struct Runtime {
models: Mutex<HashMap<String, String>>,
hide_a: std::sync::atomic::AtomicBool,
turns: Mutex<Vec<Value>>,
tiers: Mutex<HashMap<String, Value>>,
servers: Mutex<Vec<Peer>>,
}
struct Connection {
runtime: Arc<Runtime>,
peer: OnceLock<Peer>,
}
impl Handler for Connection {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
match method {
"initialize" => Ok(json!({})),
"model/list" => {
let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})];
if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) {
data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]}));
}
Ok(json!({"data":data}))
}
"config/read" => Ok(json!({"layers":[]})),
"skills/list" => Ok(json!({"data":[]})),
"thread/start" | "thread/resume" => {
let mut models = self.runtime.models.lock();
let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len()));
let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone();
Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model,
"serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))}))
}
"turn/start" => {
let id = p["threadId"].as_str().unwrap();
self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into());
if let Some(tier) = p.get("serviceTier") {
self.runtime.tiers.lock().insert(id.into(), tier.clone());
}
self.runtime.turns.lock().push(p.clone());
self.peer
.get()
.unwrap()
.notify(
"turn/completed",
json!({"threadId":id,
"turn":{"id":"t","status":"completed"}}),
)
.unwrap();
Ok(json!({"turn":{"id":"t"}}))
}
_ => Err((codes::METHOD_NOT_FOUND, method.into())),
}
}
}
fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
let agents = dir.join("agents");
crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap();
AgentManager::with_connector(
crate::AgentPaths {
project_root: dir.into(),
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
custom_agents_dir: Some(agents),
home_dir: Some(dir.into()),
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
Arc::new(move |spec, _, client, _| {
assert_eq!(spec.driver, crate::provider::Driver::Codex);
let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() });
let (a, b) = tokio::io::duplex(1 << 20);
let (r, w) = tokio::io::split(b);
let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines);
handler.peer.set(server.clone()).ok().unwrap();
runtime.servers.lock().push(server);
attach(client, |events| {
let (r, w) = tokio::io::split(a);
Ok(Peer::connect_framed(r, w, events, Framing::Lines))
})
}),
)
}
fn prompt() -> AgentPrompt {
AgentPrompt { text: "fixture".into(), ..Default::default() }
}
async fn ready(mgr: &AgentManager, id: &str) {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let task = mgr.task(id).unwrap();
let (status, busy) = {
let s = task.state.lock();
(s.task.status, s.busy)
};
assert_ne!(status, AgentStatus::Failed);
if status == AgentStatus::Ready && !busy {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
}
async fn send(mgr: &AgentManager, id: &str) {
mgr.prompt(id, prompt(), false).await.unwrap();
ready(mgr, id).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() {
for late_model in [0, 1, 2, 3] {
for choice in [Some("true"), Some("false"), None] {
let tmp = tempfile::tempdir().unwrap();
let runtime = Arc::new(Runtime::default());
let mgr = manager(tmp.path(), runtime.clone());
let task = mgr
.create(NewAgentTask {
provider: "codex".into(),
prompt: prompt(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
ready(&mgr, &task.id).await;
let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
if let Some(value) = choice {
mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap();
}
send(&mgr, &task.id).await;
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
);
mgr.set_config(&task.id, "model", "b".into()).await.unwrap();
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
send(&mgr, &task.id).await;
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|_| json!("default")).as_ref()
);
mgr.shutdown();
drop(mgr);
runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst);
let mut mgr = manager(tmp.path(), runtime.clone());
send(&mgr, &task.id).await; // Reconnect while still on Standard-only B.
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|_| json!("default")).as_ref()
);
if late_model != 0 {
// Catalog knows A, but the session's picker has not received it yet.
let current = mgr.task(&task.id).unwrap();
let mut s = current.state.lock();
let catalog = serde_json::from_value(
json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::<Vec<_>>() }}),
)
.unwrap();
mgr.shared
.known
.lock()
.entry("codex".into())
.or_default()
.catalogs
.insert(mgr.shared.root_key(), catalog);
s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a");
}
mgr.set_config(&task.id, "model", "a".into()).await.unwrap();
if late_model == 3 {
// An older saved pending switch has no retained intent field.
mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None;
mgr.shutdown();
mgr = manager(tmp.path(), runtime.clone());
}
let displayed = mgr
.task(&task.id)
.unwrap()
.state
.lock()
.snapshot()
.config
.iter()
.find(|o| o.id == "service_tier")
.unwrap()
.current
.clone();
assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true")));
send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting.
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
);
let other = mgr
.create(NewAgentTask {
provider: "codex".into(),
prompt: prompt(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
ready(&mgr, &other.id).await;
assert!(
runtime.turns.lock().last().unwrap().get("serviceTier").is_none(),
"choices must not leak to another task"
);
mgr.shutdown();
}
}
}
+250 -1
Переглянути файл
@@ -110,7 +110,8 @@ for line in sys.stdin:
cursor = request['params']['cursor']
model = 'one' if cursor is None else 'two'
result = {'data': [{'id': model, 'isDefault': cursor is None,
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}],
'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}],
'nextCursor': 'second-page' if cursor is None else None}
else:
raise RuntimeError('must not create a thread or prompt: ' + method)
@@ -125,6 +126,7 @@ for line in sys.stdin:
driver: crate::provider::Driver::Codex,
command: script.to_string_lossy().into_owned(),
args: Vec::new(),
additional_args_len: 0,
env: Vec::new(),
login_hint: String::new(),
source: crate::AgentSource::Builtin,
@@ -138,6 +140,9 @@ for line in sys.stdin:
.collect();
assert_eq!(models, ["one", "two"]);
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
assert!(found.config.iter().any(|o| o.id == SERVICE_TIER));
assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER));
assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER));
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(
@@ -162,6 +167,72 @@ for line in sys.stdin:
// ---- Pure translations -------------------------------------------------------------
#[test]
fn fast_is_offered_only_when_the_model_advertises_it() {
for capability in [
json!({ "additionalSpeedTiers": ["fast"] }),
json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }),
json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }),
] {
let mut model = json!({ "id": "supported", "isDefault": true });
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] }));
let mut settings = Settings::of(&json!({}), &models);
let options = config_options(&models, &settings);
let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option");
assert_eq!(fast["category"], "model_config");
assert_eq!(fast["currentValue"], "false");
assert!(settings.set(&models, "service_tier", "true").is_ok());
assert!(settings.set(&models, "service_tier", "invalid").is_err());
let selected = settings.service_tier_override(&models).map(str::to_owned);
settings.set(&models, "model", "unsupported").unwrap();
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
assert!(settings.set(&models, "service_tier", "true").is_err());
assert_eq!(settings.service_tier_override(&models), Some("default"));
settings.set(&models, "model", "supported").unwrap();
assert_eq!(settings.service_tier_override(&models), selected.as_deref());
let options = config_options(&models, &settings);
assert_eq!(
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
"true"
);
}
for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] {
let mut model = json!({ "id": "old", "isDefault": true });
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
let models = models_of(&json!({ "data": [model] }));
let settings = Settings::of(&json!({}), &models);
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
}
}
#[test]
fn fast_defaults_do_not_become_user_overrides() {
let models = models_of(&json!({ "data": [{
"id": "m", "isDefault": true, "defaultServiceTier": "fast",
"serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }]
}] }));
for (reported, current) in [
(json!({}), "true"),
(json!({ "serviceTier": null }), "false"),
(json!({ "serviceTier": "fast" }), "true"),
(json!({ "serviceTier": "priority" }), "true"),
(json!({ "serviceTier": "default" }), "false"),
] {
let mut settings = Settings::of(&reported, &models);
let options = config_options(&models, &settings);
assert_eq!(
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
current
);
assert_eq!(settings.service_tier_override(&models), None);
settings.set(&models, SERVICE_TIER, "true").unwrap();
assert_eq!(settings.service_tier_override(&models), Some("fast"));
settings.set(&models, SERVICE_TIER, "false").unwrap();
assert_eq!(settings.service_tier_override(&models), Some("default"));
}
}
fn models() -> Vec<ModelInfo> {
models_of(&json!({"data": [
{"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true,
@@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() {
Settings {
model: "big".into(),
effort: Some("low".into()),
service_tier: None,
fast_override: None,
mode: Mode::Ask,
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
collaboration_mode_override: None,
@@ -382,6 +455,90 @@ fn failures_are_classified() {
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
}
#[test]
fn failed_turns_preserve_codex_error_diagnostics() {
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
assert_eq!(failure.code, codes::INTERNAL_ERROR);
assert_eq!(failure.message, expected);
}
// A completed turn's own error wins over an older error notification.
let failure = stop_reason(
&json!({ "status": "failed", "error": policy }),
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
None,
)
.unwrap_err();
assert_eq!(failure.message, expected);
}
#[test]
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
for (value, expected) in [
(
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
"Context is full.\nCodex error: contextWindowExceeded",
),
(
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
),
(
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
"Failed\nbecause",
),
(
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
"Codex failed\nDetails\nCodex error: cyberPolicy",
),
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
(json!({}), "Codex failed"),
] {
assert_eq!(error_message(&value), expected);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
for notification_only in [false, true] {
let mut transcript = load(Scenario::UsageLimit.file());
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
for (out, frame) in &mut transcript.frames {
if *out {
continue;
}
match frame["method"].as_str() {
Some("error") => frame["params"]["error"] = policy.clone(),
Some("turn/completed") => {
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
}
_ => {}
}
}
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
match result(&results, "prompt") {
Err(RpcError::Server { code, message, .. }) => {
assert_eq!(*code, codes::INTERNAL_ERROR);
assert_eq!(
message,
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
);
}
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
}
}
}
#[test]
fn approvals_offer_what_codex_offers_and_always_a_decline() {
let params = json!({"availableDecisions": ["accept",
@@ -648,6 +805,7 @@ enum Scenario {
Steer,
Simple,
MultiTurn,
ServiceTier { first: Option<bool>, second: Option<bool> },
Approvals,
UsageLimit,
Subagent,
@@ -666,6 +824,7 @@ impl Scenario {
Scenario::Steer => "steer",
Scenario::Simple => "simple",
Scenario::MultiTurn => "multi_turn",
Scenario::ServiceTier { .. } => "multi_turn",
Scenario::Approvals => "approvals",
Scenario::UsageLimit => "usage_limit",
Scenario::Subagent => "subagent",
@@ -772,6 +931,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await));
out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await));
}
Scenario::ServiceTier { first, second } => {
for (label, choice) in [("first", first), ("second", second)] {
if let Some(fast) = choice {
request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" }))
.await
.expect("the model advertises Fast");
}
out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await));
}
}
Scenario::Approvals => {
client.answers.lock().extend([Some("accept"), None]);
out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await));
@@ -1304,6 +1473,44 @@ fn thread_names_are_the_first_line_of_the_reply() {
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
}
#[tokio::test(flavor = "multi_thread")]
async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() {
for (first, second, expected) in [
(Some(true), Some(false), [Some("fast"), Some("default")]),
(Some(false), Some(true), [Some("default"), Some("fast")]),
(Some(true), None, [Some("fast"), Some("fast")]),
(None, None, [None, None]),
] {
let scenario = Scenario::ServiceTier { first, second };
let mut transcript = load(scenario.file());
for (out, frame) in &mut transcript.frames {
if *out {
continue;
}
if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) {
for model in models {
model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]);
model["defaultServiceTier"] = json!("fast");
}
}
if frame.pointer("/result/thread").is_some() {
frame["result"]["serviceTier"] = json!("fast");
}
}
let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await;
assert!(result(&results, "first").is_ok());
assert!(result(&results, "second").is_ok());
let starts = sent(&frames, "turn/start");
assert_eq!(starts.len(), 2);
for (start, expected) in starts.iter().zip(expected) {
assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref());
assert!(start["params"].get("serviceTierForTurn").is_none());
}
assert!(sent(&frames, "turn/settings/update").is_empty());
assert!(sent(&frames, "config/value/write").is_empty());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn settings_apply_to_the_next_turn() {
let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
@@ -1877,6 +2084,11 @@ fn skills_become_commands_with_their_invocation_names() {
let commands = crate::config::commands_of(&update, "codex");
assert!(commands.iter().all(|c| c.source == crate::AgentCommandSource::Skill));
assert_eq!(commands[0].name, "$review");
let builtins = builtin_commands();
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
assert!(skill_commands(&json!({})).is_none());
}
@@ -1891,3 +2103,40 @@ fn workspace_roots_join_the_thread_roots() {
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
for ephemeral in [true, false] {
let tmp = tempfile::tempdir().unwrap();
let cwd = tmp.path().to_string_lossy().into_owned();
let server = Arc::new(TrustServer {
cwd: cwd.clone(),
disabled: false,
other_project: false,
write_error: false,
overridden: false,
calls: Mutex::default(),
});
let client = Arc::new(Client::default());
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
let acp = attach(client.clone(), |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
request(&acp, "initialize", json!({})).await.unwrap();
let mut params = json!({"cwd": cwd, "mcpServers": []});
if ephemeral {
params["_meta"] = json!({"openidea": {"ephemeral": true}});
}
request(&acp, "session/new", params).await.unwrap();
let calls = server.calls.lock();
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
drop(calls);
acp.kill();
native.kill();
}
}
+84 -7
Переглянути файл
@@ -97,6 +97,8 @@ pub(super) struct ModelInfo {
/// `(effort, description)`.
pub efforts: Vec<(String, String)>,
pub default_effort: Option<String>,
pub fast_tier: Option<String>,
pub default_service_tier: Option<String>,
pub is_default: bool,
pub hidden: bool,
}
@@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec<ModelInfo> {
})
.collect(),
default_effort: str_of(m, "defaultReasoningEffort"),
fast_tier: m
.get("serviceTiers")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|tier| tier.get("id").and_then(Value::as_str))
.chain(
m.get("additionalSpeedTiers")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str),
)
.find(|tier| is_fast_tier(tier))
.map(str::to_owned),
default_service_tier: str_of(m, "defaultServiceTier"),
is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true),
hidden: m.get("hidden").and_then(Value::as_bool) == Some(true),
id,
@@ -137,6 +155,9 @@ pub(super) struct Settings {
/// A model id from `model/list`, or the one the thread reported.
pub model: String,
pub effort: Option<String>,
pub service_tier: Option<String>,
/// No choice preserves the runtime's default; false explicitly selects Standard.
pub fast_override: Option<bool>,
pub mode: Mode,
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
/// part of the turn contract rather than the sandbox permission mode above.
@@ -158,6 +179,12 @@ impl Settings {
let mut s = Settings {
model,
effort: str_of(result, "reasoningEffort"),
service_tier: match result.get("serviceTier") {
// A live thread can explicitly report Standard even when the catalog defaults to Fast.
Some(Value::Null) => Some("default".into()),
_ => str_of(result, "serviceTier"),
},
fast_override: None,
mode: Mode::of(
result.get("approvalPolicy").unwrap_or(&Value::Null),
result.get("sandbox").unwrap_or(&Value::Null),
@@ -205,6 +232,16 @@ impl Settings {
}
self.effort = Some(value.to_owned());
}
SERVICE_TIER => {
if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) {
return Err(format!("{} has no Fast mode", self.model));
}
self.fast_override = Some(match value {
"true" => true,
"false" => false,
_ => return Err(format!("unknown Fast mode {value}")),
});
}
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
COLLABORATION_MODE => {
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
@@ -217,16 +254,32 @@ impl Settings {
}
Ok(())
}
/// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast.
pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> {
match self.fast_override {
Some(true) => Some(
models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"),
),
Some(false) => Some("default"),
None => None,
}
}
}
pub(super) const MODEL: &str = "model";
pub(super) const EFFORT: &str = "reasoning_effort";
pub(super) const SERVICE_TIER: &str = "service_tier";
pub(super) const MODE: &str = "mode";
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
fn is_fast_tier(tier: &str) -> bool {
matches!(tier, "fast" | "priority")
}
/// ACP `configOptions`: model, its supported settings and session modes.
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
let mut model_values: Vec<Value> = models
.iter()
@@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
"currentValue": effort, "options": values,
}));
}
if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) {
let fast = s.fast_override.unwrap_or_else(|| {
s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier)
});
out.push(json!({
"id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select",
"currentValue": if fast { "true" } else { "false" },
"options": [select_value("false", "Standard", None), select_value("true", "Fast", None)],
}));
}
out.push(json!({
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
@@ -677,7 +740,7 @@ pub(super) enum Failure {
UsageLimit(Option<f64>),
/// Signed out or refused.
Auth,
/// The model declined.
/// The server blocked the turn under a safety policy.
Refusal,
Other,
}
@@ -717,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
exhausted.map(|s| s * 1000.0)
}
/// The text a failed turn reports: codex's message, with its details.
/// The text a failed turn reports: Codex's message, details and diagnostic code.
pub(super) fn error_message(error: &Value) -> String {
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
_ => message.to_owned(),
let original =
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
let mut message = original.to_owned();
if let Some(details) =
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
&& !original.contains(details)
{
message.push('\n');
message.push_str(details);
}
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
message.push_str(&format!("\nCodex error: {code}"));
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
message.push_str(&format!(" (HTTP {status})"));
}
}
message
}
/// One choice of an approval: what ACP shows and what codex gets back.
+258 -8
Переглянути файл
@@ -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>,
@@ -450,6 +522,7 @@ impl CopilotShim {
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
"_openidea/context_usage" => self.context_usage(&params).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close_session(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
@@ -465,7 +538,7 @@ impl CopilotShim {
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
},
"agentInfo": {
"name": "copilot",
@@ -583,12 +656,47 @@ impl CopilotShim {
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
self.sync_usage_metrics(&actual_id);
Ok(json!({
"sessionId": actual_id,
"configOptions": options,
}))
}
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
self.runtime.spawn(async move {
let Ok(metrics) = shim.call("session.usage.getMetrics", json!({ "sessionId": sid })).await else {
return;
};
let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) else {
return;
};
let catalog = shim.catalog.try_lock().ok().and_then(|g| g.clone());
let update = {
let mut st = shim.state.lock();
st.sessions.get_mut(&sid).and_then(|entry| {
entry.translator.set_total_nano_aiu(nano_aiu);
let used = entry.translator.last_used_tokens?;
let size = entry
.translator
.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or_else(|| {
catalog.as_deref().and_then(|m| entry.settings.active_context_tokens(m)).filter(|&s| s > 0)
})?;
Some(entry.translator.usage_update(used, size))
})
};
if let Some(update) = update {
shim.send_update(&sid, update);
}
});
}
fn publish_commands(self: &Arc<Self>, session_id: &str, cwd: &str) {
let shim = self.clone();
let sid = session_id.to_owned();
@@ -663,25 +771,152 @@ impl CopilotShim {
let new_limit = next_settings.active_context_tokens(&catalog);
let options = models::config_options(&catalog, &next_settings);
{
let usage_update = {
let mut st = self.state.lock();
if let Some(entry) = st.sessions.get_mut(session_id) {
entry.settings = next_settings;
if matches!(option, MODEL | CONTEXT_TIER)
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
{
Some(entry.translator.usage_update(used, size))
} else {
None
}
} else {
None
}
}
if matches!(option, MODEL | CONTEXT_TIER)
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
{
self.send_update(session_id, json!({ "sessionUpdate": "usage_update", "used": used, "size": size }));
};
if let Some(update) = usage_update {
self.send_update(session_id, update);
}
Ok(json!({ "configOptions": options }))
}
async fn context_usage(&self, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?;
let catalog = self.models().await.ok();
let (model_id, fallback_limit, snapshot) = {
let st = self.state.lock();
let entry = st.sessions.get(session_id).ok_or_else(|| invalid(format!("unknown session {session_id}")))?;
let limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
(entry.settings.model.clone(), limit, entry.translator.last_usage_snapshot.clone())
};
let (attr_res, metrics_res) = tokio::join!(
self.call("session.metadata.getContextAttribution", json!({ "sessionId": session_id })),
self.call("session.usage.getMetrics", json!({ "sessionId": session_id })),
);
if let Ok(metrics) = metrics_res
&& let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64)
&& let Some(entry) = self.state.lock().sessions.get_mut(session_id)
{
entry.translator.set_total_nano_aiu(nano_aiu);
}
let mut usage =
attr_res.ok().and_then(|v| translate::context_usage_from_attribution(&v, &model_id, fallback_limit));
if usage.is_none()
&& !model_id.is_empty()
&& let Ok(info) = self
.call("session.metadata.contextInfo", json!({ "sessionId": session_id, "modelName": model_id }))
.await
{
usage = translate::context_usage_from_context_info(&info, &model_id, fallback_limit);
}
let usage = usage
.or_else(|| snapshot.as_ref().map(|snap| translate::context_usage_from_snapshot(snap, &model_id)))
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Context details are not available yet"))?;
let meter_update = {
let mut st = self.state.lock();
st.sessions.get_mut(session_id).map(|entry| {
entry.translator.last_used_tokens = Some(usage.total_tokens);
entry.translator.usage_update(usage.total_tokens, usage.max_tokens)
})
};
if let Some(update) = meter_update {
self.send_update(session_id, update);
}
serde_json::to_value(usage).map_err(|e| error(codes::INTERNAL_ERROR, e.to_string()))
}
async fn compact_session(&self, session_id: &str, instructions: Option<&str>) -> Result<Value, ResponseError> {
let mut req = json!({
"sessionId": session_id,
"trigger": "manual",
});
if let Some(text) = instructions.map(str::trim).filter(|s| !s.is_empty()) {
req["customInstructions"] = json!(text);
}
let res = self.call("session.history.compact", req).await?;
let success = res.get("success").and_then(Value::as_bool).unwrap_or(true);
if !success {
let msg = res.get("error").and_then(Value::as_str).unwrap_or("Conversation compaction failed");
return Err(error(codes::INTERNAL_ERROR, msg));
}
let catalog = self.models().await.ok();
let meter_update = {
let mut st = self.state.lock();
st.sessions.get_mut(session_id).and_then(|entry| {
let cw = res.get("contextWindow")?;
let used = cw.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())?;
let fallback_limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
let size = cw
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit.filter(|&n| n > 0))?;
let u32_field = |k: &str| cw.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
entry.translator.record_snapshot(translate::UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_field("systemTokens"),
tool_definitions_tokens: u32_field("toolDefinitionsTokens"),
conversation_tokens: u32_field("conversationTokens"),
});
Some(entry.translator.usage_update(used, size))
})
};
if let Some(update) = meter_update {
self.send_update(session_id, update);
}
let tokens_removed = res.get("tokensRemoved").and_then(Value::as_u64).unwrap_or(0);
let messages_removed = res.get("messagesRemoved").and_then(Value::as_u64).unwrap_or(0);
let summary = if tokens_removed > 0 || messages_removed > 0 {
format!("Compacted conversation ({tokens_removed} tokens, {messages_removed} messages removed).")
} else {
"Conversation compacted.".to_owned()
};
self.send_update(
session_id,
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": summary } }),
);
if let Some(entry) = self.state.lock().sessions.get_mut(session_id) {
entry.early_cancel = None;
}
Ok(json!({ "stopReason": "end_turn" }))
}
async fn prompt(&self, params: &Value, steer: bool) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?.to_owned();
let blocks = params.get("prompt").and_then(Value::as_array).ok_or_else(|| invalid("missing prompt"))?;
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
if !steer
&& attachments.is_empty()
&& let Some(instructions) = parse_compact_command(&text)
{
cleanup_files(&temp_files);
return self.compact_session(&session_id, instructions).await;
}
if steer {
let (is_running, main_busy) = {
let st = self.state.lock();
@@ -998,6 +1233,21 @@ impl CopilotShim {
}
}
fn parse_compact_command(text: &str) -> Option<Option<&str>> {
let trimmed = text.trim();
if trimmed == "/compact" {
return Some(None);
}
let rest = trimmed.strip_prefix("/compact")?;
let first = rest.chars().next()?;
if first.is_whitespace() {
let focus = rest.trim();
Some((!focus.is_empty()).then_some(focus))
} else {
None
}
}
fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Value>, Vec<PathBuf>) {
let mut text_parts = Vec::new();
let mut attachments = Vec::new();
+309
Переглянути файл
@@ -1,6 +1,11 @@
use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults};
use super::translate::{
self, EventTranslator, UsageSnapshot, context_usage_from_attribution, context_usage_from_context_info,
context_usage_from_snapshot,
};
use super::{acp_args, acp_fallback_spec, attach, headless_args};
use crate::config;
use crate::model::{AgentContextCategory, AgentContextUsage};
use crate::provider::Driver;
use ide_jsonrpc::{Framing, Handler, Peer, codes};
use parking_lot::Mutex;
@@ -443,6 +448,38 @@ impl Handler for FakeCopilotServer {
] })),
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
"session.abort" => Ok(json!({})),
"session.usage.getMetrics" => Ok(json!({
"totalNanoAiu": 4_211_400_000_000.0,
"totalPremiumRequestCost": 12.0,
})),
"session.metadata.getContextAttribution" => Ok(json!({
"contextAttribution": {
"totalTokens": 405_200,
"limit": 1_000_000,
"promptTokenLimit": 936_000,
"bufferTokens": 64_000,
"compactionThreshold": 800_000,
"modelId": "gemini-4-carbon",
"entries": [
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 203_000, "parentId": "system:root" },
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 }
]
}
})),
"session.history.compact" => Ok(json!({
"success": true,
"tokensRemoved": 250_000,
"messagesRemoved": 12,
"contextWindow": {
"currentTokens": 155_200,
"tokenLimit": 1_000_000,
"systemTokens": 20_000,
"toolDefinitionsTokens": 100_000,
"conversationTokens": 35_200
}
})),
"session.send" if self.background_shell => {
if let Some(peer) = self.peer.get().cloned() {
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
@@ -795,3 +832,275 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
"contextAttribution": {
"totalTokens": 405_200,
"limit": 1_000_000,
"bufferTokens": 64_000,
"compactionThreshold": 800_000,
"modelId": "gemini-4-carbon",
"entries": [
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 120_000, "parentId": "system:root" },
{ "kind": "toolDefinition", "id": "toolDefinition:view", "label": "view", "tokens": 83_000, "parentId": "system:root" },
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 },
{ "kind": "plugin", "id": "plugin:git", "label": "git", "tokens": 5_000 },
{ "kind": "skill", "id": "skill:pr", "label": "pr", "tokens": 5_000, "parentId": "plugin:git" }
]
}
});
let usage = context_usage_from_attribution(&payload, "fallback", None).unwrap();
assert_eq!(usage.total_tokens, 405_200);
assert_eq!(usage.max_tokens, 1_000_000);
assert_eq!(usage.reserved_tokens, Some(64_000));
assert_eq!(usage.auto_compact_threshold, Some(800_000));
assert_eq!(usage.is_auto_compact_enabled, Some(true));
assert_eq!(
usage.categories,
vec![
AgentContextCategory {
name: "System prompt".into(),
tokens: 20_000,
kind: Some("used".into()),
group: Some("System".into()),
},
AgentContextCategory {
name: "Tool Definitions".into(),
tokens: 203_000,
kind: Some("used".into()),
group: Some("System".into()),
},
AgentContextCategory {
name: "Tool Results".into(),
tokens: 69_000,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory {
name: "Messages".into(),
tokens: 108_200,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory {
name: "Skills".into(),
tokens: 5_000,
kind: Some("used".into()),
group: Some("User Context".into()),
},
AgentContextCategory { name: "Free space".into(), tokens: 530_800, kind: Some("free".into()), group: None },
]
);
}
#[test]
fn translates_context_info_and_usage_snapshot_fallbacks() {
let info = json!({
"contextInfo": {
"modelName": "claude-sonnet-4.5",
"systemTokens": 12_000,
"toolDefinitionsTokens": 48_000,
"conversationTokens": 40_000,
"totalTokens": 100_000,
"limit": 200_000,
"bufferTokens": 20_000,
"compactionThreshold": 160_000
}
});
let from_info = context_usage_from_context_info(&info, "fallback", None).unwrap();
assert_eq!(from_info.reserved_tokens, Some(20_000));
assert_eq!(
from_info.categories.iter().map(|c| (c.name.as_str(), c.tokens, c.group.as_deref())).collect::<Vec<_>>(),
vec![
("System prompt", 12_000, Some("System")),
("Tool Definitions", 48_000, Some("System")),
("Messages", 40_000, Some("User Context")),
("Free space", 80_000, None),
]
);
let from_snap = context_usage_from_snapshot(
&UsageSnapshot {
current_tokens: 50_000,
token_limit: 200_000,
system_tokens: Some(10_000),
tool_definitions_tokens: Some(25_000),
conversation_tokens: Some(15_000),
},
"gpt-5.6-sol",
);
assert_eq!(from_snap.total_tokens, 50_000);
assert_eq!(from_snap.max_tokens, 200_000);
assert_eq!(from_snap.categories.len(), 4);
}
#[test]
fn accumulates_copilot_credits_across_turns_subagents_and_compaction() {
let mut tr = EventTranslator::default();
let first = tr.translate(
"s1",
&json!({
"type": "session.usage_info",
"data": { "currentTokens": 40_000, "tokenLimit": 200_000, "systemTokens": 10_000, "toolDefinitionsTokens": 20_000, "conversationTokens": 10_000 }
}),
Some(200_000),
);
assert_eq!(first.updates[0].1["used"], 40_000);
assert!(first.updates[0].1.get("cost").is_none());
// Main-agent usage reports 1.5 credits; subagent usage adds 0.5 credits -> 2.0 credits total.
let main_usage = tr.translate(
"s1",
&json!({
"type": "assistant.usage",
"data": { "inputTokens": 45_000, "copilotUsage": { "totalNanoAiu": 1_500_000_000.0 } }
}),
Some(200_000),
);
assert_eq!(main_usage.updates[0].1["cost"]["currency"], "credits");
assert!((main_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 1.5).abs() < 1e-6);
let sub_usage = tr.translate(
"s1",
&json!({
"type": "assistant.usage",
"agentId": "sub-1",
"data": { "inputTokens": 12_000, "copilotUsage": { "totalNanoAiu": 500_000_000.0 } }
}),
Some(200_000),
);
assert_eq!(sub_usage.updates[0].1["used"], 45_000);
assert!((sub_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
// Compaction updates token count while keeping accumulated credits.
let compacted = tr.translate(
"s1",
&json!({
"type": "session.compaction_complete",
"data": { "success": true, "postCompactionTokens": 22_000, "tokenLimit": 200_000 }
}),
Some(200_000),
);
assert_eq!(compacted.updates[0].1["used"], 22_000);
assert!((compacted.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
}
#[test]
fn available_commands_includes_compact_when_omitted_by_server() {
let cmds = translate::available_commands(Some(&json!({ "commands": [{ "name": "review" }] })), None);
assert!(cmds.iter().any(|c| c["name"] == "compact"));
assert!(cmds.iter().any(|c| c["name"] == "review"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn context_usage_rpc_and_compact_command_work_end_to_end() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["contextUsage"], true);
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
let ctx: AgentContextUsage =
client.request("_openidea/context_usage", json!({ "sessionId": "cop-sess-1" }), None).await.unwrap();
assert_eq!(ctx.total_tokens, 405_200);
assert_eq!(ctx.max_tokens, 1_000_000);
assert_eq!(ctx.reserved_tokens, Some(64_000));
assert!(ctx.categories.iter().any(|c| c.name == "System prompt" && c.group.as_deref() == Some("System")));
assert!(ctx.categories.iter().any(|c| c.name == "Tool Definitions" && c.group.as_deref() == Some("System")));
assert!(ctx.categories.iter().any(|c| c.name == "Tool Results" && c.group.as_deref() == Some("User Context")));
assert!(ctx.categories.iter().any(|c| c.name == "Messages" && c.group.as_deref() == Some("User Context")));
// Syncing metrics updated usage_update with credits cost.
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(updates.0.lock().iter().any(|u| {
u["sessionUpdate"] == "usage_update"
&& u["used"] == 405_200
&& u["cost"]["currency"] == "credits"
&& (u["cost"]["amount"].as_f64().unwrap_or(0.0) - 4211.4).abs() < 0.01
}));
// `/compact` invokes `session.history.compact` instead of `session.send`.
let res: Value = client
.request(
"session/prompt",
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "/compact keep PR notes" }] }),
None,
)
.await
.unwrap();
assert_eq!(res["stopReason"], "end_turn");
assert!(server.calls.lock().iter().any(|(m, p)| {
m == "session.history.compact"
&& p["sessionId"] == "cop-sess-1"
&& p["trigger"] == "manual"
&& p["customInstructions"] == "keep PR notes"
}));
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(updates.0.lock().iter().any(|u| u["sessionUpdate"] == "usage_update" && u["used"] == 155_200));
}
#[test]
fn available_commands_preserves_input_choices() {
let cmds = json!({
"commands": [
{
"name": "skills",
"description": "Manage skills for enhanced capabilities",
"input": {
"hint": "[list|info|reload]",
"choices": [
{ "name": "list", "description": "List all available skills" },
{ "name": "info", "description": "Show details for a skill" },
{ "name": "INFO", "description": "Duplicate ignored" },
{ "name": "", "description": "Empty ignored" },
{ "name": "reload", "description": "Reload skills from disk" }
]
}
},
{
"name": "subconscious",
"description": "Manage memory",
"input": {
"choices": [{ "name": "run", "description": "Consolidate now" }]
}
}
]
});
let list = super::translate::available_commands(Some(&cmds), None);
let parsed = crate::config::commands_of(&json!({ "availableCommands": list }), "copilot");
// Then the built-in /compact.
assert_eq!(parsed.len(), 3);
assert_eq!(parsed[2].name, "compact");
assert_eq!(parsed[0].name, "skills");
assert_eq!(parsed[0].hint.as_deref(), Some("[list|info|reload]"));
assert_eq!(
parsed[0].choices,
vec![
crate::AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
crate::AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
crate::AgentCommandChoice { name: "reload".into(), description: "Reload skills from disk".into() },
]
);
assert_eq!(parsed[1].name, "subconscious");
assert_eq!(parsed[1].hint, None);
assert_eq!(
parsed[1].choices,
vec![crate::AgentCommandChoice { name: "run".into(), description: "Consolidate now".into() }]
);
}
+364 -20
Переглянути файл
@@ -2,11 +2,22 @@
//! permissions, slash commands, MCP servers) and ACP v1.
use crate::LIMITS_UPDATE;
use crate::model::{AgentContextCategory, AgentContextUsage};
use serde_json::{Map, Value, json};
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
const MAX_OUTPUT: usize = 64 * 1024;
const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct UsageSnapshot {
pub current_tokens: u32,
pub token_limit: u32,
pub system_tokens: Option<u32>,
pub tool_definitions_tokens: Option<u32>,
pub conversation_tokens: Option<u32>,
}
#[derive(Default)]
pub(super) struct EventTranslator {
@@ -18,6 +29,11 @@ pub(super) struct EventTranslator {
subagents: HashMap<String, String>,
/// Last reported prompt token count, used when updating context size.
pub last_used_tokens: Option<u32>,
/// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent.
pub last_usage_snapshot: Option<UsageSnapshot>,
/// Accumulated session AI-credit spend in nano-AIU (across main agent and subagents).
total_nano_aiu: f64,
has_nano_aiu: bool,
}
#[derive(Clone, Debug)]
@@ -46,6 +62,29 @@ impl EventTranslator {
self.streamed_messages.clear();
}
pub fn set_total_nano_aiu(&mut self, nano_aiu: f64) {
if nano_aiu.is_finite() && nano_aiu > 0.0 {
self.total_nano_aiu = nano_aiu;
self.has_nano_aiu = true;
}
}
pub fn record_snapshot(&mut self, snapshot: UsageSnapshot) {
self.last_used_tokens = Some(snapshot.current_tokens);
self.last_usage_snapshot = Some(snapshot);
}
pub fn usage_update(&self, used: u32, size: u32) -> Value {
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if self.has_nano_aiu && self.total_nano_aiu > 0.0 {
update["cost"] = json!({
"amount": self.total_nano_aiu / NANO_AIU_PER_CREDIT,
"currency": "credits",
});
}
update
}
pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let mut out = Translated { updates: Vec::new(), terminal: None };
let event_type = str_of(event, "type").unwrap_or_default();
@@ -239,36 +278,75 @@ impl EventTranslator {
}
}
"session.usage_info" => {
let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
let limit = data
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit);
let used = u32_of(data, "currentTokens");
let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit);
if let (Some(used), Some(size)) = (used, limit) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
self.record_snapshot(UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_of(data, "systemTokens"),
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
conversation_tokens: u32_of(data, "conversationTokens"),
});
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
}
"assistant.usage" => {
let added_credits = data
.pointer("/copilotUsage/totalNanoAiu")
.and_then(Value::as_f64)
.filter(|n| n.is_finite() && *n > 0.0);
if let Some(nano_aiu) = added_credits {
self.total_nano_aiu += nano_aiu;
self.has_nano_aiu = true;
}
if agent_id.is_none() {
let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) {
let used = u32_of(data, "inputTokens").or(self.last_used_tokens);
let size = self
.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or(fallback_limit.filter(|&s| s > 0));
if let (Some(used), Some(size)) = (used, size) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
} else if added_credits.is_some()
&& let (Some(used), Some(size)) = (
self.last_used_tokens,
self.last_usage_snapshot
.as_ref()
.map(|s| s.token_limit)
.filter(|&s| s > 0)
.or(fallback_limit.filter(|&s| s > 0)),
)
{
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
if let Some(limits) = quota_limits(data.get("quotaSnapshots")) {
out.updates.push((main_session.to_owned(), limits));
}
}
"session.compaction_complete" if agent_id.is_none() => {
if data.get("success").and_then(Value::as_bool) == Some(true) {
let used = u32_of(data, "postCompactionTokens");
let size = u32_of(data, "tokenLimit")
.filter(|&n| n > 0)
.or_else(|| self.last_usage_snapshot.as_ref().map(|s| s.token_limit).filter(|&n| n > 0))
.or(fallback_limit.filter(|&n| n > 0));
if let (Some(used), Some(size)) = (used, size) {
self.record_snapshot(UsageSnapshot {
current_tokens: used,
token_limit: size,
system_tokens: u32_of(data, "systemTokens"),
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
conversation_tokens: u32_of(data, "conversationTokens"),
});
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
}
}
}
"session.idle" if agent_id.is_none() => {
let mode = str_of(data, "mode").unwrap_or_default();
if mode != "autopilot" {
@@ -542,11 +620,34 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
continue;
}
let hint = cmd.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty());
let mut seen_choices = HashSet::new();
let choices: Vec<Value> = cmd
.pointer("/input/choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|ch| {
let choice_name = str_of(ch, "name").map(str::trim).filter(|n| !n.is_empty())?;
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
return None;
}
Some(json!({
"name": choice_name,
"description": str_of(ch, "description").unwrap_or_default(),
}))
})
.collect();
let input = match (hint, choices.is_empty()) {
(Some(h), false) => Some(json!({ "hint": h, "choices": choices })),
(Some(h), true) => Some(json!({ "hint": h })),
(None, false) => Some(json!({ "choices": choices })),
(None, true) => None,
};
out.push(json!({
"name": name,
"description": str_of(cmd, "description").unwrap_or_default(),
"source": "command",
"input": hint.map(|h| json!({ "hint": h })),
"input": input,
}));
}
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
@@ -573,9 +674,252 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
"input": hint.map(|h| json!({ "hint": h })),
}));
}
if seen.insert("compact".to_owned()) {
out.push(json!({
"name": "compact",
"description": "Compact conversation history to free context window space",
"source": "command",
"input": { "hint": "optional focus instructions" },
}));
}
out
}
/// Converts Copilot's `session.metadata.getContextAttribution` payload into [`AgentContextUsage`],
/// grouping items into `System` (`System prompt`, `Tool Definitions`, …) and `User Context`
/// (`Tool Results`, `Messages`, `Skills`, …) without double-counting parent rollup entries.
pub(super) fn context_usage_from_attribution(
res: &Value,
fallback_model: &str,
fallback_limit: Option<u32>,
) -> Option<AgentContextUsage> {
let attr = res.get("contextAttribution").unwrap_or(res);
if !attr.is_object() {
return None;
}
let total_tokens = u32_of(attr, "totalTokens")?;
let max_tokens = u32_of(attr, "limit")
.filter(|&n| n > 0)
.or_else(|| u32_of(attr, "promptTokenLimit").filter(|&n| n > 0))
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
let reserved_tokens = u32_of(attr, "bufferTokens").filter(|&n| n > 0);
let model = str_of(attr, "modelId").filter(|s| !s.is_empty()).unwrap_or(fallback_model).to_owned();
let auto_compact_threshold = u32_of(attr, "compactionThreshold").filter(|&n| n > 0);
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
let mut categories = Vec::new();
let entries = attr.get("entries").and_then(Value::as_array).filter(|e| !e.is_empty());
if let Some(entries) = entries {
// Any entry referenced via `parentId` is a rollup parent whose children are accounted for individually.
let parent_ids: HashSet<&str> = entries.iter().filter_map(|e| str_of(e, "parentId")).collect();
let mut system_rows: Vec<(String, u32)> = Vec::new();
let mut tool_definitions: u32 = 0;
let mut tool_results: u32 = 0;
let mut skills: u32 = 0;
let mut subagents: u32 = 0;
let mut mcp_tools: u32 = 0;
let mut plugins: u32 = 0;
let mut other_user: BTreeMap<String, u32> = BTreeMap::new();
let mut accounted: u32 = 0;
for entry in entries {
if let Some(id) = str_of(entry, "id")
&& parent_ids.contains(id)
{
continue;
}
let tokens = u32_of(entry, "tokens").unwrap_or(0);
if tokens == 0 {
continue;
}
accounted = accounted.saturating_add(tokens);
match str_of(entry, "kind").unwrap_or_default() {
"system" => {
let label = normalize_system_label(str_of(entry, "label").unwrap_or("System prompt"));
if let Some((_, existing)) = system_rows.iter_mut().find(|(k, _)| k == &label) {
*existing = existing.saturating_add(tokens);
} else {
system_rows.push((label, tokens));
}
}
"toolDefinition" => tool_definitions = tool_definitions.saturating_add(tokens),
"tool" => tool_results = tool_results.saturating_add(tokens),
"skill" => skills = skills.saturating_add(tokens),
"subagent" => subagents = subagents.saturating_add(tokens),
"mcpServer" => mcp_tools = mcp_tools.saturating_add(tokens),
"plugin" => plugins = plugins.saturating_add(tokens),
kind => {
let label = str_of(entry, "label").filter(|s| !s.is_empty()).unwrap_or(kind).to_owned();
let slot = other_user.entry(label).or_insert(0);
*slot = slot.saturating_add(tokens);
}
}
}
for (name, tokens) in system_rows {
categories.push(used_category(name, tokens, "System"));
}
if tool_definitions > 0 {
categories.push(used_category("Tool Definitions", tool_definitions, "System"));
}
if tool_results > 0 {
categories.push(used_category("Tool Results", tool_results, "User Context"));
}
let messages = total_tokens.saturating_sub(accounted);
if messages > 0 {
categories.push(used_category("Messages", messages, "User Context"));
}
if skills > 0 {
categories.push(used_category("Skills", skills, "User Context"));
}
if subagents > 0 {
categories.push(used_category("Sub-agents", subagents, "User Context"));
}
if mcp_tools > 0 {
categories.push(used_category("MCP tools", mcp_tools, "User Context"));
}
if plugins > 0 {
categories.push(used_category("Plugins", plugins, "User Context"));
}
for (name, tokens) in other_user {
categories.push(used_category(name, tokens, "User Context"));
}
} else if let Some(cats) = attr.get("categories").and_then(Value::as_object) {
let get = |k: &str| cats.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
let sys_prompt = get("systemPrompt");
let custom_inst = get("customInstructions");
let tool_defs = get("systemTools").saturating_add(get("mcpTools"));
let messages = get("messages");
if sys_prompt > 0 {
categories.push(used_category("System prompt", sys_prompt, "System"));
}
if custom_inst > 0 {
categories.push(used_category("Custom instructions", custom_inst, "System"));
}
if tool_defs > 0 {
categories.push(used_category("Tool Definitions", tool_defs, "System"));
}
if messages > 0 {
categories.push(used_category("Messages", messages, "User Context"));
}
}
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
Some(AgentContextUsage {
categories,
total_tokens,
max_tokens,
model,
is_auto_compact_enabled,
auto_compact_threshold,
reserved_tokens,
})
}
/// Converts Copilot's `session.metadata.contextInfo` payload into [`AgentContextUsage`].
pub(super) fn context_usage_from_context_info(
res: &Value,
fallback_model: &str,
fallback_limit: Option<u32>,
) -> Option<AgentContextUsage> {
let info = res.get("contextInfo").unwrap_or(res);
if !info.is_object() {
return None;
}
let total_tokens = u32_of(info, "totalTokens")?;
let max_tokens = u32_of(info, "limit")
.filter(|&n| n > 0)
.or_else(|| u32_of(info, "promptTokenLimit").filter(|&n| n > 0))
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
let reserved_tokens = u32_of(info, "bufferTokens").filter(|&n| n > 0);
let model = str_of(info, "displayModelName")
.or_else(|| str_of(info, "modelName"))
.filter(|s| !s.is_empty())
.unwrap_or(fallback_model)
.to_owned();
let auto_compact_threshold = u32_of(info, "compactionThreshold").filter(|&n| n > 0);
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
let mut categories = Vec::new();
if let Some(sys) = u32_of(info, "systemTokens").filter(|&n| n > 0) {
categories.push(used_category("System prompt", sys, "System"));
}
if let Some(tools) = u32_of(info, "toolDefinitionsTokens").filter(|&n| n > 0) {
categories.push(used_category("Tool Definitions", tools, "System"));
}
if let Some(conv) = u32_of(info, "conversationTokens").filter(|&n| n > 0) {
categories.push(used_category("Messages", conv, "User Context"));
}
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
Some(AgentContextUsage {
categories,
total_tokens,
max_tokens,
model,
is_auto_compact_enabled,
auto_compact_threshold,
reserved_tokens,
})
}
/// Fallback breakdown from the latest `session.usage_info` / compaction snapshot.
pub(super) fn context_usage_from_snapshot(snap: &UsageSnapshot, model: &str) -> AgentContextUsage {
let mut categories = Vec::new();
if let Some(sys) = snap.system_tokens.filter(|&n| n > 0) {
categories.push(used_category("System prompt", sys, "System"));
}
if let Some(tools) = snap.tool_definitions_tokens.filter(|&n| n > 0) {
categories.push(used_category("Tool Definitions", tools, "System"));
}
if let Some(conv) = snap.conversation_tokens.filter(|&n| n > 0) {
categories.push(used_category("Messages", conv, "User Context"));
}
push_free_space(&mut categories, snap.current_tokens, snap.token_limit, None);
AgentContextUsage {
categories,
total_tokens: snap.current_tokens,
max_tokens: snap.token_limit,
model: model.to_owned(),
is_auto_compact_enabled: None,
auto_compact_threshold: None,
reserved_tokens: None,
}
}
fn used_category(name: impl Into<String>, tokens: u32, group: &str) -> AgentContextCategory {
AgentContextCategory { name: name.into(), tokens, kind: Some("used".to_owned()), group: Some(group.to_owned()) }
}
fn push_free_space(
categories: &mut Vec<AgentContextCategory>,
total_tokens: u32,
max_tokens: u32,
reserved_tokens: Option<u32>,
) {
let free = max_tokens.saturating_sub(total_tokens.saturating_add(reserved_tokens.unwrap_or(0)));
if free > 0 {
categories.push(AgentContextCategory {
name: "Free space".to_owned(),
tokens: free,
kind: Some("free".to_owned()),
group: None,
});
}
}
fn normalize_system_label(raw: &str) -> String {
match raw.trim().to_ascii_lowercase().as_str() {
"system prompt" | "system" | "system instructions" => "System prompt".to_owned(),
"custom instructions" => "Custom instructions".to_owned(),
_ => raw.trim().to_owned(),
}
}
fn u32_of(v: &Value, key: &str) -> Option<u32> {
v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
}
/// The running entries of a `session.tasks.list` result, in the background-task shape the
/// app shows (`task_id`, `task_type`, `description`).
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
+442 -27
Переглянути файл
@@ -2,7 +2,10 @@
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
//! Registry, see `registry`).
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
use crate::{
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
GhAuthAccount,
};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -33,6 +36,8 @@ pub(crate) struct ProviderSpec {
pub driver: Driver,
pub command: String,
pub args: Vec<String>,
/// Number of trailing arguments added by the built-in agent's settings.
pub additional_args_len: usize,
pub env: Vec<(String, String)>,
/// How to sign in when the agent reports it needs authentication.
pub login_hint: String,
@@ -71,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
"GitHub Copilot",
Driver::Copilot,
&["copilot", "--headless", "--no-auto-update", "--stdio"],
"Run `copilot` in a terminal and sign in.",
"Run `copilot login` in a terminal.",
),
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
@@ -96,6 +101,7 @@ fn builtins() -> Vec<ProviderSpec> {
driver: *driver,
command: cmd[0].into(),
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
additional_args_len: 0,
env: Vec::new(),
login_hint: (*hint).into(),
source: AgentSource::Builtin,
@@ -148,12 +154,26 @@ impl ProviderSpec {
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let is_copilot = is_copilot_provider(&self.id);
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
let explicit_copilot_token =
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
} else if is_copilot
&& !strip_ambient_tokens
&& !explicit_copilot_token
&& ide_core::project_env::github_token(cwd).is_some()
&& let Some(default_token) = default_github_token()
{
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
}
Ok(resolved)
}
@@ -163,7 +183,7 @@ impl ProviderSpec {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
@@ -173,6 +193,80 @@ impl ProviderSpec {
.into_owned();
self
}
/// Resolves the executable, arguments, and environment to run this agent's interactive
/// sign-in flow directly in an IDE PTY without shell quoting.
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
let search = ide_core::tool_path::search_path();
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
let candidate =
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
if candidate.is_absolute() && is_executable(&candidate) {
return Some(candidate);
}
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
};
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
"claude-acp" => Some(("claude", &[][..])),
"codex-acp" => Some(("codex", &["login"][..])),
"vibe" => Some(("vibe", &[][..])),
_ => None,
} {
let program = resolve_exe(separate_cmd, &self.env)?;
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
});
}
if let Some(builtin) = builtin_spec(&self.id) {
let args = terminal_auth_args
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
.map(<[String]>::to_vec)
.or_else(|| builtin_login_args(&builtin))?;
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
if is_copilot_provider(&self.id) {
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
}
return Some(LoginLaunch { program, args, env });
}
let args = terminal_auth_args?.to_vec();
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
}
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
self.login_launch(cwd, terminal_auth_args).is_some()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoginLaunch {
pub program: PathBuf,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
}
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
let prefix = format!("Run `{}", builtin.command);
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
match rest {
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
let (args, _) = after_space.split_once('`')?;
Some(args.split_whitespace().map(str::to_owned).collect())
}
Some(_) => Some(Vec::new()),
None => None,
}
}
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
@@ -191,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
.map(str::to_owned)
}
fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn is_valid_github_login(account: &str) -> bool {
let bytes = account.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 39
&& bytes[0].is_ascii_alphanumeric()
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
if !is_valid_github_login(account) {
return Err(format!("Invalid GitHub account login: {account}"));
}
let program = find_gh_executable()
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
ide_core::process::prepare(&mut command);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
@@ -226,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
Ok(token.to_owned())
}
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
let mut env = BTreeMap::new();
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
Ok(LoginLaunch {
program,
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
env,
})
}
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
/// ignoring ambient token environment variables so keyring accounts remain visible.
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
let Some(program) = find_gh_executable() else {
return (false, Vec::new());
};
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
let mut command = std::process::Command::new(&program);
ide_core::process::prepare(&mut command);
command
.args(args)
.envs(ide_core::process::shell_env())
.env("GH_PROMPT_DISABLED", "1")
.env("GH_NO_UPDATE_NOTIFIER", "1")
.env("NO_COLOR", "1");
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
command.output().ok()
};
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
return (true, accounts);
}
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("unknown flag: --json") {
return (true, Vec::new());
}
}
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
.map(|text| parse_gh_auth_status_text(&text))
.unwrap_or_default();
(true, fallback)
}
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
#[serde(default)]
state: Option<String>,
#[serde(default)]
active: bool,
#[serde(default)]
login: String,
#[serde(default)]
token_source: Option<String>,
}
#[derive(Deserialize)]
struct Response {
#[serde(default)]
hosts: BTreeMap<String, Vec<Entry>>,
}
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
let mut accounts: Vec<GhAuthAccount> = Vec::new();
if let Some(entries) = parsed.hosts.get("github.com") {
for entry in entries {
let login = entry.login.trim();
if login.is_empty() {
continue;
}
if entry.state.as_deref().is_some_and(|s| s != "success") {
continue;
}
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
continue;
}
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
existing.active |= entry.active;
} else {
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
}
}
}
Some(accounts)
}
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
let mut accounts: Vec<GhAuthAccount> = Vec::new();
let mut current: Option<usize> = None;
for line in text.lines() {
let trimmed = line.trim();
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
let login = rest.split_whitespace().next().unwrap_or("").trim();
current = None;
if !login.is_empty() && !rest.contains("_TOKEN") {
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
current = Some(idx);
} else {
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
current = Some(accounts.len() - 1);
}
}
} else if trimmed.starts_with("- Active account: true")
&& let Some(idx) = current
{
accounts[idx].active = true;
}
}
accounts
}
fn default_github_token() -> Option<String> {
let program = find_gh_executable()?;
let mut command = std::process::Command::new(program);
ide_core::process::prepare(&mut command);
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command.output().ok().filter(|out| out.status.success())?;
let token = String::from_utf8(output.stdout).ok()?;
let token = token.trim();
(!token.is_empty()).then(|| token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -234,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
}
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
})
}
fn ambient_copilot_env_value(key: &str) -> Option<String> {
ide_core::process::shell_env()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.to_string_lossy().into_owned())
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
})
}
/// Builds child environment overrides for `copilot`:
@@ -256,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
pub(crate) fn sanitized_copilot_env(
spec_env: &[(String, String)],
cwd: &Path,
strip_ambient_tokens: bool,
) -> Vec<(String, String)> {
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
}
pub(crate) fn sanitize_copilot_env_with(
@@ -347,16 +585,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
}
fn uses_package_runner(command: &str) -> bool {
matches!(command, "npx" | "bunx" | "uvx")
}
fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool {
builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command)
}
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
let builtin = builtin_spec(&spec.id);
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
Some(AgentCommandReadOnlyReason::Registry)
} else if let Some(default) = &builtin {
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
} else {
Some(AgentCommandReadOnlyReason::CustomAgent)
};
let additional_args = builtin
.as_ref()
.filter(|b| reason.is_none() && allows_additional_args(b, spec.driver))
.map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec());
AgentProvider {
id: spec.id.clone(),
name: spec.name.clone(),
@@ -366,6 +616,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
.join(" "),
program: spec.command.clone(),
args: spec.args.clone(),
additional_args,
default_program: builtin.as_ref().map(|b| b.command.clone()),
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
@@ -373,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
config: vec![],
@@ -391,7 +643,24 @@ pub(crate) fn set_builtin_command(
command: Option<&str>,
) -> IdeResult<()> {
update_builtin(custom_dir, secrets, id, |agent, builtin| {
agent.command = command.unwrap_or(&builtin.command).to_owned()
agent.command = command.unwrap_or(&builtin.command).to_owned();
Ok(())
})
}
/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them.
pub(crate) fn set_builtin_additional_args(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
id: &str,
args: Vec<String>,
) -> IdeResult<()> {
update_builtin(custom_dir, secrets, id, |agent, builtin| {
if !allows_additional_args(builtin, agent.driver) {
return Err(IdeError::invalid(format!("{id} does not support additional arguments")));
}
agent.additional_args = args;
Ok(())
})
}
@@ -427,7 +696,10 @@ pub(crate) fn set_builtin_env(
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
update_builtin(custom_dir, secrets, id, |agent, _| {
agent.env = env;
Ok(())
})
}
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
@@ -435,7 +707,7 @@ fn update_builtin(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
id: &str,
change: impl FnOnce(&mut CustomAgent, &ProviderSpec),
change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>,
) -> IdeResult<()> {
let Some(builtin) = builtin_spec(id) else {
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
@@ -449,6 +721,7 @@ fn update_builtin(
driver: builtin.driver,
command: builtin.command.clone(),
args: builtin.args.clone(),
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: None,
}
@@ -456,11 +729,12 @@ fn update_builtin(
if agent.registry.is_some() {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
change(&mut agent, &builtin);
change(&mut agent, &builtin)?;
if agent.command == builtin.command
&& agent.name.as_deref() == Some(builtin.name.as_str())
&& agent.driver == builtin.driver
&& agent.args == builtin.args
&& agent.additional_args.is_empty()
&& agent.env.is_empty()
{
match std::fs::remove_file(&file) {
@@ -502,6 +776,7 @@ pub(crate) fn save_custom(
driver: Driver::Acp,
command: input.command.clone(),
args: input.args.clone(),
additional_args: Vec::new(),
env: input.env.clone(),
registry: None,
}
@@ -572,6 +847,7 @@ pub(crate) fn import_acp(
driver: Driver::Acp,
command: server.command,
args: server.args,
additional_args: Vec::new(),
env: server.env,
registry: None,
}
@@ -615,6 +891,9 @@ pub(crate) struct CustomAgent {
pub command: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
/// Kept separate from `args` so Settings reset does not erase a hand-written launch line.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub additional_args: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
/// Set when the agent was installed from the ACP Registry.
@@ -746,6 +1025,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
driver: agent.driver,
command: agent.command,
args: agent.args,
additional_args_len: 0,
env,
login_hint: "Sign in with the agent's own command line first.".into(),
source,
@@ -763,6 +1043,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
spec.args = crate::native::copilot::headless_args(&spec.args);
}
if spec.source == AgentSource::Custom {
if allows_additional_args(existing, spec.driver) {
spec.additional_args_len = agent.additional_args.len();
spec.args.extend(agent.additional_args);
}
spec.source = AgentSource::Builtin;
}
*existing = spec;
@@ -853,6 +1137,22 @@ mod tests {
assert_eq!(reset.env, custom.env);
}
#[test]
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
for spec in builtins() {
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
continue;
}
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
}
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
assert_eq!(args("copilot"), ["login"]);
assert_eq!(args("goose"), ["configure"]);
assert_eq!(args("hermes"), ["model"]);
assert!(args("qwen").is_empty());
}
#[test]
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
for spec in builtins() {
@@ -1043,6 +1343,53 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn additional_args_append_and_reset_without_replacing_agent_file_overrides() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap();
assert_eq!(describe(&omp()).additional_args, Some(vec![]));
set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap();
assert_eq!(omp().args, ["acp", "--extra"]);
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
assert!(!root.join("omp.toml").exists());
let file = root.join("omp.toml");
std::fs::write(
&file,
"name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n",
)
.unwrap();
let original = omp();
let extra = vec!["--label".into(), "two words".into(), String::new()];
set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap();
let configured = omp();
assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]);
assert_eq!(describe(&configured).additional_args, Some(extra));
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
assert_eq!(omp(), original);
}
#[test]
fn additional_args_cannot_modify_managed_or_non_acp_launches() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("gemini.toml"),
"command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n",
)
.unwrap();
std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap();
std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap();
let before = load(Some(root), None);
for id in ["gemini", "mine", "omp", "codex", "claude-acp"] {
let spec = before.iter().find(|spec| spec.id == id).unwrap();
assert!(describe(spec).additional_args.is_none());
assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err());
}
assert_eq!(load(Some(root), None), before);
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
@@ -1052,6 +1399,7 @@ mod tests {
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
additional_args: Vec::new(),
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
@@ -1064,12 +1412,12 @@ mod tests {
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
@@ -1078,7 +1426,7 @@ mod tests {
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
@@ -1108,6 +1456,7 @@ mod tests {
driver: Driver::Acp,
command: "amp".into(),
args: vec![],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
}
@@ -1133,6 +1482,7 @@ mod tests {
driver: Driver::Claude,
command: "/old/claude".into(),
args: vec![],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: None,
};
@@ -1186,6 +1536,7 @@ mod tests {
driver: Driver::Acp,
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
args: vec!["acp".into()],
additional_args: Vec::new(),
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }),
};
@@ -1359,4 +1710,68 @@ mod tests {
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
);
}
#[test]
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
let raw = r#"{
"hosts": {
"github.com": [
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
],
"ghe.example.com": [
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
]
}
}"#;
assert_eq!(
parse_gh_auth_status_json(raw),
Some(vec![
GhAuthAccount { login: "alice".into(), active: true },
GhAuthAccount { login: "alice-work".into(), active: false },
])
);
let text = "\
github.com
✓ Logged in to github.com account env_user (GH_TOKEN)
- Active account: true
✓ Logged in to github.com account alice (keyring)
- Active account: false
✓ Logged in to github.com account alice-work (keyring)
- Active account: true
";
assert_eq!(
parse_gh_auth_status_text(text),
vec![
GhAuthAccount { login: "alice".into(), active: false },
GhAuthAccount { login: "alice-work".into(), active: true },
]
);
}
#[test]
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
let dir = tempfile::tempdir().unwrap();
let app_support = dir.path().join("Application Support/copilot");
std::fs::create_dir_all(&app_support).unwrap();
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let mut spec = builtin_spec("copilot").unwrap();
spec.command = bin.to_string_lossy().into_owned();
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
let launch = spec.login_launch(dir.path(), None).unwrap();
assert_eq!(launch.program, bin);
assert_eq!(launch.args, ["login"]);
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
}
}
+159 -11
Переглянути файл
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
}
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
let tag = format!("v{}", entry.version.trim_start_matches('v'));
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
let sha256_url = format!("{base}/SHA256SUMS.txt");
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
Some(p) => (p.args.clone(), p.env.clone()),
None => (vec!["--acp".into()], BTreeMap::new()),
};
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
let linux_arm = format!(
"copilot-{}-arm64.tar.gz",
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
);
let linux_x64 =
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
let targets = [
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
}
}
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
let (glibc_rel, musl_rel) = match arch {
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
};
let glibc = root.join(glibc_rel);
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
let points_to_musl =
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
let has_glibc = glibc.exists() && !points_to_musl;
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
}
fn safe_segment(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('.')
@@ -443,7 +467,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
/// Installs (or updates to) the registry's current version of `id`, streaming progress
/// through `emit`, and points the agent file at it.
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
/// Installs agent `id`; an npm package retries against the public npm registry when the
/// configured one misses it only with `public_npm_fallback`.
pub fn install(
paths: &RegistryPaths,
id: &str,
public_npm_fallback: bool,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let id = canonical_id(id);
// The saved index is what the user picked from; fetch only when there is none.
let text = match fs::read_to_string(&paths.cache_file) {
@@ -455,9 +487,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
.iter()
.find(|e| e.id == id)
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
let npm_installer =
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
};
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
}
#[cfg(test)]
fn install_entry(
paths: &RegistryPaths,
entry: &Entry,
@@ -466,7 +503,10 @@ fn install_entry(
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
install_npm(p, entry, dir, platform, true, cancel, emit)
};
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
}
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
@@ -550,6 +590,7 @@ fn install_entry_with(
driver: Driver::Acp,
command: exe.to_string_lossy().into_owned(),
args,
additional_args: Vec::new(),
env,
registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }),
};
@@ -662,20 +703,23 @@ fn install_npm(
entry: &Entry,
dir: &Path,
platform: Platform,
public_fallback: bool,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
let (name, _) = split_npm_spec(&p.package);
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
#[allow(clippy::too_many_arguments)]
fn install_npm_with(
npm: &Path,
p: &Package,
entry: &Entry,
dir: &Path,
platform: Platform,
public_fallback: bool,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
@@ -703,6 +747,7 @@ fn install_npm_with(
},
&specs,
false,
public_fallback,
cancel,
emit,
)?;
@@ -941,6 +986,7 @@ mod tests {
driver: Driver::Acp,
command: "/x".into(),
args: vec![],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: id.into(), version: version.into() }),
};
@@ -1002,7 +1048,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
let dir = tempfile::tempdir().unwrap();
let install_dir = dir.path().join("acme/1.2.0");
fs::create_dir_all(&install_dir).unwrap();
@@ -1041,8 +1087,8 @@ esac
]}"#;
let entry = parse(index).unwrap().remove(0);
let pkg = entry.distribution.npx.as_ref().unwrap();
let exe =
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
.unwrap();
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
assert_eq!(calls.len(), 2, "{calls:?}");
assert!(!calls[0].contains("--registry="), "{calls:?}");
@@ -1050,6 +1096,15 @@ esac
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
assert!(exe.is_file());
// Only the configured registries: the miss is the error, and npmjs is never asked.
let only = dir.path().join("acme-only/1.2.0");
fs::create_dir_all(&only).unwrap();
let err =
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
assert_eq!(calls.len(), 3, "{calls:?}");
assert!(!calls[2].contains("--registry="), "{calls:?}");
assert!(err.message.contains("notarget"), "{err:?}");
}
#[test]
@@ -1168,6 +1223,7 @@ esac
driver: Driver::Acp,
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
args: vec!["--acp".into()],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
}
@@ -1180,7 +1236,7 @@ esac
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(spec.name, "GitHub Copilot");
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
let mut providers = vec![provider::describe(&spec)];
@@ -1272,4 +1328,96 @@ esac
assert!(npm_bin.is_file());
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
}
#[test]
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
let index = r#"{"agents":[
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
]}"#;
let archives_for = |root: &Path| -> (String, String) {
let mut entry = parse(index).unwrap().remove(0);
entry.distribution.binary.clear();
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
(
entry.distribution.binary["linux-x86_64"].archive.clone(),
entry.distribution.binary["linux-aarch64"].archive.clone(),
)
};
let touch = |path: PathBuf| {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b"").unwrap();
};
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
let empty = tempfile::tempdir().unwrap();
assert_eq!(
archives_for(empty.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
let glibc = tempfile::tempdir().unwrap();
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
let musl = tempfile::tempdir().unwrap();
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
#[cfg(unix)]
{
fs::create_dir_all(musl.path().join("lib64")).unwrap();
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
.unwrap();
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
}
#[cfg(target_os = "linux")]
{
let parsed = parse(index).unwrap().remove(0);
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
assert!(
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
"unexpected linux-x86_64 archive: {}",
parsed.distribution.binary["linux-x86_64"].archive
);
}
}
}
+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();
+3
Переглянути файл
@@ -209,6 +209,7 @@ impl Frontmatter {
source,
description: truncate(&description),
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
choices: Vec::new(),
}
}
}
@@ -913,6 +914,7 @@ pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) ->
description: state.skill.description.clone(),
hint: state.skill.hint.clone(),
source: AgentCommandSource::Skill,
choices: Vec::new(),
});
}
}
@@ -938,6 +940,7 @@ mod tests {
description: description.into(),
hint: None,
source: AgentCommandSource::Command,
choices: Vec::new(),
}
}
+533 -17
Переглянути файл
@@ -63,6 +63,8 @@ struct FakeAgent {
session_steering: bool,
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
/// The params of every `session/fork`, in order.
forks: Mutex<Vec<Value>>,
/// The content blocks of each `session/prompt`.
prompts: Mutex<Vec<Value>>,
}
@@ -175,6 +177,9 @@ impl Handler for FakeAgent {
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
self.calls.lock().push("ephemeral".into());
}
}
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
match method {
@@ -193,7 +198,11 @@ impl Handler for FakeAgent {
}
"session/new" => {
if self.hold_session_new.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_secs(5));
let peer = self.latest();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !peer.is_closed() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
}
if self.empty_config.load(Ordering::Acquire) {
return Ok(json!({"sessionId": "s1"}));
@@ -203,7 +212,11 @@ impl Handler for FakeAgent {
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": options}))
}
"session/fork" => Ok(json!({"sessionId": "s2"})),
"session/fork" => {
self.forks.lock().push(params.clone());
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
}
"_openidea/stop_task" => {
self.calls.lock().push(format!("{method} {}", params["taskId"]));
Ok(json!({}))
@@ -448,8 +461,9 @@ impl Handler for FakeAgent {
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "wait" {
// Works until cancelled.
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
// Works until cancelled or the client closes the connection.
let peer = self.latest();
while !peer.is_closed() && !self.calls.lock().iter().any(|c| c == "session/cancel") {
std::thread::sleep(Duration::from_millis(5));
}
return Ok(json!({"stopReason": "cancelled"}));
@@ -633,15 +647,170 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
mgr.shutdown();
let restored_agent = Arc::new(FakeAgent::default());
let restored = manager(tmp.path(), restored_agent.clone());
// Listing the tasks leaves the conversation on disk until something asks for it.
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
assert!(!restored.task(&task.id).unwrap().state.lock().history.is_loaded());
assert!(!restored.entries(&task.id, None).unwrap().is_empty());
assert!(restored.task(&task.id).unwrap().state.lock().history.is_loaded());
assert!(restored_agent.calls.lock().is_empty());
assert!(restored.entries("missing-task", None).is_err());
assert!(restored.entries(&task.id, Some("missing-subagent".into())).is_err());
restored.task(&task.id).unwrap().state.lock().conversation = Conversation::default();
restored.task(&task.id).unwrap().state.lock().history.conversation = Conversation::default();
assert!(restored.entries(&task.id, None).unwrap().is_empty());
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("hello"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let names = |list: Vec<AgentCommand>| list.into_iter().map(|c| c.name).collect::<Vec<_>>();
let snapshot = |mgr: &AgentManager| mgr.task(&task.id).unwrap().state.lock().snapshot();
assert!(names(snapshot(&mgr).commands).contains(&"review".to_owned()));
mgr.archive(&task.id).unwrap();
assert!(snapshot(&mgr).commands.is_empty());
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
mgr.shutdown();
// A list saved with an archived task (by an earlier version) isn't read back.
let other = tempfile::tempdir().unwrap();
std::fs::create_dir_all(other.path().join("store")).unwrap();
let name = format!("{}.json", task.id);
let mut file: Value =
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
assert_eq!(file["task"]["status"], json!("archived"));
file["task"]["commands"] = json!([{"name": "old", "description": "Old", "hint": null}]);
std::fs::write(other.path().join("store").join(&name), serde_json::to_vec(&file).unwrap()).unwrap();
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
assert!(snapshot(&restored).commands.is_empty());
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn archiving_a_task_keeps_the_permission_answer_that_is_settling() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let handle = mgr.task(&task.id).unwrap();
let permission = *handle.permissions.lock().keys().next().unwrap();
let answered = |e: &AgentEntry| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow");
let status_at_answer = tokio::task::block_in_place(|| {
// Pause delivery of the changed entry so archive runs before the reply handler returns.
let _delivery = handle.dirty.lock();
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
let status = loop {
let s = handle.state.lock();
if s.history.conversation.main.entries.iter().any(answered) {
break s.task.status;
}
drop(s);
assert!(std::time::Instant::now() < deadline, "permission answer was never recorded");
std::thread::sleep(Duration::from_millis(1));
};
mgr.archive(&task.id).unwrap();
status
});
tokio::time::timeout(Duration::from_secs(5), async {
while handle.state.lock().busy {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the archived turn did not finish");
mgr.shutdown();
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Archived);
assert!(restored.entries(&task.id, None).unwrap().iter().any(answered));
assert_eq!(status_at_answer, AgentStatus::Running, "the recorded answer must finish the wait for input");
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("Keep this"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
// In a store of its own: a late save of the first manager can't touch it.
let name = format!("{}.json", task.id);
let mut file: Value =
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
file["entries"].as_array_mut().unwrap().push(json!({"type": "no-such-entry"}));
let damaged = serde_json::to_vec(&file).unwrap();
let other = tempfile::tempdir().unwrap();
std::fs::create_dir_all(other.path().join("store")).unwrap();
let path = other.path().join("store").join(&name);
std::fs::write(&path, &damaged).unwrap();
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
// The task is listed from its own fields; its conversation shows empty.
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
assert!(restored.entries(&task.id, None).unwrap().is_empty());
restored.rename(&task.id, "Renamed").unwrap();
restored.shutdown();
assert_eq!(std::fs::read(&path).unwrap(), damaged);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
let tmp = tempfile::tempdir().unwrap();
for ephemeral in [true, false] {
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("Write a commit message"),
provider: "claude".into(),
isolation: Isolation::Local,
ephemeral,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
mgr.shutdown();
// The caller never deleted it (its window closed): only a saved task comes back.
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
restored.shutdown();
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn claude_commands_share_catalog_discovery_and_persist_results() {
@@ -1163,6 +1332,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
description: "Agent supplied description".into(),
hint: Some("instructions".into()),
source: AgentCommandSource::Command,
choices: Vec::new(),
};
mgr.task(&task.id).unwrap().state.lock().task.commands = vec![advertised.clone()];
// The task's provider wins over the caller's provider; metadata is not replaced.
@@ -1444,9 +1614,9 @@ async fn saving_a_large_task_does_not_hold_up_readers() {
let path = task_file(tmp.path(), &task.id);
for i in 0..24 {
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text });
}
let entries = handle.state.lock().conversation.main.entries.clone();
let entries = handle.state.lock().history.conversation.main.entries.clone();
let started = std::time::Instant::now();
let json = serde_json::to_vec(&entries).unwrap();
let serialising = started.elapsed();
@@ -1539,7 +1709,7 @@ async fn concurrent_saves_keep_the_newest_state_of_each_task() {
let task = idle_task(&mgr, name).await;
let handle = mgr.task(&task.id).unwrap();
// Long enough that a save takes a while between the copy and the write.
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
}
// "<name> <n>", n growing with every change made under the state lock.
@@ -1673,6 +1843,184 @@ async fn shutdown_skips_rewriting_untouched_restored_tasks() {
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
}
/// Closing a project while a turn is in flight must not let the killed turn wake up and
/// mark the persisted task as `Failed` with "The agent process exited.".
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_running_turn_does_not_mark_task_failed() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
for _ in 0..500 {
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert!(agent.calls.lock().iter().any(|c| c == "session/prompt"));
mgr.shutdown();
// Wait past TURN_GRACE so any unguarded Task::run continuation would have settled and failed.
tokio::time::sleep(TURN_GRACE * 3).await;
let path = task_file(tmp.path(), &task.id);
assert_eq!(saved_task(&path).map(|(status, _)| status), Some(serde_json::to_value(AgentStatus::Ready).unwrap()));
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let restored_task = restored.task(&task.id).unwrap();
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
assert_eq!(restored_task.state.lock().task.error, None);
let entries = restored.entries(&task.id, None).unwrap();
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"shutdown must not append an exit error entry: {entries:?}"
);
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::User { text, done_ms: None, .. } if text == "wait")),
"interrupted turn must not stamp a bogus completion timestamp: {entries:?}"
);
restored.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&restored, &task.id, AgentStatus::Ready).await;
restored.shutdown();
}
/// Shutting down while `open_session` is still mid-handshake kills the connecting peer
/// immediately and leaves the task `Ready` rather than failing or leaking the process.
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
agent.hold_session_new.store(true, Ordering::Release);
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
for _ in 0..500 {
if agent.calls.lock().iter().any(|c| c == "session/new") {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert!(agent.calls.lock().iter().any(|c| c == "session/new"));
mgr.shutdown();
tokio::time::sleep(TURN_GRACE * 3).await;
assert!(agent.latest().is_closed(), "shutdown must kill the in-flight connecting peer");
let handle = mgr.task(&task.id).unwrap();
assert!(handle.live.lock().is_none(), "opening peer must not be published after shutdown");
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
assert_eq!(handle.state.lock().task.error, None);
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let restored_task = restored.task(&task.id).unwrap();
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
assert_eq!(restored_task.state.lock().task.error, None);
let entries = restored.entries(&task.id, None).unwrap();
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"shutdown during session open must not record an error: {entries:?}"
);
restored.shutdown();
}
/// Shutting down while the agent is blocked on a permission prompt settles the pending
/// permission as Cancelled and leaves the task `Ready` without an exit error.
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_permission_request_settles_without_failing() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("decide"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
tokio::time::sleep(TURN_GRACE * 3).await;
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let restored_task = restored.task(&task.id).unwrap();
assert_eq!(restored_task.state.lock().task.status, AgentStatus::Ready);
assert_eq!(restored_task.state.lock().task.error, None);
let entries = restored.entries(&task.id, None).unwrap();
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"shutdown during permission prompt must not append an exit error: {entries:?}"
);
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")),
"unanswered permission should be settled as Cancelled: {entries:?}"
);
restored.shutdown();
}
/// Revoking and restoring project trust calls `shutdown()` on a manager that stays in use;
/// interrupting a running turn must leave the manager ready to accept later prompts.
#[tokio::test(flavor = "multi_thread")]
async fn manager_can_run_new_turns_after_shutdown_replaces_an_interrupted_turn() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("wait"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
for _ in 0..500 {
if agent.calls.lock().iter().any(|c| c == "session/prompt") {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
mgr.shutdown();
tokio::time::sleep(TURN_GRACE * 3).await;
let handle = mgr.task(&task.id).unwrap();
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
assert!(!handle.state.lock().busy);
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == "second turn")),
"follow-up turn on the same manager after shutdown should succeed: {entries:?}"
);
assert!(
!entries.iter().any(|e| matches!(e, AgentEntry::Error { .. })),
"no stale shutdown error should appear: {entries:?}"
);
mgr.shutdown();
}
/// Archiving saves the task as it is, including changes nobody asked to be saved.
#[tokio::test]
async fn archiving_saves_the_task_before_it_returns() {
@@ -2649,7 +2997,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
let handle = mgr.task(&task.id).unwrap();
handle.replaying.store(true, Ordering::Release);
handle.turn_started.store(false, Ordering::Release);
let client = Client::new(&handle, None);
let client = Client::new(&handle, handle.shared.shutdown_epoch(), None);
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
client.on_notification(WARNING_NOTIFICATION, json!({}));
@@ -2658,7 +3006,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
mgr.shutdown();
let restored = manager(tmp.path(), agent);
let handle = restored.task(&task.id).unwrap();
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
assert_eq!(handle.state.lock().history.conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
restored.shutdown();
}
@@ -2685,7 +3033,8 @@ async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
let asking = {
let handle = handle.clone();
let params = params.clone();
tokio::task::spawn_blocking(move || handle.ask_permission(&params))
let epoch = handle.shared.shutdown_epoch();
tokio::task::spawn_blocking(move || handle.ask_permission(&params, epoch))
};
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert!(!asking.is_finished());
@@ -2754,13 +3103,13 @@ async fn forks_rollbacks_and_steering() {
"state": {"state": "idle", "stopReason": "end_turn"}}),
);
}
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
handle.state.lock().history.conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
assert_eq!(first.text, "again");
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
assert!(handle.state.lock().conversation.saved_subagents().is_empty());
assert!(handle.state.lock().history.conversation.saved_subagents().is_empty());
assert!(handle.state.lock().task.usage.is_none());
assert_eq!(agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count(), rewinds);
mgr.shutdown();
@@ -2773,6 +3122,128 @@ async fn forks_rollbacks_and_steering() {
restored.shutdown();
}
const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111";
const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222";
/// Plants a recorded claude transcript for `session_id` under the project's escaped folder.
fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
let config = root.join("claude-config");
mgr.set_builtin_env(
"claude",
[("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(),
)
.unwrap();
mgr.reload_providers();
let escaped: String =
root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl"));
std::fs::create_dir_all(transcript.parent().unwrap()).unwrap();
std::fs::write(
&transcript,
format!(
"{}\n",
json!({
"type": "user",
"uuid": "u1",
"parentUuid": null,
"message": {"role": "user", "content": "fix the login bug"},
"cwd": root.to_string_lossy(),
})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap();
assert_eq!(task.provider, "claude");
assert_eq!(task.status, AgentStatus::Ready);
assert_eq!(task.isolation, Isolation::Local);
mgr.prompt(&task.id, text("again"), true).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1, "one fork start");
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap();
assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}");
assert_ne!(target, NATIVE_SOURCE);
assert!(
!agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"),
"the task forks the recorded session instead of starting or loading another"
);
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target));
mgr.shutdown();
}
/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree.
fn plant_codex_session(root: &Path, session_id: &str) {
let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(format!("rollout-{session_id}.jsonl")),
format!(
"{}\n{}\n",
json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}),
json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_codex_session(tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap();
assert_eq!(task.status, AgentStatus::Ready);
mgr.prompt(&task.id, text("again"), true).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1);
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_invalid_input_before_starting() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
// Non-native provider, malformed id, unknown session, wrong directory.
let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [
("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput),
("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput),
("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound),
("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput),
];
for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() {
let error = mgr.fork_session(provider, id, cwd).unwrap_err();
assert_eq!(error.kind, kind, "case {index}: {error}");
}
// A session already held by a task cannot be forked again.
mgr.import_session("claude", NATIVE_SOURCE).unwrap();
let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}");
assert!(agent.calls.lock().is_empty(), "no process may start");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn usage_limits_and_late_settings() {
let tmp = tempfile::tempdir().unwrap();
@@ -3045,6 +3516,46 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
for value in [None, Some("false"), Some("true")] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = vec![json!({
"id": "service_tier", "name": "Fast", "category": "model_config", "type": "select",
"currentValue": value.unwrap_or("true"),
"options": [{"value": "false"}, {"value": "true"}]
})];
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "codex".into(),
config: value
.map(|value| vec![AgentConfigChoice { id: "service_tier".into(), value: value.into() }])
.unwrap_or_default(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let calls = agent.calls.lock();
let prompt = calls.iter().position(|call| call == "session/prompt").unwrap();
if let Some(value) = value {
let setting = calls
.iter()
.position(|call| call == &format!("session/set_config_option \"{value}\""))
.expect("an explicit tier must not be mistaken for an inherited default");
assert!(setting < prompt);
} else {
assert!(!calls.iter().any(|call| call == "session/set_config_option"));
}
drop(calls);
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
for (effort, applied) in [("medium", true), ("high", false)] {
@@ -4172,6 +4683,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| {
@@ -4753,7 +5265,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
Isolation::Worktree => None,
};
assert_eq!(read("later.txt").as_deref(), later, "{case}");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().history.turns.len(), 1, "{case}");
// Without `files` they stay; the first message takes the task back to its start.
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
@@ -4761,7 +5273,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
mgr.rollback(&task.id, 0, true).await.unwrap();
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
assert!(mgr.task(&task.id).unwrap().state.lock().history.turns.is_empty(), "{case}");
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
mgr.delete(&task.id, true).await.unwrap();
@@ -4782,7 +5294,7 @@ async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back()
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
// As a task saved with its last turn's record only.
mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
mgr.task(&task.id).unwrap().state.lock().history.turns[1] = None;
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
@@ -4810,7 +5322,7 @@ async fn rolling_back_to_first_message_without_turn_record_checks_before_changin
{
let handle = mgr.task(&task.id).unwrap();
let mut s = handle.state.lock();
s.turns[0] = None;
s.history.turns[0] = None;
s.saved = None;
}
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
@@ -5421,6 +5933,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
ephemeral: false,
})
.await
.unwrap();
@@ -5483,6 +5996,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
("tdd".into(), AgentSkillMode::Auto),
("noisy".into(), AgentSkillMode::Off),
]),
ephemeral: false,
})
.await
.unwrap();
@@ -5626,6 +6140,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
ephemeral: false,
})
.await
.unwrap();
@@ -5652,6 +6167,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
ephemeral: false,
})
.await
.unwrap();
+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;
+19 -7
Переглянути файл
@@ -9,6 +9,7 @@ mod modules;
mod parse;
mod single;
mod structure;
mod tsc_watch;
mod up_to_date;
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
@@ -16,16 +17,19 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
};
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
pub use up_to_date::{menu_up_to_date, record_menu_build};
use crate::process::{self, Stream};
use crate::{BuildModel, maven};
use ide_core::build_jobs::append_default_jobs;
use ide_core::settings::CMakeProfile;
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
use parse::{ColUnit, Format, OutputParser, RawMessage};
@@ -417,7 +421,8 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
}
/// CLion's Build Project for a CMake project: configures the build directory when it has no
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). The directory and
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
/// logical CPU unless the profile's build arguments choose a count. The directory and
/// options come from the CMake profile; without one, a configured directory of the project
/// (the first by name), else `build`, as the generated run configurations use.
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
@@ -455,6 +460,7 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
build.args.push("--clean-first".into());
}
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
append_default_jobs(&mut build.args);
build.env = env;
steps.push(build);
steps
@@ -811,6 +817,11 @@ pub fn run(
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
}
/// [`diagnostics`] reported by `source`.
pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
for m in messages {
let (Some(path), Some(range)) = (&m.path, m.range) else { continue };
@@ -818,11 +829,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
range,
severity: m.severity,
message: m.text.clone(),
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
source: Some(source.to_owned()),
code: m.code.clone(),
unnecessary: false,
deprecated: false,
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
server: Some(source.to_owned()),
});
}
out
@@ -1500,14 +1511,15 @@ mod tests {
let cm = tmp.path().join("cm");
write(&cm, "CMakeLists.txt", "project(app)");
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
let p =
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::CMake);
assert_eq!(
args(&p),
[
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
"--build build --config Debug"
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
format!("--build build --config Debug {jobs}"),
],
"an unconfigured project is configured first"
);
@@ -1516,7 +1528,7 @@ mod tests {
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
args(&p),
["--build cmake-build-release --config Debug --clean-first"],
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
"a configured directory is reused"
);
let profile = CMakeProfile {
+104 -8
Переглянути файл
@@ -94,12 +94,12 @@ pub(super) fn build_javac_step(
Ok(step)
}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
/// The last resolved dependency classpath for one module and scope. A fingerprint
/// permits reuse during a build; NoBuild also uses records without one.
#[derive(Debug, Deserialize, Serialize)]
struct CachedClasspath {
version: u32,
fingerprint: LaunchFingerprint,
fingerprint: Option<LaunchFingerprint>,
classpath: String,
}
@@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
.iter()
.find(|p| root.join(&p.dir) == module)
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
if project.packaging == "pom" {
return Err(IdeError::not_found("the launch module is a Maven aggregator without sources"));
}
let top = maven_reactor(m, &project.dir)
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
let top_dir = subdir(root, &top.dir);
@@ -217,6 +214,30 @@ pub fn module_classpath(
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
}
/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle.
pub fn module_classpath_without_build(
root: &Path,
model: &BuildModel,
module: &Path,
test: bool,
cache: &Path,
cancel: &CancellationToken,
) -> IdeResult<String> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let target = module_target(root, model, module, test)?;
if let Some(path) = classpath_cache_path(root, cache, module, test)
&& let Ok(bytes) = fs::read(path)
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(cached.classpath);
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
/// theirs cached for their own launches.
@@ -245,7 +266,7 @@ pub fn module_classpaths(
&& let Ok(bytes) = fs::read(path)
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
&& cached.version == CLASSPATH_CACHE_VERSION
&& cached.fingerprint == *fingerprint
&& cached.fingerprint.as_ref() == Some(fingerprint)
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
@@ -269,7 +290,7 @@ pub fn module_classpaths(
return Err(IdeError::cancelled());
}
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
if let Some(path) = cache_path {
let cached =
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
if let Err(error) = cache_classpath(&path, &cached) {
@@ -675,6 +696,81 @@ mod tests {
assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err());
}
#[cfg(unix)]
#[test]
fn pom_launch_resolves_dependencies_without_compiling_for_no_build() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
fixture(&root);
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
write(
&root,
"app/pom.xml",
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
);
let script = root.join("mvnw");
write(
&root,
"mvnw",
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n",
);
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(&root, &root.join("cache"), None);
let cancel = CancellationToken::new();
let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
.unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert!(paths.contains(&root.join("lib/target/classes")), "{cp}");
assert!(paths.contains(&root.join("shared/target/classes")), "{cp}");
assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}");
assert!(!paths.contains(&root.join("app/target/classes")), "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}");
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}");
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "compile"), "{args}");
}
#[cfg(unix)]
#[test]
fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
fixture(&root);
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
write(
&root,
"app/pom.xml",
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
);
write(
&root,
"mvnw",
"#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n",
);
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(&root, &root.join("cache"), None);
let cancel = CancellationToken::new();
let previous =
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
assert!(previous.contains("repo/runtime.jar"), "{previous}");
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
write(&root, "app/pom.xml", &pom.replace("</project>", "<description>changed</description></project>"));
let launch =
module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
.unwrap();
assert!(launch.contains("repo/runtime.jar"), "{launch}");
assert!(!launch.contains("runtime-v2.jar"), "{launch}");
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1);
}
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
+451
Переглянути файл
@@ -0,0 +1,451 @@
//! Problems › TypeScript project errors: the project's own `tsc --watch` on each root
//! `tsconfig.json`, its output parsed like Build's tsc step, one compilation at a time.
//!
//! A background check never writes into the project. A plain project runs `tsc --noEmit -p`
//! with its `.tsbuildinfo` (written by `composite` / `incremental` even without emit) moved to a
//! scratch folder. `tsc -b` cannot check without emitting (`--noEmit` fails with TS6310 on
//! composite references), and plain `tsc -p` on a project with references needs their built
//! `.d.ts` (TS6305). So a solution runs `tsc -b` on scratch copies of its configurations: each
//! `extends` the real one and only sends the outputs and `.tsbuildinfo` to the scratch folder,
//! keeping every option, file list and source position of the project.
use super::parse::{Format, OutputParser, RawMessage};
use super::{BuildMessage, Lines, PathMap, resolve};
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
// ponytail: one `tsc` per root; past this the shallowest roots win. Raise it, or watch
// on demand, if monorepos without a solution tsconfig need more.
const MAX_ROOTS: usize = 8;
/// The configurations among `found` (the `tsconfig.json` files of the project) that no other
/// one references: the ones a watcher runs on. Referenced projects are checked by their solution.
pub fn tsc_watch_roots(found: Vec<PathBuf>) -> Vec<PathBuf> {
let referenced: BTreeSet<PathBuf> = found.iter().flat_map(|c| references(c)).collect();
let mut roots: Vec<PathBuf> = found.into_iter().filter(|c| !referenced.contains(c)).collect();
roots.sort_by_key(|c| (c.components().count(), c.clone()));
roots.truncate(MAX_ROOTS);
roots
}
fn read_json(path: &Path) -> Option<Value> {
let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&ide_core::jsonc::strip(&text)).ok()
}
/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`).
fn references(config: &Path) -> Vec<PathBuf> {
let Some(json) = read_json(config) else { return Vec::new() };
let dir = config.parent().unwrap_or(Path::new(""));
let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten();
refs.filter_map(|r| r.get("path")?.as_str())
.map(|p| {
let p = super::normalize(&dir.join(p));
if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") }
})
.collect()
}
/// A configuration and the ones it `extends`, most derived first, each with its folder (the
/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up
/// in `node_modules` above the configuration.
fn chain(config: &Path) -> Vec<(PathBuf, Value)> {
let mut out = Vec::new();
let mut next = vec![config.to_path_buf()];
// A cycle or a deep chain ends here.
while let Some(path) = next.pop().filter(|_| out.len() < 16) {
let Some(json) = read_json(&path) else { continue };
let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
let bases: Vec<String> = match json.get("extends") {
Some(Value::String(s)) => vec![s.clone()],
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
_ => Vec::new(),
};
// Later bases override earlier ones: visit them first.
next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b)));
out.push((dir, json));
}
out
}
fn resolve_base(dir: &Path, base: &str) -> Option<PathBuf> {
let with_json = |p: PathBuf| {
if p.is_dir() {
p.join("tsconfig.json")
} else if p.extension().is_some_and(|e| e == "json") {
p
} else {
let mut s = p.into_os_string();
s.push(".json");
PathBuf::from(s)
}
};
if base.starts_with('.') || Path::new(base).is_absolute() {
return Some(with_json(super::normalize(&dir.join(base))));
}
dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file())
}
/// The first value of `key` (a top-level key, or `compilerOptions.<key>`) along `chain`, with the
/// folder it is relative to.
fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> {
chain.iter().find_map(|(dir, json)| {
let value = match key.strip_prefix("compilerOptions.") {
Some(option) => json.get("compilerOptions")?.get(option)?,
None => json.get(key)?,
};
Some((dir.as_path(), value))
})
}
/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and
/// `.tsbuildinfo` in `scratch` (file `<n>`), referencing the scratch copies `refs`. Settings that
/// default relative to the configuration's own folder are spelled out, since the copy lives
/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the
/// `rootDir` of a composite project.
fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value {
let chain = chain(config);
let dir = config.parent().unwrap_or(Path::new(""));
let out = scratch.join(n.to_string());
let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) });
if lookup(&chain, "compilerOptions.declarationDir").is_some() {
options["declarationDir"] = json!(out);
}
if lookup(&chain, "compilerOptions.outFile").is_some() {
options["outFile"] = json!(out.join("out.js"));
}
if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true))
&& lookup(&chain, "compilerOptions.rootDir").is_none()
{
options["rootDir"] = json!(dir);
}
let mut copy = json!({
"extends": config,
"compilerOptions": options,
"references": refs.iter().map(|r| json!({ "path": r })).collect::<Vec<_>>(),
});
if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() {
copy["include"] = json!([dir.join("**/*")]);
}
if lookup(&chain, "exclude").is_none() {
let mut exclude = vec![dir.join("node_modules")];
if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") {
exclude.push(super::normalize(&base.join(out_dir)));
}
copy["exclude"] = json!(exclude);
}
copy
}
/// The `tsc` arguments that watch `config` without writing into the project, writing the
/// scratch configurations a solution needs into `scratch`.
fn watch_args(config: &Path, scratch: &Path) -> std::io::Result<Vec<String>> {
let path = |p: &Path| p.to_string_lossy().into_owned();
let mut args: Vec<String> = if references(config).is_empty() {
let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned());
let info = path(&scratch.join("tsconfig.tsbuildinfo"));
["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec()
} else {
// Every configuration the solution reaches gets a number: the solution 0, then in order.
let mut numbers: BTreeMap<PathBuf, usize> = BTreeMap::from([(config.to_path_buf(), 0)]);
let mut queue = vec![config.to_path_buf()];
let mut i = 0;
while i < queue.len() {
let current = queue[i].clone();
let refs: Vec<PathBuf> = references(&current)
.into_iter()
.map(|r| {
let next = numbers.len();
let n = *numbers.entry(r.clone()).or_insert_with(|| {
queue.push(r);
next
});
scratch.join(format!("{n}.json"))
})
.collect();
let copy = scratch_config(&current, scratch, numbers[&current], &refs);
std::fs::write(scratch.join(format!("{}.json", numbers[&current])), copy.to_string())?;
i += 1;
}
vec!["-b".into(), path(&scratch.join("0.json"))]
};
args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from));
Ok(args)
}
/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`).
fn local_tsc(root: &Path, dir: &Path) -> Option<PathBuf> {
dir.ancestors()
.take_while(|d| d.starts_with(root))
.find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir))
}
/// The messages of one compilation at a time: tsc ends each with
/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every
/// project of the solution that has some, rebuilt this time or not ("out of date because it had
/// errors"), so each compilation's list replaces the last.
#[derive(Default)]
struct Compilations {
parser: Option<OutputParser>,
raws: Vec<RawMessage>,
}
impl Compilations {
fn feed(&mut self, line: &str) -> Option<Vec<RawMessage>> {
let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc));
if line.contains("Watching for file changes.") {
self.raws.extend(parser.finish());
return Some(std::mem::take(&mut self.raws));
}
self.raws.extend(parser.feed(line).messages);
None
}
}
/// A scratch folder of this process for `config`, removed when dropped.
struct Scratch(PathBuf);
impl Scratch {
fn new(config: &Path) -> std::io::Result<Self> {
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
config.hash(&mut hash);
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
"{}-{:016x}",
std::process::id(),
hash.finish()
));
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir)?;
Ok(Scratch(dir))
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the
/// messages of every finished compilation (all of them, an empty list when it passes) to
/// `on_compilation`. Not found when the project has no TypeScript of its own.
pub fn tsc_watch(
root: &Path,
config: &Path,
cancel: &CancellationToken,
mut on_compilation: impl FnMut(Vec<BuildMessage>),
) -> IdeResult<()> {
let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?;
let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?;
let scratch = Scratch::new(config)?;
let args = watch_args(config, &scratch.0)?;
let paths = PathMap::new(root);
let mut compilations = Compilations::default();
let program = tsc.to_string_lossy();
process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| {
if let Some(raws) = compilations.feed(line) {
// Fresh file texts each time: the files changed since the last compilation.
let mut lines = Lines::default();
on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect());
}
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn write(dir: &Path, rel: &str, text: &str) {
let p = dir.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
#[test]
fn roots_are_the_configurations_no_other_one_references() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
// A solution with references (one by folder, one by file), plus an unrelated package.
write(
root,
"tsconfig.json",
r#"{ "files": [], // solution
"references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#,
);
write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
write(root, "tools/cli/tsconfig.json", "{}");
let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json"));
assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]);
}
#[test]
fn a_solution_is_checked_through_scratch_copies_of_its_configurations() {
let tmp = tempfile::tempdir().unwrap();
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
std::fs::create_dir_all(&scratch).unwrap();
write(
&root,
"tsconfig.json",
r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#,
);
// a: composite, every setting by default.
write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
// b: references a, settles its files, outputs and root in a shared base.
write(
&root,
"packages/b/tsconfig.json",
r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#,
);
write(
&root,
"tsconfig.base.json",
r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"},
"include": ["packages/*/src"]}"#,
);
let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap();
let s = |p: &str| scratch.join(p).to_string_lossy().into_owned();
assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]);
let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap();
let path = |p: &Path| json!(p);
assert_eq!(
copy(0),
json!({
"extends": path(&root.join("tsconfig.json")),
"compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")},
"references": [{"path": s("1.json")}, {"path": s("2.json")}],
"exclude": [path(&root.join("node_modules"))],
})
);
// 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!({
"extends": path(&a.join("tsconfig.json")),
"compilerOptions": {
"outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a),
},
"references": [],
"include": [path(&a.join("**/*"))],
"exclude": [path(&a.join("node_modules"))],
})
);
let b = root.join("packages").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").join("out.js")),
},
"references": [{"path": s("1.json")}],
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
})
);
}
#[test]
fn a_composite_package_base_gets_its_root_folder() {
let tmp = tempfile::tempdir().unwrap();
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#);
write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#);
let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]);
assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app")));
assert_eq!(copy.get("include"), None, "the files come from the real configuration");
}
#[test]
fn each_compilation_reports_its_own_messages() {
// `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed.
let output = "\
2:14:08 PM - Starting compilation in watch mode...
2:14:09 PM - Found 0 errors. Watching for file changes.
2:14:12 PM - File change detected. Starting incremental compilation...
src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'.
src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
Type 'string' is not assignable to type 'number'.
2:14:12 PM - Found 2 errors. Watching for file changes.
2:14:15 PM - File change detected. Starting incremental compilation...
2:14:15 PM - Found 0 errors. Watching for file changes.";
let mut compilations = Compilations::default();
let found: Vec<Vec<(String, Option<String>)>> = output
.lines()
.filter_map(|l| compilations.feed(l))
.map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect())
.collect();
assert_eq!(
found,
[
vec![],
vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))],
vec![]
]
);
}
#[cfg(unix)]
#[test]
fn the_projects_tsc_reports_until_cancelled() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "app/tsconfig.json", "{}");
write(root, "app/src/b.ts", "export const b: number = a;\n");
// A watcher that prints one compilation and keeps running, like `tsc --watch`.
write(
root,
"node_modules/.bin/tsc",
"#!/bin/sh\necho \"$@\" > args.txt\n\
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n",
);
let bin = root.join("node_modules/.bin/tsc");
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
let cancel = CancellationToken::new();
let mut compilations = Vec::new();
let started = std::time::Instant::now();
let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| {
compilations.push(messages);
cancel.cancel();
});
assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher");
let [messages] = &compilations[..] else { panic!("{compilations:?}") };
let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect();
let at = |l, c| ide_core::Pos::new(l, c);
assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]);
let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap();
let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap();
assert_eq!(check, "--noEmit -p tsconfig.json --incremental");
let (info, watch) = rest.split_once(' ').unwrap();
assert_eq!(watch, "--watch --pretty false --preserveWatchOutput");
// The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher.
let scratch = Path::new(info).parent().unwrap();
assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}");
assert!(!scratch.exists());
}
#[test]
fn no_local_typescript_runs_nothing() {
let tmp = tempfile::tempdir().unwrap();
write(tmp.path(), "tsconfig.json", "{}");
let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| {
panic!("no compilation without typescript")
})
.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
}
}
+19 -16
Переглянути файл
@@ -46,6 +46,16 @@ fn subdir(root: &Path, rel: &str) -> PathBuf {
root.join(rel).components().collect()
}
/// The `-pl` value selecting `projects` in their Maven reactor, by `groupId:artifactId`. Their
/// directories are the absolute `basedir`s Maven reported, which need not share a spelling with the
/// opened folder (drive letter case, separators, links), so a path selector could miss the reactor.
fn maven_project_selection<'a>(projects: impl Iterator<Item = &'a ProjectModel>) -> String {
let mut selection: Vec<String> = projects.map(|p| format!("{}:{}", p.group_id, p.artifact_id)).collect();
selection.sort();
selection.dedup();
selection.join(",")
}
/// The resident part of the build: javac servers and one lock per reactor.
#[derive(Default)]
pub struct JavaBuildService {
@@ -441,7 +451,7 @@ impl JavaBuild<'_> {
let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?;
let project = record.model.projects.iter().find(|p| p.dir == module)?;
let paths = class_paths(project, test);
paths.first().is_some_and(|p| p.is_dir()).then_some(paths)
paths.first().is_some_and(|p| p.exists()).then_some(paths)
}
/// Builds `target`. A launch gets the classpath to run with; the others an empty one.
@@ -691,17 +701,8 @@ impl JavaBuild<'_> {
let out = model::output_root(self.cache, &top.key());
let step = match top {
Reactor::Maven(top) => {
let top_dir = subdir(self.root, &top.dir);
let mut selection: Vec<String> = changed
.iter()
.map(|(p, _, _)| {
let rel = p.dir.strip_prefix(&top_dir).unwrap_or(&p.dir).to_string_lossy().replace('\\', "/");
if rel.is_empty() { ".".to_owned() } else { rel }
})
.collect();
selection.sort();
selection.dedup();
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection.join(",")];
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
extra.push("resources:resources".into());
if changed.iter().any(|(_, test, _)| *test) {
extra.push("resources:testResources".into());
@@ -1039,7 +1040,7 @@ fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test:
if test {
visit(project, false, by_output, by_test_output, seen, out);
}
for entry in &project.set(test).classpath {
for entry in project.set(test).classpath.iter().chain(&project.set(test).runtime_classpath) {
if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
visit(upstream, false, by_output, by_test_output, seen, out);
} else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
@@ -1061,10 +1062,12 @@ fn class_paths(target: &ProjectModel, test: bool) -> Vec<PathBuf> {
out.push(p.clone());
}
};
if test {
push(&target.test.output);
if target.packaging != "pom" {
if test {
push(&target.test.output);
}
push(&target.main.output);
}
push(&target.main.output);
for entry in &target.set(test).runtime_classpath {
push(entry);
}
+52 -11
Переглянути файл
@@ -11,6 +11,50 @@ fn write(root: &Path, rel: &str, text: &str) {
fs::write(path, text).unwrap();
}
fn build_output_tail(events: &[BuildEvent]) -> String {
let mut lines: Vec<_> = events
.iter()
.filter_map(|event| match event {
BuildEvent::Output { text, .. } => Some(text.as_str()),
_ => None,
})
.flat_map(str::lines)
.rev()
.take(150)
.collect();
lines.reverse();
lines.join("\n")
}
#[test]
fn build_output_tail_keeps_the_last_150_lines_across_streams() {
let lines = |range: std::ops::Range<usize>| range.map(|n| n.to_string()).collect::<Vec<_>>().join("\n");
let events = [
BuildEvent::Output { text: lines(0..100), stderr: false },
BuildEvent::Progress { message: "building".into(), fraction: None },
BuildEvent::Output { text: lines(100..155), stderr: true },
];
assert_eq!(build_output_tail(&events), lines(5..155));
}
#[test]
fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
// Maven reports absolute basedirs whose spelling can differ from the opened folder on Windows
// (`D:/worktree/jxc/organ` against `d:\\worktree\\jxc`); coordinates always name a reactor project.
let project = |dir: &str, artifact: &str| ProjectModel {
dir: PathBuf::from(dir),
group_id: "org.starry".into(),
artifact_id: artifact.into(),
..Default::default()
};
let projects = [
project("D:/worktree/jxc/organ", "organ"),
project("D:/worktree/jxc", "cloud"),
project("D:/worktree/jxc/organ", "organ"),
];
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
@@ -18,15 +62,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
@@ -145,7 +183,10 @@ impl Fixture {
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Ok(Built::Unsupported(reason)) => {
let output = build_output_tail(&self.events.lock().unwrap());
panic!("unsupported: {reason}\n{output}");
}
Err(e) => panic!("{e:?}"),
}
}
@@ -216,7 +257,7 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
+7 -4
Переглянути файл
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
/// redirector loaded before Maven calculates its lifecycle execution plans.
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
pub fn build(
root: &Path,
model: &BuildModel,
bundle: &Path,
generation: &Path,
cancel: &CancellationToken,
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model, cancel)?;
@@ -124,10 +126,10 @@ pub fn build(
for step in &plan.steps {
let mut reactor = plan.clone();
reactor.steps = vec![step.clone()];
let result = compile::run(root, &reactor, cancel, &|event| {
if let BuildEvent::Output { text, .. } = event {
tracing::debug!("kotlin bridge: {}", text.trim_end());
}
let result = compile::run(root, &reactor, cancel, &|event| match event {
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
_ => {}
})?;
messages.extend(result.messages);
}
@@ -456,6 +458,7 @@ mod tests {
Path::new("unused.jar"),
&directory.path().join("private"),
&CancellationToken::new(),
&|_, _| {},
)
.err()
.unwrap();
+24
Переглянути файл
@@ -0,0 +1,24 @@
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
</parent>
<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>t</groupId>
<artifactId>lib</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
+9
Переглянути файл
@@ -0,0 +1,9 @@
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
</parent>
<artifactId>lib</artifactId>
</project>
+35
Переглянути файл
@@ -0,0 +1,35 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>t</groupId>
<artifactId>root</artifactId>
<version>1</version>
<packaging>pom</packaging>
<modules>
<module>lib</module>
<module>app</module>
</modules>
<properties>
<maven.compiler.release>11</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.4.0</version>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
+118 -2
Переглянути файл
@@ -260,8 +260,8 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
/// may be larger than the text, and a malformed one may lack the NUL.
#[cfg(any(windows, test))]
fn unicode_text(bytes: &[u8]) -> String {
let units: Vec<u16> =
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
let (pairs, _) = bytes.as_chunks::<2>();
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
String::from_utf16_lossy(&units)
}
@@ -340,6 +340,18 @@ mod imp {
const OPEN_ATTEMPTS: usize = 10;
const OPEN_RETRY: Duration = Duration::from_millis(20);
/// WARNING: reading or writing the clipboard from two threads at once crashes the whole
/// process. `OpenClipboard(NULL)` does not keep the other threads of this process out, and
/// a second `GetClipboardData` can free the block the first thread is still reading, so
/// `GlobalSize` finds a corrupted heap and Windows ends the app with 0xc0000374 (#6388:
/// restoring a minimized window starts several reads). Every function below that opens the
/// clipboard holds this lock from before `OpenClipboard` until after `CloseClipboard`.
static CLIPBOARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn lock() -> std::sync::MutexGuard<'static, ()> {
CLIPBOARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[link(name = "user32")]
unsafe extern "system" {
fn OpenClipboard(owner: Handle) -> i32;
@@ -389,6 +401,7 @@ mod imp {
}
pub fn png() -> Option<Vec<u8>> {
let _clipboard = lock();
if !open() {
return None;
}
@@ -405,6 +418,7 @@ mod imp {
}
pub fn text() -> Option<String> {
let _clipboard = lock();
// Empty rather than None: a None falls back to the WebView, which prompts the user.
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
return Some(String::new());
@@ -447,6 +461,7 @@ mod imp {
}
pub fn files() -> std::io::Result<Vec<PathBuf>> {
let _clipboard = lock();
if !open() {
return Err(std::io::Error::last_os_error());
}
@@ -528,6 +543,7 @@ mod imp {
}
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
let _clipboard = lock();
let (memory, _) = global_text(text);
if memory.is_null() {
return Err(std::io::Error::last_os_error());
@@ -551,6 +567,7 @@ mod imp {
}
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
let _clipboard = lock();
let dib = super::image::png_to_dib(png)?;
let format = png_format();
if format == 0 {
@@ -593,6 +610,7 @@ mod imp {
}
pub fn set_files(paths: &[PathBuf]) -> bool {
let _clipboard = lock();
let bytes = encode(paths);
if bytes.len() <= HEADER {
return false;
@@ -923,6 +941,104 @@ mod tests {
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
}
#[cfg(windows)]
const READ_TEXT: &str = "clipboard read test";
/// Reads the clipboard's text for 5 s from `threads` threads, one at a time when
/// `serialized`, in a child process: heap corruption ends a process, and the test
/// keeps the result. Replaces the clipboard with text and writes the earlier text
/// back afterwards; skipped where no clipboard can be written.
#[cfg(windows)]
fn reads_survive(test: &str, threads: usize, serialized: bool) {
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const STAGE: &str = "IDE_CLIPBOARD_READ_STAGE";
if std::env::var_os(STAGE).is_some() {
#[link(name = "kernel32")]
unsafe extern "system" {
fn WerSetFlags(flags: u32) -> i32;
}
// WER_FAULT_REPORTING_NO_UI: a crash ends the child instead of waiting on a dialog.
unsafe { WerSetFlags(0x20) };
let stop = Instant::now() + Duration::from_secs(5);
let turn = Arc::new(Mutex::new(()));
let readers: Vec<_> = (0..threads)
.map(|_| {
let turn = turn.clone();
std::thread::spawn(move || {
let mut reads = 0usize;
while Instant::now() < stop {
let _turn = serialized.then(|| turn.lock().unwrap());
// None: another reader kept the clipboard open through every retry.
let read = text();
assert!(matches!(read.as_deref(), None | Some(READ_TEXT)), "read {read:?}");
reads += 1;
}
reads
})
})
.collect();
let reads: usize = readers.into_iter().map(|reader| reader.join().unwrap()).sum();
println!("reads: {reads}");
return;
}
// The tests share the one clipboard: one at a time, so none rewrites it under another.
static SERIAL: Mutex<()> = Mutex::new(());
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let earlier = text();
if let Err(error) = set_text(READ_TEXT, 0) {
eprintln!("skipped: the clipboard cannot be written here ({error})");
return;
}
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", test, "--test-threads=1", "--nocapture"])
.env(STAGE, "1")
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(60);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break Some(status);
}
if Instant::now() > deadline {
let _ = child.kill();
break None;
}
std::thread::sleep(Duration::from_millis(100));
};
if let Some(earlier) = earlier.filter(|earlier| !earlier.is_empty()) {
let _ = set_text(&earlier, 0);
}
let status = status.expect("the reads did not finish within 60 s");
assert!(
status.success(),
"clipboard reads ended the process: exit code {:#x}",
status.code().unwrap_or_default() as u32
);
}
#[cfg(windows)]
#[test]
fn text_reads_on_one_thread_do_not_corrupt_the_heap() {
reads_survive("tests::text_reads_on_one_thread_do_not_corrupt_the_heap", 1, false);
}
#[cfg(windows)]
#[test]
fn text_reads_taking_turns_do_not_corrupt_the_heap() {
reads_survive("tests::text_reads_taking_turns_do_not_corrupt_the_heap", 8, true);
}
/// The project view reads the clipboard's text whenever a window gains focus, on
/// whichever worker thread the command lands, so restoring a minimized window can
/// start several reads at once (#6388).
#[cfg(windows)]
#[test]
fn concurrent_text_reads_do_not_corrupt_the_heap() {
reads_survive("tests::concurrent_text_reads_do_not_corrupt_the_heap", 8, false);
}
fn paths(list: &[&str]) -> Vec<PathBuf> {
list.iter().map(PathBuf::from).collect()
}
+74
Переглянути файл
@@ -0,0 +1,74 @@
//! Parallelism for build tools whose default is one compiler process at a time.
//!
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
//! the user wrote into the build arguments is left alone.
/// Jobs a native build tool gets when the user did not choose a count.
pub fn default_jobs() -> usize {
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
}
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
/// build tool's options stay last.
pub fn append_default_jobs(args: &mut Vec<String>) {
if args.iter().any(|arg| is_jobs_flag(arg)) {
return;
}
let jobs = default_jobs().to_string();
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
args.splice(at..at, ["-j".to_owned(), jobs]);
}
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
fn is_jobs_flag(arg: &str) -> bool {
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
arg.strip_prefix("-j").is_some_and(count)
|| arg.strip_prefix("--parallel=").is_some_and(count)
|| arg.strip_prefix("--jobs=").is_some_and(count)
|| arg == "--parallel"
|| arg == "--jobs"
}
#[cfg(test)]
mod tests {
use super::*;
fn args_of(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).to_owned()).collect()
}
#[test]
fn the_default_is_one_job_per_logical_cpu() {
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
assert_eq!(default_jobs(), expected);
}
#[test]
fn a_build_without_a_count_gets_one() {
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
append_default_jobs(&mut argv);
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
}
#[test]
fn a_count_the_user_chose_is_left_alone() {
let own: [&[&str]; 6] =
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
for flags in own {
let mut argv = args_of(&["--build", "build"]);
argv.extend(flags.iter().map(|value| (*value).to_owned()));
let expected = argv.clone();
append_default_jobs(&mut argv);
assert_eq!(argv, expected, "the build arguments set the count");
}
}
#[test]
fn the_count_stays_before_native_build_tool_options() {
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
append_default_jobs(&mut argv);
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
}
}
+77
Переглянути файл
@@ -33,6 +33,10 @@ pub struct EditorGeneralSettings {
pub remove_trailing_blank_lines: bool,
/// Copy as rich text (HTML with syntax colours) by default.
pub rich_text_copy: bool,
/// Gutter › Highlight modified lines in the gutter: the VCS change bars next to the line numbers.
pub highlight_modified_lines: bool,
/// Gutter › Highlight modified lines in error stripe on the scrollbar (with `highlight_modified_lines`).
pub highlight_modified_lines_in_scrollbar: bool,
}
impl Default for EditorGeneralSettings {
@@ -51,6 +55,8 @@ impl Default for EditorGeneralSettings {
keep_trailing_on_caret_line: true,
remove_trailing_blank_lines: false,
rich_text_copy: true,
highlight_modified_lines: true,
highlight_modified_lines_in_scrollbar: true,
}
}
}
@@ -486,6 +492,38 @@ pub struct LanguageCodeStyle {
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
/// Java: organize imports switches to a wildcard import once this many
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
/// 5; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_count_to_use_import_with_star: Option<u32>,
/// Java: organize imports switches to a wildcard static import once this
/// many statically imported names are used (jdtls `staticStarThreshold`;
/// IDEA's default 3; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub names_count_to_use_static_import_with_star: Option<u32>,
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
#[serde(skip_serializing_if = "Option::is_none")]
pub semicolons: Option<String>,
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
#[serde(skip_serializing_if = "Option::is_none")]
pub quotes: Option<String>,
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub spaces: BTreeMap<String, bool>,
/// JavaScript / TypeScript › Imports › Import paths:
/// `shortest` | `relative` | `non-relative` | `project-relative`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier: Option<String>,
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier_ending: Option<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_file_exclude_patterns: Vec<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_specifier_exclude_regexes: Vec<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -543,6 +581,25 @@ pub struct EncodingSettings {
pub native_to_ascii: bool,
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
pub utf8_bom: String,
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
/// relative to the project with `/` separators. The status bar's choice is kept here.
#[serde(deserialize_with = "labels")]
#[specta(type = BTreeMap<String, String>)]
pub mappings: BTreeMap<String, String>,
}
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
return Ok(BTreeMap::new());
};
Ok(entries
.into_iter()
.filter_map(|(path, label)| match label {
serde_json::Value::String(label) => Some((path, label)),
_ => None,
})
.collect())
}
impl Default for EncodingSettings {
@@ -553,10 +610,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};
+2
Переглянути файл
@@ -46,6 +46,8 @@ pub enum ErrorData {
JavaBuildProblems {
problems: Vec<String>,
},
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
RemoteBackendBusy,
}
/// Git's reported result for each destination ref. A remote with several push URLs can
+29 -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)]
@@ -27,6 +48,10 @@ pub enum McpUiRequest {
pub enum IdeEvent {
/// Project data source settings changed; reload the Database tree.
DbSourcesChanged,
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
PlotAdded {
path: String,
},
McpRequest {
id: u32,
request: McpUiRequest,
+1
Переглянути файл
@@ -4,6 +4,7 @@
//! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod build_jobs;
pub mod cli_process;
pub mod editor_settings;
pub mod error;
+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());
}
}
+81 -3
Переглянути файл
@@ -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.
@@ -834,6 +862,8 @@ pub struct AppearanceSettings {
pub smooth_scrolling: bool,
pub full_path_in_title: bool,
pub project_colors_in_toolbar: bool,
/// Strength of the project colour tint in the window header, in percent (10–70).
pub project_color_strength: u8,
pub dnd_with_alt_only: bool,
pub menu_icons: bool,
/// `hamburger` | `merged` | `toolbar` (a separate row): main menu presentation in the frameless title bar.
@@ -973,6 +1003,7 @@ impl Default for AppearanceSettings {
smooth_scrolling: true,
full_path_in_title: false,
project_colors_in_toolbar: true,
project_color_strength: 22,
dnd_with_alt_only: false,
menu_icons: true,
main_menu_style: "hamburger".into(),
@@ -1212,6 +1243,8 @@ pub struct LanguagesSettings {
pub prettier: ExternalFormatterSettings,
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
/// dprint formats every file its configuration covers: `languages` is unused.
pub dprint: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub black: ExternalFormatterSettings,
pub java: JavaSettings,
@@ -1238,6 +1271,7 @@ impl Default for LanguagesSettings {
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
..ExternalFormatterSettings::default()
},
dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() },
ruff: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
@@ -1315,6 +1349,7 @@ impl LanguagesSettings {
ExternalFormatter::Prettier => &self.prettier,
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Dprint => &self.dprint,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
@@ -1328,6 +1363,7 @@ pub enum ExternalFormatter {
Prettier,
Oxfmt,
Biome,
Dprint,
Ruff,
Black,
}
@@ -1339,6 +1375,7 @@ impl ExternalFormatter {
Self::Prettier => "prettier",
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Dprint => "dprint",
Self::Ruff => "ruff",
Self::Black => "black",
}
@@ -1349,11 +1386,11 @@ impl ExternalFormatter {
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
/// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH.
pub path: String,
/// Ruff only: directory containing its configuration, or a configuration file.
pub configuration_directory: String,
@@ -1361,6 +1398,8 @@ pub struct ExternalFormatterSettings {
/// Prefer this formatter even when a language server offers formatting.
pub prefer: bool,
pub run_on_save: bool,
/// Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting.
pub fix_on_save: bool,
}
impl Default for ExternalFormatterSettings {
@@ -1389,6 +1428,7 @@ impl Default for ExternalFormatterSettings {
.collect(),
prefer: false,
run_on_save: false,
fix_on_save: false,
}
}
}
@@ -1414,6 +1454,15 @@ 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,
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
pub profiler: String,
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
/// unless the run sets it); off: matplotlib's own window.
pub show_plots_in_tool_window: bool,
}
impl Default for PythonSettings {
@@ -1426,6 +1475,9 @@ impl Default for PythonSettings {
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
profiler: "auto".into(),
show_plots_in_tool_window: true,
}
}
}
@@ -1724,11 +1776,14 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
}
impl Default for TypeScriptSettings {
fn default() -> Self {
Self { version: "bundled".into(), tsserver_max_memory: 0 }
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
}
}
@@ -1904,6 +1959,16 @@ impl Settings {
mod tests {
use super::*;
#[test]
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
assert!(old.languages.ruff.run_on_save);
assert!(!old.languages.ruff.fix_on_save);
let on: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"fixOnSave":true}}}"#).unwrap();
assert!(on.languages.ruff.fix_on_save);
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
}
#[test]
fn python_interpreter_may_name_a_run_target() {
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
@@ -1937,6 +2002,19 @@ mod tests {
assert_eq!(json["appearance"]["smoothScrolling"], false);
}
#[test]
fn database_output_destination_defaults_and_round_trips() {
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
assert!(old.database.in_editor_results);
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
let saved = serde_json::to_value(&services).unwrap();
assert_eq!(saved["database"]["outputDestination"], "services");
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
}
#[test]
fn window_close_settings_default_off_and_round_trip() {
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
+32
Переглянути файл
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
}
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
/// only when installed, then the user's `PATH`), and standard OS install locations.
pub fn find_gh_executable() -> Option<PathBuf> {
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
}
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
return Some(explicit);
}
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
}
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
return Some(explicit.to_path_buf());
}
if let Some(found) = find_command("gh", search, Path::new("")) {
return Some(found);
}
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
}
fn is_executable(path: &Path) -> bool {
let Ok(metadata) = path.metadata() else { return false };
#[cfg(unix)]
+37 -1
Переглянути файл
@@ -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(),
}
}
}
@@ -238,6 +250,8 @@ pub struct CommitSettings {
pub reformat: bool,
pub optimize_imports: bool,
pub cleanup: bool,
/// Apply Ruff's safe lint fixes before composing the commit, independently of formatting.
pub fix_on_commit: bool,
pub blank_line_after_subject: bool,
pub limit_subject: bool,
pub subject_limit: u32,
@@ -279,6 +293,7 @@ impl Default for CommitSettings {
reformat: false,
optimize_imports: false,
cleanup: false,
fix_on_commit: false,
blank_line_after_subject: true,
limit_subject: true,
subject_limit: 72,
@@ -390,13 +405,24 @@ impl Default for LogLevelColors {
#[serde(default, rename_all = "camelCase")]
pub struct DatabaseSettings {
/// A console's result sets show under the statements that produced them, in the editor,
/// instead of in the Services view's result tabs.
/// instead of in the output window's result tabs.
pub in_editor_results: bool,
/// The tool window that receives SQL query output and plans.
pub output_destination: DatabaseOutputDestination,
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
/// resolves against (completion, inspections, navigation), most specific path first.
pub resolution_scopes: Vec<SqlResolutionScope>,
}
/// Database › Query Output: where SQL results open.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DatabaseOutputDestination {
#[default]
DatabaseOutput,
Services,
}
/// One row of SQL Resolution Scopes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -716,6 +742,16 @@ impl Default for AgentSecuritySettings {
mod tests {
use super::*;
#[test]
fn ruff_safe_fixes_on_commit_default_off_and_round_trip() {
let old: CommitSettings = serde_json::from_str(r#"{"reformat":true}"#).unwrap();
assert!(old.reformat);
assert!(!old.fix_on_commit);
let on: CommitSettings = serde_json::from_str(r#"{"fixOnCommit":true}"#).unwrap();
assert!(on.fix_on_commit);
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
}
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
+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
+174
Переглянути файл
@@ -0,0 +1,174 @@
//! 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.has_root() {
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 path = Path::new(&text);
// Joining a drive-less foreign root on Windows would add the checkout's drive.
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
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, tmp.path()).unwrap().finish("Cobertura");
assert!(suite.has_branches);
assert_eq!(suite.files.len(), 3);
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
// `m.py` exists under the second source; `n.py` falls back to the first.
let m = file(&second.join("m.py"));
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
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!(file(Path::new("/abs/x.py")).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);
}
}
+281
Переглянути файл
@@ -0,0 +1,281 @@
//! 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::cli_process::{CliTool, Decoding};
use ide_core::{IdeError, IdeResult};
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
/// block the import for good.
const TIMEOUT: Duration = Duration::from_secs(600);
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
const MEASURED: &str = "import sys, json, coverage\n\
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
/// The files coverage.py reads its configuration from, in the directory it runs in.
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
/// 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
}
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
fn run_dir(path: &Path, root: &Path) -> PathBuf {
path.ancestors()
.skip(1)
.take_while(|d| d.starts_with(root))
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
.unwrap_or(root)
.to_path_buf()
}
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
let mut cmd = Command::new(python);
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
if out.success {
return Ok(out.stdout);
}
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
let text = text.trim();
if text.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()
)));
}
if text.contains("no such option") {
return Err(IdeError::unavailable(format!(
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
python.display()
)));
}
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
}
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
/// configuration is; `out` holds the scratch files. Blocking.
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
let dir = run_dir(path, root);
let data = out.join(".coverage");
let xml = out.join("coverage.xml");
let coverage = |args: &[&OsStr]| {
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
all.extend(args);
python(python_path, &dir, &all)
};
let inputs = inputs(path);
let mut args: Vec<&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(&args)?;
// `-i`: report what has source here instead of failing on the first file that has none.
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
coverage(&[
"xml".as_ref(),
"-i".as_ref(),
"--fail-under=0".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, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
// The files the report left out (no source here): listed without lines.
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
for file in measured {
acc.file(&dir.join(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 runs_where_the_coverage_configuration_is() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
std::fs::create_dir_all(root.join("data")).unwrap();
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
// A data file outside the project runs in the project.
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
}
/// A stand-in interpreter that prints `stderr` and exits with `code`.
#[cfg(unix)]
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let p = dir.join("python");
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
#[cfg(unix)]
#[test]
fn reports_why_coverage_py_failed() {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join(".coverage");
let err = |stderr: &str| {
let python = fake_python(tmp.path(), stderr, 1);
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
};
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
}
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
#[test]
fn reads_a_members_relative_data_below_fail_under() {
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();
let root = tmp.path().canonicalize().unwrap();
let member = root.join("backend");
std::fs::create_dir_all(member.join("app")).unwrap();
std::fs::write(
member.join("pyproject.toml"),
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
[tool.coverage.report]\nfail_under = 90\n",
)
.unwrap();
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
assert!(ok.success());
std::fs::remove_file(member.join("t.py")).unwrap();
let out = root.join("out");
std::fs::create_dir_all(&out).unwrap();
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
// `t.py` has no source any more and its warning is off: still listed, without lines.
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
assert!(t.lines.is_empty());
}
}
+127 -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);
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
acc.finish("JaCoCo")
}
None if text.starts_with("!coverage.py: This is a private format") => {
return Err(IdeError::invalid(format!(
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
path.display()
)));
}
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 +88,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 +163,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();
@@ -168,8 +220,75 @@ mod tests {
assert!(import(&tmp.path().join("missing"), &root).is_err());
std::fs::write(&report, "nothing").unwrap();
assert!(import(&report, &root).is_err());
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
.unwrap();
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
}
/// `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};
+2 -1
Переглянути файл
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
argv.extend(py.target.iter().cloned());
let report = CoverageReportSpec::Exported {
runner: s("coverage.py"),
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
cwd: dir.to_path_buf().into(),
env: config.env.clone(),
lcov: lcov.into(),
+15
Переглянути файл
@@ -859,6 +859,21 @@ async fn connect_with_retries(
mod tests {
use super::*;
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
/// language (a template one) declares debugpy before Python.
#[test]
fn debugpy_comes_from_the_python_language() {
let dir = tempfile::tempdir().unwrap();
let python = include_str!("../../../languages/python.toml").replace(
"args = [\"-m\", \"debugpy.adapter\"]",
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
);
assert!(python.contains("frozen_modules"));
std::fs::write(dir.path().join("python.toml"), python).unwrap();
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
}
#[test]
fn adapters_run_on_the_tool_search_path() {
let search = ide_core::tool_path::search_path();
+44 -12
Переглянути файл
@@ -51,12 +51,17 @@ pub async fn build(
cwd: &Path,
args: &[String],
filter: &CargoFilter,
cancel: &ide_core::CancellationToken,
on_output: impl Fn(String) + Send + Sync + 'static,
) -> IdeResult<PathBuf> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
let mut cmd = tokio::process::Command::new(cargo);
cmd.current_dir(cwd);
ide_core::process::prepare(cmd.as_std_mut());
ide_core::process::own_group(cmd.as_std_mut());
cmd.args(args)
.arg("--message-format=json-render-diagnostics")
.stdin(Stdio::null())
@@ -65,11 +70,13 @@ pub async fn build(
.kill_on_drop(true);
on_output(format!("> cargo {}\n", args.join(" ")));
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to run cargo: {e}")))?;
#[cfg(windows)]
let job = child.id().and_then(ide_core::process::Job::for_pid);
let stderr = child.stderr.take().ok_or_else(|| IdeError::internal("cargo stderr unavailable"))?;
let stdout = child.stdout.take().ok_or_else(|| IdeError::internal("cargo stdout unavailable"))?;
let on_output = std::sync::Arc::new(on_output);
let err_out = on_output.clone();
let err_task = tokio::spawn(async move {
let mut err_task = tokio::spawn(async move {
let mut lines = BufReader::new(stderr).split(b'\n');
while let Ok(Some(line)) = lines.next_segment().await {
let line = ide_core::output_encoding::decode_tool_output(&line);
@@ -77,19 +84,44 @@ pub async fn build(
err_out(format!("{line}\n"));
}
});
let mut found = None;
let mut lines = BufReader::new(stdout).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(exe) = artifact_executable(&line, filter) {
found = Some(exe);
let outcome = tokio::select! {
biased;
_ = cancel.cancelled() => None,
result = async {
let mut found = None;
let mut lines = BufReader::new(stdout).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(exe) = artifact_executable(&line, filter) {
found = Some(exe);
}
}
let _ = (&mut err_task).await;
let status = child.wait().await?;
if !status.success() {
return Err(IdeError::invalid(format!("cargo {} failed ({status})", args.first().map_or("", |s| s))));
}
found.ok_or_else(|| IdeError::invalid("cargo produced no executable to debug"))
} => Some(result),
};
match outcome {
Some(result) => result,
None => {
err_task.abort();
if let Some(pid) = child.id() {
let _ = tokio::task::spawn_blocking(move || {
#[cfg(windows)]
if let Some(job) = job {
job.terminate();
return;
}
ide_core::process::kill_tree_of(pid);
})
.await;
}
let _ = child.kill().await;
Err(IdeError::cancelled())
}
}
let _ = err_task.await;
let status = child.wait().await?;
if !status.success() {
return Err(IdeError::invalid(format!("cargo {} failed ({status})", args.first().map_or("", |s| s))));
}
found.ok_or_else(|| IdeError::invalid("cargo produced no executable to debug"))
}
#[cfg(test)]
+114
Переглянути файл
@@ -0,0 +1,114 @@
//! 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. Listening again right
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
const RELEASE: Duration = Duration::from_secs(5);
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(()) };
let deadline = tokio::time::Instant::now() + RELEASE;
loop {
match std::net::TcpListener::bind((host, port)) {
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(e) => return Err(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}");
}
#[tokio::test(start_paused = true)]
async 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).await.unwrap_err();
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
drop(taken);
assert!(require_free_port(&listen).await.is_ok());
}
#[tokio::test]
async fn an_address_the_machine_lacks_is_reported_at_once() {
// 192.0.2.0/24 is reserved for documentation, never a local address.
let started = std::time::Instant::now();
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
assert!(started.elapsed() < Duration::from_secs(1));
}
#[tokio::test]
async fn waits_for_the_previous_adapter_to_release_the_port() {
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = previous.local_addr().unwrap().port();
let released = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(300)).await;
drop(previous);
});
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
released.await.unwrap();
}
#[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": {}})));
}
}
+215 -57
Переглянути файл
@@ -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;
@@ -308,6 +309,14 @@ pub struct SessionInfo {
pub parent: Option<DebugSessionId>,
}
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
#[derive(Default)]
struct OwnerBreakpoints {
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
functions: Vec<FunctionBreakpoint>,
data: Vec<DataBreakpoint>,
}
/// Who started a session. Every event of the session, and of the child sessions
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
/// listings such as [`DebugManager::sessions`].
@@ -336,13 +345,12 @@ pub struct DebugManager {
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
/// Session start order, for "the first session" semantics.
order: Mutex<Vec<DebugSessionId>>,
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
/// Breakpoints by owner (window): each window's sessions get only its own.
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
exception_choices: Mutex<BTreeMap<String, bool>>,
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
jvm_finder: Mutex<jvm_memory::JvmFinder>,
@@ -818,8 +826,6 @@ impl DebugManager {
states: Mutex::default(),
exception_choices: Mutex::default(),
exception_classes: Mutex::default(),
function_breakpoints: Mutex::default(),
data_breakpoints: Mutex::default(),
stopping: Mutex::default(),
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
})
@@ -839,8 +845,24 @@ impl DebugManager {
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
}
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
}
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
}
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
}
/// `owner`'s sessions that take breakpoint requests.
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
self.live_sessions()
.into_iter()
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
.collect()
}
/// Live sessions of `owner` (all owners when `None`).
@@ -879,7 +901,27 @@ impl DebugManager {
custom_command: impl FnOnce(&str) -> Option<String>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
self.start_with_cancel(config, owner, custom_command, exception_classes, ide_core::CancellationToken::new())
.await
}
/// [`start_with_exception_classes`](Self::start_with_exception_classes), cancelling a pending
/// pre-launch build, adapter launch or configuration when `cancel` is triggered.
pub async fn start_with_cancel(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
) -> IdeResult<DebugSessionId> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut arguments = launch_arguments(&config)?;
if debugpy::listens(&config.adapter, &config.request, &arguments) {
debugpy::require_free_port(&arguments).await?;
}
// 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 =
@@ -967,7 +1009,7 @@ impl DebugManager {
.unwrap_or_else(|| vec!["build".into()]);
let filter = cargo::CargoFilter::from_json(cargo.get("filter"));
let sink = owner.sink.clone();
let program = cargo::build(&cwd, &cargo_args, &filter, move |line| {
let program = cargo::build(&cwd, &cargo_args, &filter, &cancel, move |line| {
sink.emit(ide_core::IdeEvent::Debug {
session: id,
event: ide_core::event::DebugEvent::Output { category: "console".into(), output: line },
@@ -983,7 +1025,11 @@ impl DebugManager {
other => other.as_u64().and_then(|p| u32::try_from(p).ok()),
});
if let Some(pid) = pid {
let port = attach::enable_node_inspector(pid).await?;
let port = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
port = attach::enable_node_inspector(pid) => port?,
};
if let Some(obj) = arguments.as_object_mut() {
obj.remove("processId");
obj.insert("port".into(), port.into());
@@ -1031,6 +1077,7 @@ impl DebugManager {
spec,
port,
exception_classes,
cancel,
)
.await
}
@@ -1065,6 +1112,7 @@ impl DebugManager {
spec,
port,
None,
ide_core::CancellationToken::new(),
)
.await
.map(|_| ())
@@ -1083,11 +1131,19 @@ impl DebugManager {
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
cancel: ide_core::CancellationToken,
) -> IdeResult<DebugSessionId> {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
}
let io = self.launcher.launch(spec.clone(), reuse_port).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let io = tokio::select! {
biased;
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
};
let launch_after_configuration = io.launch_after_configuration && request == "launch";
let stderr = io.stderr.clone();
let (conn, incoming) = {
@@ -1108,6 +1164,21 @@ impl DebugManager {
if let Some(pid) = rdbg_pid {
session.debuggee_pid.store(i64::from(pid), Ordering::Release);
}
let cancelled = {
let mut sessions = self.sessions.lock();
if cancel.is_cancelled() {
true
} else {
sessions.insert(id, session.clone());
self.order.lock().push(id);
false
}
};
if cancelled {
session.conn.close();
session.kill_processes();
return Err(IdeError::cancelled());
}
if let Some(mut output) = io.program_output {
session.output_drained.send_replace(false);
let session = session.clone();
@@ -1118,8 +1189,6 @@ impl DebugManager {
session.output_drained.send_replace(true);
});
}
self.sessions.lock().insert(id, session.clone());
self.order.lock().push(id);
// Announced before the event loop runs, so it precedes every adapter event.
session.emit(ide_core::event::DebugEvent::Started {
name: session.name.clone(),
@@ -1128,14 +1197,28 @@ 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);
}
enum ConfigOutcome {
Done(IdeResult<()>),
Stopped,
Cancelled,
}
let configured = tokio::select! {
biased;
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
result = self.configure(&session, arguments, launch_after_configuration) => result,
_ = session.startup_cancel.cancelled() => ConfigOutcome::Stopped,
_ = cancel.cancelled() => ConfigOutcome::Cancelled,
result = self.configure(&session, arguments, launch_after_configuration) => ConfigOutcome::Done(result),
};
match configured {
Ok(()) => Ok(id),
Err(e) => {
ConfigOutcome::Done(Ok(())) => Ok(id),
ConfigOutcome::Stopped => Err(IdeError::cancelled()),
ConfigOutcome::Cancelled => {
let _ = self.stop(id).await;
Err(IdeError::cancelled())
}
ConfigOutcome::Done(Err(e)) => {
let e = if session.conn.is_closed() {
let mut msg = format!("debug adapter `{}` exited during startup", session.adapter);
let tail = stderr.lock().join("\n");
@@ -1291,8 +1374,10 @@ impl DebugManager {
let (files, idle): (Vec<_>, Vec<_>) = self
.breakpoints
.lock()
.iter()
.map(|(p, b)| (p.clone(), b.clone()))
.get(&s.owner.key)
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
.unwrap_or_default()
.into_iter()
.partition(|(_, b)| b.iter().any(|b| b.enabled));
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
// Breakpoint states follow the owner's first session.
@@ -1310,14 +1395,14 @@ impl DebugManager {
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
}
}
let functions = self.function_breakpoints.lock().clone();
let functions = self.function_breakpoints(&s.owner.key);
if !functions.is_empty()
&& s.supports("supportsFunctionBreakpoints")
&& let Err(e) = s.send_function_breakpoints(&functions).await
{
tracing::debug!("setFunctionBreakpoints failed: {e}");
}
let data = self.data_breakpoints.lock().clone();
let data = self.data_breakpoints(&s.owner.key);
if !data.is_empty()
&& s.supports("supportsDataBreakpoints")
&& let Err(e) = s.send_data_breakpoints(&data).await
@@ -1470,26 +1555,59 @@ impl DebugManager {
}
}
/// Breakpoints are kept per file even without a session and sent on start.
/// Returns states from the first live session, or unverified states when none.
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
/// its sessions starts. Returns states from its first live session, or unverified states.
pub async fn set_breakpoints(
&self,
owner: &str,
path: PathBuf,
breakpoints: Vec<Breakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
{
let mut store = self.breakpoints.lock();
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
if breakpoints.is_empty() {
store.remove(&path);
lines.remove(&path);
} else {
store.insert(path.clone(), breakpoints.clone());
lines.insert(path.clone(), breakpoints.clone());
}
}
self.send_file_breakpoints(owner, path, breakpoints).await
}
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
/// the files that changed to its sessions. A file the window no longer lists can't stay
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
let mut store = self.breakpoints.lock();
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
let changed = removed.chain(changed).collect();
*lines = files;
changed
};
for (path, breakpoints) in changed {
self.send_file_breakpoints(owner, path, breakpoints).await?;
}
Ok(())
}
/// Drops `owner`'s breakpoints (its window closed).
pub fn forget_breakpoints(&self, owner: &str) {
self.breakpoints.lock().remove(owner);
}
async fn send_file_breakpoints(
&self,
owner: &str,
path: PathBuf,
breakpoints: Vec<Breakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
let mut result: Option<Vec<BreakpointState>> = None;
for s in self.live_sessions() {
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
continue;
}
for s in self.configured_sessions(owner) {
match s.send_breakpoints(&path, &breakpoints, None).await {
Ok(states) => {
result.get_or_insert(states);
@@ -1640,16 +1758,39 @@ impl DebugManager {
}
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
const MAX_FRAMES: u64 = 400;
let session = self.session(s)?;
session.check_thread(thread_id)?;
let body = session
.conn
.request_timeout(
let request = |start: u64, levels: u64| {
session.conn.request_timeout(
"stackTrace",
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
REQUEST_TIMEOUT,
)
.await?;
};
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
Some(Value::Array(frames)) => frames,
_ => Vec::new(),
};
let raw = match request(0, MAX_FRAMES).await {
Ok(body) => frames_of(body),
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
// time instead, without the ones it cannot describe.
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
Err(first @ DapError::Failed { .. }) => {
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
let mut raw = frames_of(top);
for start in 1..total {
if let Ok(body) = request(start, 1).await {
raw.extend(frames_of(body));
}
}
raw
}
Err(e) => return Err(e.into()),
};
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
let frame = |f: &Value| {
let mut frame = frame_from(f);
@@ -1661,7 +1802,7 @@ impl DebugManager {
}
frame
};
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
Ok(raw.iter().map(frame).collect())
}
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
@@ -1853,7 +1994,7 @@ impl DebugManager {
if force {
self.suspend_breakpoints(&session, Some(&path)).await?;
}
let stored = self.stored_breakpoints(&path);
let stored = self.stored_breakpoints(&session.owner.key, &path);
let sent: Vec<Breakpoint> =
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
session.send_breakpoints(&path, &sent, Some(line)).await?;
@@ -1868,10 +2009,15 @@ impl DebugManager {
let files: Vec<PathBuf> = self
.breakpoints
.lock()
.iter()
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
.map(|(path, _)| path.clone())
.collect();
.get(&session.owner.key)
.map(|b| {
b.lines
.iter()
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
.map(|(path, _)| path.clone())
.collect()
})
.unwrap_or_default();
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
let mut failed = None;
for (path, result) in files.into_iter().zip(sent) {
@@ -1885,11 +2031,12 @@ impl DebugManager {
if let Some(e) = failed {
return Err(e.into());
}
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
{
session.send_function_breakpoints(&[]).await?;
session.pending_restore.lock().functions = true;
}
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
session.send_data_breakpoints(&[]).await?;
session.pending_restore.lock().data = true;
}
@@ -1899,8 +2046,11 @@ impl DebugManager {
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
let pending = std::mem::take(&mut *session.pending_restore.lock());
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
.files
.into_iter()
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
.collect();
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
for ((path, _), result) in files.iter().zip(sent) {
if let Err(e) = result {
@@ -1908,13 +2058,13 @@ impl DebugManager {
}
}
if pending.functions {
let functions = self.function_breakpoints.lock().clone();
let functions = self.function_breakpoints(&session.owner.key);
if let Err(e) = session.send_function_breakpoints(&functions).await {
tracing::debug!("restoring function breakpoints failed: {e}");
}
}
if pending.data {
let data = self.data_breakpoints.lock().clone();
let data = self.data_breakpoints(&session.owner.key);
if let Err(e) = session.send_data_breakpoints(&data).await {
tracing::debug!("restoring data breakpoints failed: {e}");
}
@@ -2124,14 +2274,17 @@ impl DebugManager {
Ok(hot_swap_result(&body))
}
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
/// every configured session whose adapter supports them. States from the first one.
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
*self.function_breakpoints.lock() = list.clone();
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
/// to each of its configured sessions whose adapter supports them. States from the first one.
pub async fn set_function_breakpoints(
&self,
owner: &str,
list: Vec<FunctionBreakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
let mut result = None;
for s in self.live_sessions() {
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
{
for s in self.configured_sessions(owner) {
if !s.supports("supportsFunctionBreakpoints") {
continue;
}
match s.send_function_breakpoints(&list).await {
@@ -2144,12 +2297,17 @@ impl DebugManager {
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
}
/// Stores field watchpoints and sends them to every configured session that supports them.
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
*self.data_breakpoints.lock() = list.clone();
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
/// supports them.
pub async fn set_data_breakpoints(
&self,
owner: &str,
list: Vec<DataBreakpoint>,
) -> IdeResult<Vec<BreakpointState>> {
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
let mut result = None;
for s in self.live_sessions() {
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
for s in self.configured_sessions(owner) {
if !s.supports("supportsDataBreakpoints") {
continue;
}
match s.send_data_breakpoints(&list).await {
+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);
+93 -21
Переглянути файл
@@ -126,6 +126,8 @@ struct Script {
child_request: Option<Value>,
ignore_configuration_done: bool,
source_path: Option<String>,
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
failing_frame: Option<u64>,
/// Report this process id in the adapter's `process` event (the program being debugged).
debuggee_pid: Option<u32>,
/// java-debug's spelling of the same event.
@@ -206,6 +208,7 @@ impl Default for Script {
child_request: None,
ignore_configuration_done: false,
source_path: None,
failing_frame: None,
debuggee_pid: None,
java_process_id: false,
output_after_terminate: false,
@@ -520,6 +523,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
}
}
"stackTrace" if let Some(bad) = script.failing_frame => {
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
if (start..end).contains(&bad) {
send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
);
} else {
let frames: Vec<Value> = (start..end)
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
.collect();
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
}
}
"stackTrace" => ok!(
msg,
json!({"stackFrames": [
@@ -899,7 +916,7 @@ async fn full_protocol_flow() {
let path = PathBuf::from("/p/a.py");
let disabled = Breakpoint { enabled: false, ..bp(2) };
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
assert!(states.iter().all(|s| !s.verified), "no session yet");
let id = h.start(config()).await.unwrap();
@@ -981,7 +998,7 @@ async fn full_protocol_flow() {
assert_eq!(asked["arguments"]["frameId"], 10);
// Live breakpoint updates reach the session.
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
assert!(states[0].verified);
h.manager.resume(id, 1).await.unwrap();
@@ -1005,7 +1022,7 @@ async fn full_protocol_flow() {
async fn run_to_cursor_uses_temporary_breakpoint() {
let h = harness(Script::default());
let path = PathBuf::from("/p/a.py");
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
@@ -1037,7 +1054,7 @@ async fn stop_terminates_and_disconnects() {
#[tokio::test]
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
let start = h.start(LaunchConfig {
adapter: "unity".into(),
request: "attach".into(),
@@ -1889,7 +1906,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
async fn function_and_data_breakpoints_are_stored_and_sent() {
let h = harness(Script::default());
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
let watch = DataBreakpoint {
data_id: "Req#count".into(),
@@ -1898,7 +1915,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
hit_condition: Some("2".into()),
enabled: true,
};
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
let id = h.start(config()).await.unwrap();
assert_eq!(
@@ -1914,8 +1931,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
let states =
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
let states = h
.manager
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
.await
.unwrap();
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
@@ -1958,10 +1978,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
let h = harness(Script::default());
let a = PathBuf::from("/p/a.py");
let b = PathBuf::from("/p/b.py");
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
h.manager
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
.await
.unwrap();
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let sent_for = |path: &str| -> Vec<Value> {
@@ -1995,10 +2018,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
#[tokio::test]
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
let off = PathBuf::from("/p/off.py");
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
// Waiting for each answer before the next request would stall until the request timeout.
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
@@ -2009,6 +2032,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
);
}
#[tokio::test]
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
let h = harness(Script::default());
let other = "project-2";
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
let stale = PathBuf::from("/p/stale.py");
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
let id = h.start(config()).await.unwrap();
let paths = || -> Vec<(Value, Value)> {
requests(&h, "setBreakpoints")
.into_iter()
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
.collect()
};
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
let kept = PathBuf::from("/p/kept.py");
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
// ...unchanged files are not sent again...
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
assert_eq!(paths().len(), 3);
h.manager.stop(id).await.unwrap();
// ...and the next session gets only what the window lists.
let h2 = harness(Script::default());
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
h2.start(config()).await.unwrap();
assert!(requests(&h2, "setBreakpoints").is_empty());
}
#[tokio::test]
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
let h = harness(Script::default());
@@ -2209,7 +2266,7 @@ async fn godot_gets_resolved_paths() {
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
);
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
let id = manager.start(godot_launch(&link), owner).await.unwrap();
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
@@ -2236,7 +2293,7 @@ async fn kotlin_configures_without_configuration_done_response() {
let project = tempfile::tempdir().unwrap();
let path = project.path().join("Main.kt");
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
let mut config = config();
config.adapter = kotlin::ADAPTER.into();
config.request = "attach".into();
@@ -2270,7 +2327,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
let (owner, events) = recording_owner("kotlin-probe");
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let h = Harness { manager, owner, events, log: Arc::default() };
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
@@ -2292,6 +2349,21 @@ async fn kotlin_official_release_ten_no_delay_runs() {
}
}
#[tokio::test]
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
let id = h.start(config()).await.unwrap();
let frames = h.manager.stack_trace(id, 1).await.unwrap();
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
h.manager.stop(id).await.unwrap();
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
let id = h.start(config()).await.unwrap();
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
assert!(error.message.contains("<generated>"), "{error:?}");
h.manager.stop(id).await.unwrap();
}
#[cfg(windows)]
#[tokio::test]
async fn netcoredbg_windows_source_paths_round_trip() {
@@ -2299,7 +2371,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
let native = r"D:\work\LoginController.cs";
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
let path = PathBuf::from(client);
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
let mut cfg = config();
cfg.adapter = "netcoredbg".into();
let id = h.start(cfg).await.unwrap();
@@ -2323,7 +2395,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
] {
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
let path = PathBuf::from(client);
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
let mut cfg = config();
cfg.adapter = "java-debug".into();
cfg.request = request.into();
@@ -3418,7 +3490,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
let project = tempfile::tempdir().unwrap();
let path = project.path().join("Main.kt");
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
let sent = &h.request("attach")["arguments"];
+2 -2
Переглянути файл
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
let id = manager
.start(
LaunchConfig {
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
assert_eq!(v.value, "100");
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
manager.resume(id, thread_id).await.unwrap();
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
+1
Переглянути файл
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
let script_as_opened = dir.join("player.gd");
manager
.set_breakpoints(
"main",
script_as_opened.clone(),
vec![Breakpoint {
line: BREAK_LINE,
+1
Переглянути файл
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
let local_script = local.join("index.php");
manager
.set_breakpoints(
"main",
local_script.clone(),
vec![Breakpoint {
line: BREAK_LINE,
+13 -11
Переглянути файл
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let m = &run.manager;
let line_bp =
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
let seen = run.seen();
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
// Method breakpoint: continue → stops in `parse`.
if caps.function_breakpoints {
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.resume(s, thread).await.map_err(|e| e.message)?;
match run.stopped_after(seen).await {
@@ -368,8 +368,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
}
None => report.push("method breakpoint: NOT HIT".into()),
}
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
.await
.map_err(|e| e.message)?;
let seen = run.seen();
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
@@ -378,7 +380,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
}
// Force Step Over ignores the breakpoint inside parse.
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
@@ -409,8 +411,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
hit_condition: None,
enabled: true,
};
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.resume(s, thread).await.map_err(|e| e.message)?;
match run.stopped_after(seen).await {
@@ -425,8 +427,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
}
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
}
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
.await
.map_err(|e| e.message)?;
}
@@ -623,7 +625,7 @@ async fn attach_to_processes() {
};
let run = Run::new();
run.manager
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
.await
.map_err(|e| e.message)?;
let id =
+3 -3
Переглянути файл
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let mut report = Vec::new();
let run = Run::new();
let m = &run.manager;
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
// Without breakpoints, the program runs to its end.
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
let seen = run.seen();
m.resume(s2, t2).await.map_err(|e| e.message)?;
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
report.push("continue to exit: output and terminated".into());
// Restart (the UI starts the same configuration again), then Stop while paused.
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
let seen = run.seen();
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
+1
Переглянути файл
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
manager
.set_breakpoints(
"smoke",
source.clone(),
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
)
+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(),
}
}
+409 -77
Переглянути файл
@@ -1,11 +1,13 @@
use crate::ConsoleId;
use crate::conn::{QueryResult, ResultColumn, Setup};
use crate::source::{DataSource, DbSslMode, DbTxMode};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::RwLock;
use reqwest::{Client, RequestBuilder, StatusCode, Url};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::sync::{Mutex, MutexGuard};
#[derive(Clone)]
pub struct ClickhousePool(Arc<State>);
@@ -18,11 +20,17 @@ struct State {
database: String,
settings: Vec<(String, String)>,
read_only: bool,
session: Mutex<Session>,
connect_timeout: Duration,
startup_statements: Vec<String>,
use_http_session: bool,
session: SessionSlot,
console_sessions: parking_lot::Mutex<HashMap<(String, String), Arc<SessionSlot>>>,
closed: CancellationToken,
}
#[derive(Default)]
type SessionSlot = Mutex<Option<Session>>;
#[derive(Clone, Default)]
struct Session {
id: Option<String>,
initialized: bool,
@@ -32,6 +40,7 @@ struct Session {
/// The response format: a names line, a types line, then one JSON array per row, so rows past
/// the grid's limit are skipped without being parsed.
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(600);
const SESSION_LOST: &str = "ClickHouse HTTP session expired or is missing on this node (code 372). Reconnect to start a new session. Behind a load balancer, use one node or session affinity, or set use_http_session=false in Advanced for independent queries.";
pub(crate) fn transaction_error() -> IdeError {
@@ -44,6 +53,7 @@ impl ClickhousePool {
return Err(transaction_error());
}
let mut use_http_session = None;
let mut read_timeout = None;
let mut settings = Vec::with_capacity(setup.params.len());
for (name, value) in setup.params {
if name.eq_ignore_ascii_case("use_http_session") {
@@ -57,6 +67,14 @@ impl ClickhousePool {
} else {
return Err(IdeError::invalid("ClickHouse use_http_session must be true or false"));
});
} else if name.eq_ignore_ascii_case("http_read_timeout") {
if read_timeout.is_some() {
return Err(IdeError::invalid("ClickHouse http_read_timeout must be specified only once"));
}
let seconds = value.parse::<std::num::NonZeroU32>().map_err(|_| {
IdeError::invalid("ClickHouse http_read_timeout must be a positive whole number of seconds")
})?;
read_timeout = Some(Duration::from_secs(u64::from(seconds.get())));
} else if reserved_setting(&name) {
return Err(IdeError::invalid(format!("ClickHouse HTTP manages the {name} setting")));
} else {
@@ -89,6 +107,7 @@ impl ClickhousePool {
let _ = rustls::crypto::ring::default_provider().install_default();
let mut builder = Client::builder()
.connect_timeout(timeout)
.read_timeout(read_timeout.unwrap_or(DEFAULT_READ_TIMEOUT))
.pool_max_idle_per_host(4)
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("OpenIDEA/", env!("CARGO_PKG_VERSION")));
@@ -136,79 +155,126 @@ impl ClickhousePool {
database: database.into(),
settings,
read_only: source.read_only,
session: Mutex::new(Session {
id: use_http_session.then(|| uuid::Uuid::new_v4().to_string()),
..Session::default()
}),
connect_timeout: timeout,
startup_statements: setup.statements,
use_http_session,
session: Mutex::new(None),
console_sessions: parking_lot::Mutex::new(HashMap::new()),
closed: CancellationToken::new(),
}));
let cancel = CancellationToken::new();
let initialize = async {
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
let Some(setting) = rejected_driver_setting(&error) else {
return Err(error);
};
if !use_http_session {
if setting == "readonly" {
return Err(error);
}
if !source.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
pool.0.session.lock().await.strict_read_only = true;
pool.execute("SELECT 1", 1, &cancel).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session.
{
let mut session = pool.0.session.lock().await;
// The rejected probe may have opened a session on a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
}
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
}
}
// The HTTP database parameter applies to one request. A named session needs
// USE once so later queries inherit the selection (and may change it).
if use_http_session && !database.is_empty() {
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, database);
pool.execute(&format!("USE {name}"), 0, &cancel).await?;
}
for sql in setup.statements {
pool.execute(&sql, 0, &cancel).await?;
}
Ok(pool.clone())
if let Err(error) = pool.session(&pool.0.session, &cancel).await {
pool.close();
return Err(error);
}
Ok(pool)
}
async fn session<'a>(
&self,
slot: &'a SessionSlot,
cancel: &CancellationToken,
) -> IdeResult<MutexGuard<'a, Option<Session>>> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
session = slot.lock() => session,
};
tokio::pin!(initialize);
tokio::select! {
result = &mut initialize => {
if result.is_err() {
pool.close();
if slot.is_none() {
let mut session =
Session { id: self.0.use_http_session.then(|| uuid::Uuid::new_v4().to_string()), ..Session::default() };
{
let cancel = cancel.child_token();
let initialize = self.initialize(&mut session, &cancel);
tokio::pin!(initialize);
tokio::select! {
result = &mut initialize => result?,
() = tokio::time::sleep(self.0.connect_timeout) => {
cancel.cancel();
let _ = initialize.await;
return Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"));
}
}
}
*slot = Some(session);
}
Ok(slot)
}
async fn initialize(&self, session: &mut Session, cancel: &CancellationToken) -> IdeResult<()> {
if let Err(error) = self.execute_request("SELECT 1", 0, 1, cancel, session).await {
let Some(setting) = rejected_driver_setting(&error) else {
return Err(error);
};
if session.id.is_none() {
if setting == "readonly" {
return Err(error);
}
if !self.0.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
session.strict_read_only = true;
self.execute_request("SELECT 1", 0, 1, cancel, session).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session. The rejected probe may have used a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
let result = self.execute_request("SELECT getSetting('readonly')", 0, 1, cancel, session).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
result
},
() = tokio::time::sleep(timeout) => {
cancel.cancel();
let _ = initialize.await;
pool.close();
Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"))
}
}
// A named session needs USE once so later queries inherit the database and may change it.
if session.id.is_some() && !self.0.database.is_empty() {
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, &self.0.database);
self.execute_request(&format!("USE {name}"), 0, 0, cancel, session).await?;
}
for sql in &self.0.startup_statements {
if transaction_statement(sql) {
return Err(transaction_error());
}
self.execute_request(sql, 0, 0, cancel, session).await?;
}
Ok(())
}
pub async fn ping(&self) -> IdeResult<()> {
let cancel = CancellationToken::new();
if !self.0.use_http_session {
return self.execute("SELECT 1", 1, &cancel).await.map(|_| ());
}
let mut result = Ok(());
let consoles = self.0.console_sessions.lock().values().cloned().collect::<Vec<_>>();
let sessions = std::iter::once(&self.0.session).chain(consoles.iter().map(Arc::as_ref));
for slot in sessions {
// A running query already keeps its session active.
if let Ok(mut slot) = slot.try_lock()
&& let Some(session) = slot.as_mut()
&& let Err(error) = self.execute_request("SELECT 1", 0, 1, &cancel, session).await
{
result = result.and(Err(error));
}
}
result
}
pub fn release_console(&self, console: ConsoleId<'_>) {
self.0.console_sessions.lock().remove(&(console.window.into(), console.path.into()));
}
pub fn close(&self) {
self.0.closed.cancel();
self.0.console_sessions.lock().clear();
self.0.client.write().take();
}
@@ -261,22 +327,69 @@ impl ClickhousePool {
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
self.execute_in_console(sql, skip, max_rows, cancel, None).await
}
pub async fn execute_in_console(
&self,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
if transaction_statement(sql) {
return Err(transaction_error());
}
let mut session = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
session = self.0.session.lock() => session,
};
let console_slot = console.filter(|_| self.0.use_http_session).map(|console| {
self.0.console_sessions.lock().entry((console.window.into(), console.path.into())).or_default().clone()
});
let slot = console_slot.as_deref().unwrap_or(&self.0.session);
let mut session = self.session(slot, cancel).await?;
let state = session.as_mut().expect("session was initialized");
if self.0.use_http_session {
self.execute_request(sql, skip, max_rows, cancel, state).await
} else {
// Stateless requests use the setup's read-only flags, and have no server session to lock.
let mut request = state.clone();
drop(session);
self.execute_request(sql, skip, max_rows, cancel, &mut request).await
}
}
async fn execute_request(
&self,
sql: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
session: &mut Session,
) -> IdeResult<QueryResult> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let client = self.client()?;
if session.id.is_none() && session_set_statement(sql) {
return Err(IdeError::invalid(
"Standalone SET needs a ClickHouse HTTP session. Set use_http_session=true in Advanced or use query-level SETTINGS where applicable.",
));
}
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
let started = Instant::now();
let request_error = |error: reqwest::Error| {
if error.is_timeout() && !error.is_connect() {
IdeError::new(
ErrorKind::TimedOut,
format!("ClickHouse HTTP response timed out. The query outcome is unknown (query_id={query_id})."),
)
} else {
http_error(error)
}
};
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
let mut response = request.send().await.map_err(request_error)?;
let execution_ms = started.elapsed().as_secs_f64() * 1000.0;
let status = response.status();
let header = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_owned);
@@ -289,11 +402,11 @@ impl ClickhousePool {
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
});
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
let body = response.bytes().await.map_err(http_error)?;
let body = response.bytes().await.map_err(request_error)?;
return Err(self.server_error(status, exception_code.as_deref(), &body));
}
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
let body = response.bytes().await.map_err(http_error)?;
let body = response.bytes().await.map_err(request_error)?;
if !body.iter().all(u8::is_ascii_whitespace) {
return Err(IdeError::invalid(
"ClickHouse result grids need the default output format; remove the query's FORMAT clause",
@@ -302,7 +415,7 @@ impl ClickhousePool {
(Vec::new(), Vec::new(), false)
} else {
let mut reader = RowReader::new(skip, max_rows);
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
while let Some(chunk) = response.chunk().await.map_err(request_error)? {
reader.push(&chunk)?;
}
reader.finish().map_err(|error| self.redact_error(error))?
@@ -333,7 +446,7 @@ impl ClickhousePool {
result
}
None => {
let killed = self.kill(&client, &query_id, &session).await;
let killed = self.kill(&client, &query_id, session).await;
match killed {
Ok(()) => Err(IdeError::cancelled()),
Err(error) => Err(IdeError::new(
@@ -596,6 +709,13 @@ fn reserved_setting(name: &str) -> bool {
)
}
fn session_set_statement(mut sql: &str) -> bool {
let mut next_is =
|word: &str| crate::split::clickhouse_keyword(&mut sql).is_some_and(|part| part.eq_ignore_ascii_case(word));
// SET DEFAULT ROLE persists a user's default roles outside the current session.
next_is("SET") && !(next_is("DEFAULT") && next_is("ROLE"))
}
fn transaction_statement(sql: &str) -> bool {
let mut sql = sql.trim_start();
loop {
@@ -832,6 +952,71 @@ mod tests {
}
}
#[tokio::test]
async fn stateless_session_settings_are_refused_before_sending() {
let (port, requests) = server(vec![("200 OK", "", ONE), ("200 OK", "", ONE), ("200 OK", "", "")]).await;
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
for statement in [
"SET log_comment='openidea-test'",
"-- leading\n/* outer /* nested */ tail */ SeT `log_comment`='a;b', max_threads=1",
"# leading\nSET ROLE NONE",
"SET profile='test'",
"SET TIME ZONE 'UTC'",
] {
let error = pool.execute(statement, 1, &cancel).await.expect_err("stateless SET must fail locally");
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("use_http_session=true"), "{error}");
assert!(error.message.contains("query-level SETTINGS"), "{error}");
}
let stopped = CancellationToken::new();
stopped.cancel();
assert_eq!(
pool.execute("SET log_comment='not sent'", 1, &stopped).await.unwrap_err().kind,
ErrorKind::Cancelled
);
// A query-level setting and a persistent role change both still reach the server.
let select = "SELECT 'SET;' LIMIT 1 SETTINGS log_comment='local' FORMAT JSONCompactEachRowWithNamesAndTypes";
pool.execute(select, 1, &cancel).await.unwrap();
let default_role = "SET /* persistent */ DEFAULT # on login\n ROLE NONE TO fixture_user";
pool.execute(default_role, 0, &cancel).await.unwrap();
let requests = requests.await.unwrap();
assert!(requests[0].ends_with("SELECT 1"));
assert!(requests[1].ends_with(select));
assert!(requests[2].ends_with(default_role));
assert!(requests.iter().all(|request| query_value(&request_url(request), "session_id").is_none()));
}
#[tokio::test]
#[ignore = "requires the disposable ClickHouse fixture on loopback"]
async fn clickhouse_live_http_session_settings() -> IdeResult<()> {
let port = std::env::var("OPENIDEA_CLICKHOUSE_SET_PORT").unwrap().parse().unwrap();
let cancel = CancellationToken::new();
let read = "SELECT concat('[', getSetting('log_comment'), ']') LIMIT 1";
for (session, expected) in [("false", "[]"), ("true", "[openidea-test]")] {
let source = DataSource {
user: "set_fixture".into(),
properties: vec![property("use_http_session", session)],
..source(port)
};
let pool = Pool::connect(&source, None, None).await?;
let result = pool.execute("SET log_comment='openidea-test'", 1, &cancel).await;
if session == "true" {
result?;
} else {
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("use_http_session=true"), "{error}");
let local = format!("{read} SETTINGS log_comment='one-query'");
assert_eq!(pool.execute(&local, 1, &cancel).await?.rows, [vec![Some("[one-query]".into())]]);
}
assert_eq!(pool.execute(read, 1, &cancel).await?.rows, [vec![Some(expected.into())]]);
}
Ok(())
}
#[tokio::test]
async fn stateless_requests_keep_database_settings_readonly_and_limits() {
let (port, requests) = server(vec![("200 OK", "", ONE); 3]).await;
@@ -898,6 +1083,90 @@ mod tests {
}
}
#[tokio::test]
async fn stalled_http_response_reports_unknown_outcome_with_query_id() {
for prefix in [
"",
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n",
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 128\r\nConnection: close\r\n\r\nCode:",
] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let fixture = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
drop(probe);
let (mut stream, _) = listener.accept().await.unwrap();
let request = read_request(&mut stream).await;
let id = query_value(&request_url(&request), "query_id").unwrap();
stream.write_all(prefix.as_bytes()).await.unwrap();
assert_eq!(
tokio::time::timeout(Duration::from_secs(4), stream.read(&mut [0])).await.unwrap().unwrap(),
0
);
assert_eq!(query_value(&request_url(&request), "http_read_timeout"), None);
id
});
let source = DataSource { properties: vec![property("http_read_timeout", "1")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let error = tokio::time::timeout(
Duration::from_secs(3),
pool.execute("DELETE FROM fixture WHERE id = 1", 0, &CancellationToken::new()),
)
.await
.expect("ClickHouse must stop waiting for a stalled response")
.unwrap_err();
assert_eq!(error.kind, ErrorKind::TimedOut);
assert!(error.message.contains("outcome is unknown"), "{error}");
let id = fixture.await.unwrap();
assert!(error.message.contains(&format!("query_id={id}")), "{error}");
}
}
#[tokio::test]
async fn read_timeout_resets_while_response_keeps_arriving() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let fixture = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
drop(probe);
let (mut stream, _) = listener.accept().await.unwrap();
read_request(&mut stream).await;
let (first, rest) = ONE.split_at(6);
let headers = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", ONE.len());
stream.write_all(headers.as_bytes()).await.unwrap();
tokio::time::sleep(Duration::from_millis(1100)).await;
stream.write_all(first.as_bytes()).await.unwrap();
tokio::time::sleep(Duration::from_millis(1100)).await;
stream.write_all(rest.as_bytes()).await.unwrap();
});
let source = DataSource { properties: vec![property("http_read_timeout", "2")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let result = pool.execute("SELECT 1", 1, &CancellationToken::new()).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
fixture.await.unwrap();
}
#[tokio::test]
async fn http_read_timeout_rejects_invalid_or_duplicate_values() {
for properties in [
vec![property("http_read_timeout", "0")],
vec![property("http_read_timeout", "1.5")],
vec![property("http_read_timeout", "4294967296")],
vec![property("http_read_timeout", "1"), property("HTTP-READ-TIMEOUT", "2")],
] {
let source = DataSource { properties, ..source(0) };
let error = Pool::connect(&source, None, None).await.err().unwrap();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("http_read_timeout"), "{error}");
}
}
#[tokio::test]
async fn sequential_queries_reuse_the_http_connection() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -1151,6 +1420,69 @@ mod tests {
requests.await.unwrap();
}
#[tokio::test]
async fn console_sessions_have_distinct_http_ids() {
let (port, requests) = server(vec![("200 OK", "", ONE); 8]).await;
let Pool::Clickhouse(pool) = Pool::connect(&source(port), None, None).await.unwrap() else { unreachable!() };
let first = ConsoleId::new("main", "console.sql");
let second = ConsoleId::new("main", "console_1.sql");
let cancel = CancellationToken::new();
for console in [first, second, first] {
pool.execute_in_console("SELECT 2", 0, 1, &cancel, Some(console)).await.unwrap();
}
pool.release_console(second);
pool.ping().await.unwrap();
let requests = requests.await.unwrap();
let ids = requests
.iter()
.map(|request| query_value(&request_url(request), "session_id").unwrap())
.collect::<Vec<_>>();
assert_ne!(ids[0], ids[1]);
assert_ne!(ids[1], ids[3]);
assert_eq!(ids[1], ids[2]);
assert_eq!(ids[3], ids[4]);
assert_eq!(ids[1], ids[5]);
assert_eq!(ids[0], ids[6]);
assert_eq!(ids[1], ids[7]);
}
#[tokio::test]
async fn stateless_queries_do_not_wait_for_a_shared_session() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut probe, _) = listener.accept().await.unwrap();
read_request(&mut probe).await;
reply(&mut probe, "200 OK", "", ONE).await;
let (mut first, _) = listener.accept().await.unwrap();
let first_request = read_request(&mut first).await;
started.send(()).unwrap();
let (mut second, _) = listener.accept().await.unwrap();
let second_request = read_request(&mut second).await;
reply(&mut second, "200 OK", "", ONE).await;
reply(&mut first, "200 OK", "", ONE).await;
(first_request, second_request)
});
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
let first = pool.execute("SELECT 1", 1, &cancel);
let second = async {
received.await.unwrap();
pool.execute("SELECT 2", 1, &cancel).await
};
let (first, second) = tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(first, second) })
.await
.expect("both requests should reach the server");
first.unwrap();
second.unwrap();
let (first, second) = server.await.unwrap();
for request in [first, second] {
assert_eq!(query_value(&request_url(&request), "session_id"), None);
}
}
#[tokio::test]
async fn cancellation_sends_kill_outside_the_busy_session() {
for stateless in [false, true] {
+1
Переглянути файл
@@ -1000,6 +1000,7 @@ impl Pool {
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
Pool::Clickhouse(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
+15
Переглянути файл
@@ -30,6 +30,7 @@ pub(crate) struct Key {
target: String,
statement: String,
schema: Option<String>,
console: Option<(String, String)>,
}
impl Key {
@@ -38,8 +39,14 @@ impl Key {
target: target.to_owned(),
statement: statement.to_owned(),
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
console: None,
}
}
pub(crate) fn with_console(mut self, console: Option<crate::ConsoleId<'_>>) -> Self {
self.console = console.map(|console| (console.window.to_owned(), console.path.to_owned()));
self
}
}
/// A request for the next rows of a cursor's statement.
@@ -186,6 +193,14 @@ impl Cursors {
self.registry.lock().slots.retain(|s| s.key != *key);
}
pub(crate) fn release_console(&self, console: crate::ConsoleId<'_>, target: Option<&str>) {
self.registry.lock().slots.retain(|slot| {
let key = &slot.key;
!target.is_none_or(|target| key.target == target)
|| !key.console.as_ref().is_some_and(|(window, path)| window == console.window && path == console.path)
});
}
/// Closes the cursors of `target`: it disconnects, or a statement that changes
/// data or schema is about to run there.
pub(crate) fn release_target(&self, target: &str) {
+416
Переглянути файл
@@ -0,0 +1,416 @@
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use std::{
collections::HashMap,
path::Path,
process::Stdio,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
process::Command,
sync::{mpsc, oneshot},
time::{Instant, timeout, timeout_at},
};
const LIMIT: usize = 16 * 1024 * 1024;
const HEADER: usize = 16;
const CANCEL_GRACE: Duration = Duration::from_secs(3);
type Replies = Arc<Mutex<HashMap<u64, mpsc::Sender<Vec<u8>>>>>;
pub(super) struct Bridge {
closed: CancellationToken,
exited: CancellationToken,
sequence: AtomicU64,
outgoing: mpsc::Sender<Outgoing>,
replies: Replies,
}
struct Outgoing {
frame: Vec<u8>,
session: CancellationToken,
sent: oneshot::Sender<IdeResult<()>>,
}
struct Pending<'a> {
bridge: &'a Bridge,
id: u64,
incoming: mpsc::Receiver<Vec<u8>>,
}
impl Drop for Pending<'_> {
fn drop(&mut self) {
self.bridge.replies.lock().remove(&self.id);
}
}
impl Pending<'_> {
async fn recv(&mut self) -> IdeResult<Vec<u8>> {
tokio::select! {
biased;
frame = self.incoming.recv() => frame.ok_or_else(disconnected),
() = self.bridge.closed.cancelled() => Err(disconnected()),
}
}
}
impl Bridge {
pub(super) fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
let jdks = ide_sdk::java::installed_jdks();
let java = ide_sdk::java::java_runtime(&jdks, 17)
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
// Embedded databases can resolve file URLs against the JVM's working directory.
let files = cache.join("files");
std::fs::create_dir_all(&files)?;
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
command.current_dir(files);
ide_core::process::prepare(command.as_std_mut());
let mut child = command
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
.arg(classpath)
.args(["ai.openidea.jdbc.OpenIdeaJdbc", "--multiplex"])
.env_remove("CLASSPATH")
.env_remove("JDK_JAVA_OPTIONS")
.env_remove("JAVA_TOOL_OPTIONS")
.env_remove("_JAVA_OPTIONS")
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let input = child.stdin.take().expect("piped");
let output = child.stdout.take().expect("piped");
let closed = CancellationToken::new();
let exited = CancellationToken::new();
tokio::spawn({
let closed = closed.clone();
let exited = exited.clone();
async move {
tokio::select! {
_ = child.wait() => {}
() = closed.cancelled() => {
// The writer drops stdin. Give file-based drivers time to flush.
if timeout(Duration::from_secs(2), child.wait()).await.is_err() {
let _ = child.kill().await;
}
}
}
closed.cancel();
exited.cancel();
}
});
Ok(Self::with_io(input, output, closed, exited))
}
fn with_io(
input: impl AsyncWrite + Unpin + Send + 'static,
output: impl AsyncRead + Unpin + Send + 'static,
closed: CancellationToken,
exited: CancellationToken,
) -> Self {
let (outgoing, writes) = mpsc::channel(4);
let replies = Replies::default();
tokio::spawn(write_frames(input, writes, closed.clone()));
tokio::spawn(read_frames(output, replies.clone(), closed.clone()));
Self { closed, exited, sequence: AtomicU64::new(1), outgoing, replies }
}
pub(super) fn shutdown(&self) {
self.closed.cancel();
}
pub(super) fn is_closed(&self) -> bool {
self.closed.is_cancelled()
}
pub(super) async fn close(&self) {
self.shutdown();
self.exited.cancelled().await;
}
async fn send(&self, frame: Vec<u8>, session: &CancellationToken) -> IdeResult<()> {
let (sent, receipt) = oneshot::channel();
tokio::select! {
() = self.closed.cancelled() => return Err(disconnected()),
result = self.outgoing.send(Outgoing { frame, session: session.clone(), sent }) => {
result.map_err(|_| disconnected())?;
}
}
tokio::select! {
biased;
result = receipt => result.map_err(|_| disconnected())?,
() = self.closed.cancelled() => Err(disconnected()),
}
}
pub(super) async fn exchange(
&self,
session: u32,
fields: &[&str],
cancel: &CancellationToken,
active: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
if cancel.is_cancelled() {
return Ok(None);
}
if active.is_cancelled() {
return Err(IdeError::cancelled());
}
let id = self
.sequence
.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1))
.map_err(|_| IdeError::internal("JDBC request IDs exhausted"))?;
let frame = encode(id, session, fields)?;
let (sender, incoming) = mpsc::channel(2);
self.replies.lock().insert(id, sender);
let mut pending = Pending { bridge: self, id, incoming };
let send = self.send(frame, active);
tokio::pin!(send);
let early_deadline = tokio::select! {
result = &mut send => { result?; None },
() = cancel.cancelled() => {
let end = Instant::now() + CANCEL_GRACE;
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
Some(end)
}
};
let deadline = tokio::select! {
biased;
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Instant::now() + CANCEL_GRACE),
data = pending.recv() => {
let data = data?;
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
return Ok(Some(data));
}
};
let data = timeout_at(deadline, async {
self.send(header(id, session, 0).to_vec(), active).await?;
let first = pending.recv().await?;
let second = pending.recv().await?;
match (first.is_empty(), second.is_empty()) {
(true, false) => Ok(second),
(false, true) => Ok(first),
_ => Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement")),
}
})
.await
.map_err(|_| cancel_timeout())??;
match data.first() {
// A committed statement may finish before the bridge receives Cancel.
Some(1) => Ok(Some(data)),
Some(0) => Ok(None),
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
}
}
pub(super) async fn close_session(&self, session: u32) -> IdeResult<()> {
if self.is_closed() {
return Ok(());
}
let control = CancellationToken::new();
let data = timeout(CANCEL_GRACE, self.exchange(session, &["close"], &control, &control))
.await
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "Closing the JDBC console timed out"))??;
super::decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.).map(|_| ())
}
}
impl Drop for Bridge {
fn drop(&mut self) {
self.shutdown();
}
}
async fn write_frames(
mut input: impl AsyncWrite + Unpin,
mut writes: mpsc::Receiver<Outgoing>,
closed: CancellationToken,
) {
while let Some(outgoing) = tokio::select! {
biased;
() = closed.cancelled() => None,
outgoing = writes.recv() => outgoing,
} {
// If Close raced with an enqueued Open or query, discard it before writing.
if outgoing.session.is_cancelled() {
let _ = outgoing.sent.send(Err(IdeError::cancelled()));
continue;
}
let result = tokio::select! {
() = closed.cancelled() => break,
result = input.write_all(&outgoing.frame) => result.map_err(IdeError::from),
};
let failed = result.is_err();
let _ = outgoing.sent.send(result);
if failed {
break;
}
}
closed.cancel();
}
async fn read_frames(mut output: impl AsyncRead + Unpin, replies: Replies, closed: CancellationToken) {
loop {
let frame = async {
let id = output.read_u64().await?;
Ok::<_, IdeError>((id, read_frame(&mut output).await?))
};
let (id, data) = match tokio::select! {
() = closed.cancelled() => break,
result = frame => result,
} {
Ok(frame) => frame,
Err(_) => break,
};
let sender = replies.lock().get(&id).cloned();
// A response may arrive after its caller was cancelled and retired.
if let Some(sender) = sender
&& matches!(sender.try_send(data), Err(mpsc::error::TrySendError::Full(_)))
{
break;
}
}
closed.cancel();
}
fn disconnected() -> IdeError {
IdeError::new(ErrorKind::Io, "JDBC connection was lost")
}
fn cancel_timeout() -> IdeError {
IdeError::invalid(
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
)
}
fn header(id: u64, session: u32, fields: u32) -> [u8; HEADER] {
let mut bytes = [0; HEADER];
bytes[..8].copy_from_slice(&id.to_be_bytes());
bytes[8..12].copy_from_slice(&session.to_be_bytes());
bytes[12..].copy_from_slice(&fields.to_be_bytes());
bytes
}
pub(super) fn frame_size(fields: &[&str]) -> IdeResult<usize> {
if fields.is_empty() || fields.len() > 8192 {
return Err(IdeError::invalid("Invalid JDBC field count"));
}
fields
.iter()
.try_fold(HEADER, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))
}
fn encode(id: u64, session: u32, fields: &[&str]) -> IdeResult<Vec<u8>> {
let size = frame_size(fields)?;
let mut data = Vec::with_capacity(size);
data.extend_from_slice(&header(id, session, fields.len() as u32));
for field in fields {
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
data.extend_from_slice(field.as_bytes());
}
Ok(data)
}
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
let n = output.read_u32().await? as usize;
if n > LIMIT {
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
}
let mut data = vec![0; n];
output.read_exact(&mut data).await?;
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, 3, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
let mut field = "x".repeat(LIMIT - HEADER - 4);
assert_eq!(encode(1, 0, &[&field]).unwrap().len(), LIMIT);
field.push('x');
assert!(encode(1, 0, &[&field]).is_err());
let mut framed = vec![0u8; LIMIT + 4];
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
}
async fn reply(output: &mut (impl AsyncWrite + Unpin), id: u64, body: &[u8]) {
output.write_u64(id).await.unwrap();
output.write_u32(body.len() as u32).await.unwrap();
output.write_all(body).await.unwrap();
}
#[tokio::test]
async fn exchange_rejects_an_acknowledgement_for_an_uncancelled_request() {
let (input, mut peer_input) = tokio::io::duplex(32);
let (output, mut peer_output) = tokio::io::duplex(32);
let active = CancellationToken::new();
let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new());
let peer = async {
let frame = encode(1, 0, &["query"]).unwrap();
let mut actual = vec![0; frame.len()];
peer_input.read_exact(&mut actual).await.unwrap();
assert_eq!(actual, frame);
reply(&mut peer_output, 1, &[]).await;
};
let (result, ()) = tokio::join!(bridge.exchange(0, &["query"], &active, &active), peer);
assert!(result.unwrap_err().message.contains("Unexpected JDBC cancellation acknowledgement"));
}
#[tokio::test]
async fn cancellation_drains_tagged_replies_without_stealing_a_siblings_response() {
for ack_first in [true, false] {
let (input, mut peer_input) = tokio::io::duplex(1);
let (output, mut peer_output) = tokio::io::duplex(1);
let active = CancellationToken::new();
let cancel = CancellationToken::new();
let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new());
let peer = async {
let frame = encode(1, 11, &["query"]).unwrap();
let mut request = vec![0; frame.len()];
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, frame);
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, encode(2, 22, &["query"]).unwrap());
// Cancel during a partial reply header; the reader must stay on that frame.
peer_output.write_all(&1u64.to_be_bytes()[..2]).await.unwrap();
cancel.cancel();
let mut stop = [0; HEADER];
peer_input.read_exact(&mut stop).await.unwrap();
assert_eq!(stop, header(1, 11, 0));
peer_output.write_all(&1u64.to_be_bytes()[2..]).await.unwrap();
let terminal = !ack_first;
peer_output.write_u32(u32::from(terminal)).await.unwrap();
if terminal {
peer_output.write_u8(1).await.unwrap();
}
reply(&mut peer_output, 2, &[1, b'b']).await;
reply(&mut peer_output, 1, if ack_first { &[0] } else { &[] }).await;
};
let (a, b, ()) = tokio::join!(
biased;
bridge.exchange(11, &["query"], &cancel, &active),
bridge.exchange(22, &["query"], &active, &active),
peer,
);
assert_eq!(a.unwrap(), (!ack_first).then(|| vec![1]));
assert_eq!(b.unwrap(), Some(vec![1, b'b']));
}
}
}
+327 -299
Переглянути файл
@@ -2,21 +2,21 @@
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::local_settings::persist_local;
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use crate::{ConsoleId, DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::process::{ChildStdin, ChildStdout, Command};
use tokio::sync::Mutex;
use tokio::time::{Instant as Deadline, timeout_at};
use tokio::time::timeout;
const LIMIT: usize = 16 * 1024 * 1024;
mod bridge;
use bridge::Bridge;
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -203,171 +203,73 @@ impl DbManager {
}
}
struct Bridge {
stop: tokio::sync::oneshot::Sender<()>,
exited: tokio::task::JoinHandle<()>,
sequence: u64,
input: ChildStdin,
output: ChildStdout,
struct Session {
id: u32,
// A physical JDBC Connection executes one request at a time.
opened: Mutex<bool>,
retired: CancellationToken,
}
impl Session {
fn new(id: u32) -> Self {
Self { id, opened: Mutex::new(id == 0), retired: CancellationToken::new() }
}
}
#[derive(Default)]
struct ConsoleSessions {
latest: u32,
opened: HashMap<(String, String), Arc<Session>>,
}
pub struct JdbcPool {
bridge: Mutex<Option<Bridge>>,
closed: CancellationToken,
bridge: Arc<Bridge>,
service: Session,
consoles: parking_lot::Mutex<ConsoleSessions>,
shared_connection: bool,
pub(crate) version: String,
pub(crate) identifier_quote: String,
}
impl Bridge {
fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
let jdks = ide_sdk::java::installed_jdks();
let java = ide_sdk::java::java_runtime(&jdks, 17)
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
// Embedded databases can resolve file URLs against the JVM's working directory.
let files = cache.join("files");
std::fs::create_dir_all(&files)?;
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
command.current_dir(files);
ide_core::process::prepare(command.as_std_mut());
let mut child = command
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
.arg(classpath)
.arg("ai.openidea.jdbc.OpenIdeaJdbc")
.env_remove("CLASSPATH")
.env_remove("JDK_JAVA_OPTIONS")
.env_remove("JAVA_TOOL_OPTIONS")
.env_remove("_JAVA_OPTIONS")
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let input = child.stdin.take().expect("piped");
let output = child.stdout.take().expect("piped");
let (stop, stopped) = tokio::sync::oneshot::channel();
let exited = tokio::spawn(async move {
tokio::select! {
stop = stopped => {
// Disconnect closes stdin so a file-backed driver can flush. A dropped
// request or an unresponsive driver must be reaped without waiting.
if stop.is_err() || tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() {
let _ = child.kill().await;
}
}
_ = child.wait() => {}
}
});
Ok(Self { input, output, stop, exited, sequence: 0 })
}
async fn close(self) {
drop(self.input);
let _ = self.stop.send(());
let _ = self.exited.await;
}
/// Dropped futures and uncertain transport errors retire the connection they were using.
struct ActiveRequest<'a> {
pool: &'a JdbcPool,
session: &'a Session,
completed: bool,
}
// Request: u64 request id, u32 field count, then length-prefixed UTF-8 fields.
// Zero fields cancels that id. Replies have a u32 length; zero acknowledges Cancel.
fn encode(id: u64, fields: &[&str]) -> IdeResult<Vec<u8>> {
if fields.is_empty() || fields.len() > 8192 {
return Err(IdeError::invalid("Invalid JDBC field count"));
}
let size = fields
.iter()
.try_fold(12usize, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))?;
let mut data = Vec::with_capacity(size);
data.extend_from_slice(&id.to_be_bytes());
data.extend_from_slice(&(fields.len() as u32).to_be_bytes());
for field in fields {
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
data.extend_from_slice(field.as_bytes());
}
Ok(data)
}
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
let n = output.read_u32().await? as usize;
if n > LIMIT {
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
}
let mut data = vec![0; n];
output.read_exact(&mut data).await?;
Ok(data)
}
const CANCEL_GRACE: Duration = Duration::from_secs(3);
fn cancel_timeout() -> IdeError {
IdeError::invalid(
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
)
}
async fn exchange(
input: &mut (impl AsyncWrite + Unpin),
output: &mut (impl AsyncRead + Unpin),
frame: Vec<u8>,
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
let mut stop = [0; 12];
stop[..8].copy_from_slice(&frame[..8]);
let early_deadline = {
let send = input.write_all(&frame);
tokio::pin!(send);
tokio::select! {
result = &mut send => { result?; None },
() = cancel.cancelled() => {
let end = Deadline::now() + CANCEL_GRACE;
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
Some(end)
}
impl Drop for ActiveRequest<'_> {
fn drop(&mut self) {
if !self.completed {
self.pool.retire(self.session);
}
};
drop(frame);
let (first, deadline) = {
let reply = read_frame(output);
tokio::pin!(reply);
let end = tokio::select! {
biased;
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Deadline::now() + CANCEL_GRACE),
data = &mut reply => {
let data = data?;
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
return Ok(Some(data));
}
};
let first = timeout_at(end, async {
input.write_all(&stop).await?;
reply.await
})
.await
.map_err(|_| cancel_timeout())??;
(first, end)
};
// Drain both frames before the next statement can use this session. The driver
// may complete the statement before or after the control thread acknowledges it.
let data = if first.is_empty() {
timeout_at(deadline, read_frame(output)).await.map_err(|_| cancel_timeout())??
} else {
if timeout_at(deadline, output.read_u32()).await.map_err(|_| cancel_timeout())?? != 0 {
return Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement"));
}
first
};
match data.first() {
// A committed statement may have finished before the control thread received Cancel.
Some(1) => Ok(Some(data)),
Some(0) => Ok(None),
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
}
}
/// A second connection to an anonymous database would see a different database.
fn private_database_url(url: &str) -> bool {
if let Some(h2) = url.strip_prefix("jdbc:h2:mem:") {
return h2.is_empty() || h2.starts_with(';');
}
let Some(sqlite) = url.strip_prefix("jdbc:sqlite:") else {
return false;
};
let (path, query) = sqlite.split_once('?').unwrap_or((sqlite, ""));
if matches!(path, "" | ":memory:" | "file:") {
return true;
}
let option = |name| {
query
.split('&')
.rev()
.filter_map(|part| part.split_once('='))
.find_map(|(key, value)| (key == name).then_some(value))
};
path.starts_with("file:")
&& (path == "file::memory:" || option("mode") == Some("memory"))
&& option("cache") != Some("shared")
}
impl JdbcPool {
async fn connect(
source: &DataSource,
@@ -393,32 +295,85 @@ impl JdbcPool {
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let mut pool = Self {
bridge: Mutex::new(Some(bridge)),
closed: CancellationToken::new(),
version: String::new(),
identifier_quote: String::new(),
};
let args: Vec<_> = fields.iter().map(String::as_str).collect();
let cancel = CancellationToken::new();
let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel))
let data = timeout(Duration::from_secs(30), bridge.exchange(0, &args, &cancel, &cancel))
.await
.map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??;
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
let result = decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter();
pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into());
pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into();
Ok(pool)
Ok(Self {
bridge: Arc::new(bridge),
service: Session::new(0),
consoles: Default::default(),
shared_connection: private_database_url(&source.url),
version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()),
identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(),
})
}
pub(crate) async fn close(&self) {
self.closed.cancel();
if let Some(bridge) = self.bridge.lock().await.take() {
bridge.close().await;
}
self.bridge.close().await;
}
pub(crate) fn is_closed(&self) -> bool {
self.closed.is_cancelled()
self.bridge.is_closed()
}
fn console(&self, console: ConsoleId<'_>) -> IdeResult<Arc<Session>> {
let key = (console.window.to_owned(), console.path.to_owned());
let mut sessions = self.consoles.lock();
if let Some(existing) = sessions.opened.get(&key)
&& !existing.retired.is_cancelled()
{
return Ok(existing.clone());
}
let id = sessions.latest.checked_add(1).ok_or_else(|| IdeError::internal("JDBC session IDs exhausted"))?;
sessions.latest = id;
let session = Arc::new(Session::new(id));
sessions.opened.insert(key, session.clone());
Ok(session)
}
pub(crate) async fn release_console(&self, console: ConsoleId<'_>) -> IdeResult<()> {
let key = (console.window.to_owned(), console.path.to_owned());
// Retire the ID before allowing a reopened editor to allocate a replacement.
let session = self.consoles.lock().opened.remove(&key).inspect(|session| session.retired.cancel());
if let Some(session) = session {
let closed = self.bridge.close_session(session.id).await;
self.shutdown_service_if_idle();
closed?;
}
Ok(())
}
fn retire(&self, session: &Session) {
if session.retired.is_cancelled() {
return;
}
session.retired.cancel();
if session.id != 0 {
let bridge = self.bridge.clone();
let id = session.id;
tokio::spawn(async move {
let _ = bridge.close_session(id).await;
});
}
self.shutdown_service_if_idle();
}
fn shutdown_service_if_idle(&self) {
if !self.service.retired.is_cancelled() {
return;
}
let has_consoles =
self.consoles.lock().opened.values().any(|session| {
!session.retired.is_cancelled() && session.opened.try_lock().map_or(true, |opened| *opened)
});
// Service failure cannot discard a healthy editor's transaction or temporary tables.
if !has_consoles {
self.bridge.shutdown();
}
}
pub(crate) async fn query(
@@ -439,7 +394,21 @@ impl JdbcPool {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.request(
self.query_in_console(sql, skip, max, cancel, schema, None).await
}
pub(crate) async fn query_in_console(
&self,
sql: &str,
skip: usize,
max: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
let session = console.filter(|_| !self.shared_connection).map(|console| self.console(console)).transpose()?;
self.request_on(
session.as_deref().unwrap_or(&self.service),
&["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()],
sql,
cancel,
@@ -457,82 +426,91 @@ impl JdbcPool {
self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await
}
/// Introspection on this connection. `catalogs` lists live catalogs with the current one marked.
/// `schemas`, `tables`, `schemaColumns`, and `columns` accept a final catalog argument.
pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult<Vec<Vec<Option<String>>>> {
Ok(self.request(fields, "", &CancellationToken::new()).await?.rows)
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let result = self.exchange_once(fields, sql, cancel).await;
if let Err(e) = &result
&& fields.first() != Some(&"open")
&& e.kind != ide_core::error::ErrorKind::Cancelled
&& !self.is_closed()
&& !self.session_valid().await
{
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
// pool so the next statement or Connect starts a new one instead of failing forever.
self.close().await;
self.request_on(&self.service, fields, sql, cancel).await
}
async fn request_on(
&self,
session: &Session,
fields: &[&str],
sql: &str,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
// A rejected local request has not used the connection and cannot invalidate it.
bridge::frame_size(fields)?;
let mut opened = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = session.retired.cancelled() => {
return Err(if session.id == 0 {
IdeError::new(ErrorKind::Io, "The JDBC service connection was lost. Reconnect to restore catalog access.")
} else {
IdeError::cancelled()
});
}
slot = session.opened.lock() => slot,
};
let mut active = ActiveRequest { pool: self, session, completed: false };
if !*opened {
let data = timeout(Duration::from_secs(30), self.exchange(session, &["open"], cancel))
.await
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
*opened = true;
}
let start = Instant::now();
let data = self.exchange(session, fields, cancel).await?;
let result = data
.ok_or_else(IdeError::cancelled)
.and_then(|data| decode(&data, sql, start.elapsed().as_secs_f64() * 1000.0));
if result.as_ref().is_err_and(|error| error.kind != ErrorKind::Cancelled) && !self.session_valid(session).await
{
return result;
}
active.completed = true;
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
async fn exchange(
&self,
session: &Session,
fields: &[&str],
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
tokio::select! {
biased;
() = session.retired.cancelled() => Err(IdeError::cancelled()),
data = self.bridge.exchange(session.id, fields, cancel, &session.retired) => data,
}
}
/// Keep-alive operates on the service connection without waiting on an editor's query.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
let _service = self.service.opened.lock().await;
if self.service.retired.is_cancelled() || self.session_valid(&self.service).await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
self.retire(&self.service);
Err(IdeError::new(ErrorKind::Io, "JDBC connection was lost"))
}
/// Whether the JDBC session still works, asked after a failed statement.
async fn session_valid(&self) -> bool {
if self.bridge.lock().await.is_none() {
return false;
}
/// Checks that an error was local to this statement before reusing its connection.
async fn session_valid(&self, session: &Session) -> bool {
let cancel = CancellationToken::new();
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
Ok(Ok(result)) => {
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
}
Ok(Err(_)) | Err(_) => false,
}
}
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.closed.cancelled() => return Err(IdeError::invalid("JDBC connection is closed")),
slot = self.bridge.lock() => slot,
let Ok(Ok(Some(data))) = timeout(Duration::from_secs(10), self.exchange(session, &["valid"], &cancel)).await
else {
return false;
};
let bridge = slot
.as_mut()
.ok_or_else(|| IdeError::invalid("JDBC connection is closed; reconnect to start a new session"))?;
bridge.sequence = bridge.sequence.wrapping_add(1);
let frame = encode(bridge.sequence, fields)?;
let mut bridge = slot.take().expect("checked above");
// Dropping an in-flight request must discard its process and partially consumed frame.
let interrupted = self.closed.clone().drop_guard();
let start = Instant::now();
let response = tokio::select! {
biased;
() = self.closed.cancelled() => Err(IdeError::cancelled()),
response = exchange(&mut bridge.input, &mut bridge.output, frame, cancel) => response,
};
let data = match response {
Ok(data) => {
*slot = Some(bridge);
interrupted.disarm();
data
}
Err(e) => {
drop(bridge.stop);
let _ = bridge.exited.await;
return Err(e);
}
};
decode(&data.ok_or_else(IdeError::cancelled)?, sql, start.elapsed().as_secs_f64() * 1000.0)
decode(&data, "", 0.).is_ok_and(|result| {
result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) == Some("true")
})
}
}
@@ -655,7 +633,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 +642,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
@@ -679,85 +660,132 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
mod tests {
use super::*;
#[test]
fn only_private_jdbc_databases_keep_one_connection() {
for url in [
"jdbc:sqlite:",
"jdbc:sqlite::memory:",
"jdbc:sqlite:file:",
"jdbc:sqlite:file:private?mode=memory&cache=private",
"jdbc:h2:mem:",
"jdbc:h2:mem:;DB_CLOSE_DELAY=-1",
] {
assert!(private_database_url(url), "{url}");
}
for url in [
"jdbc:sqlite:/tmp/data.db",
"jdbc:sqlite:file:data.db?cache=shared",
"jdbc:sqlite:file:shared?mode=memory&cache=shared",
"jdbc:sqlite:file::memory:?cache=shared",
"jdbc:h2:mem:shared;DB_CLOSE_DELAY=-1",
"jdbc:h2:file:/tmp/data",
"jdbc:h2:tcp://server/data",
"jdbc:duckdb:",
"jdbc:clickhouse://localhost/default",
] {
assert!(!private_database_url(url), "{url}");
}
}
#[test]
fn schema_columns_group_by_table() {
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);
}
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
let mut field = "x".repeat(LIMIT - 16);
assert_eq!(encode(1, &[&field]).unwrap().len(), LIMIT);
field.push('x');
assert!(encode(1, &[&field]).is_err());
let mut framed = vec![0u8; LIMIT + 4];
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
}
#[tokio::test]
async fn cancel_drains_partial_replies_in_either_order() {
for ack_first in [true, false] {
let (mut input, mut peer_input) = tokio::io::duplex(1);
let (mut output, mut peer_output) = tokio::io::duplex(1);
let cancel = CancellationToken::new();
let frame = encode(42, &["query"]).unwrap();
let peer = async {
let mut request = vec![0; frame.len()];
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, frame);
// The one-byte pipe forces the reader to consume part of the header before Cancel.
peer_output.write_all(&[0, 0]).await.unwrap();
cancel.cancel();
let mut stop = [0; 12];
peer_input.read_exact(&mut stop).await.unwrap();
assert_eq!(&stop[..8], &42u64.to_be_bytes());
assert_eq!(&stop[8..], &[0; 4]);
let frames = if ack_first { [0, 0, 0, 0, 0, 1, 0] } else { [0, 1, 1, 0, 0, 0, 0] };
peer_output.write_all(&frames).await.unwrap();
};
let (result, ()) = tokio::join!(exchange(&mut input, &mut output, frame.clone(), &cancel), peer);
assert_eq!(result.unwrap(), (!ack_first).then(|| vec![1]));
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_live_catalog_metadata_is_scoped_to_the_requested_namespace() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
let driver = DbJdbcDriver {
id: "duckdb".into(),
name: "DuckDB".into(),
vendor: None,
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: String::new(),
};
let pool = JdbcPool::connect(&source, None, driver, tmp.path().join("jdbc")).await?;
let stop = CancellationToken::new();
let path = |file| tmp.path().join(file).to_string_lossy().replace('\'', "''");
let archive = "archive.db:1";
for sql in [
"SET threads = 1".into(),
"CREATE TABLE memory.main.dupe (root_only INT)".into(),
format!("ATTACH '{}' AS first", path("first.duckdb")),
format!(r#"ATTACH '{}' AS "archive.db:1""#, path("archive.duckdb")),
"CREATE TABLE first.main.dupe (first_only INT PRIMARY KEY)".into(),
r#"CREATE TABLE "archive.db:1".main.dupe (archive_only INT)"#.into(),
r#"CREATE SCHEMA "archive.db:1"."qa_%""#.into(),
r#"CREATE SCHEMA "archive.db:1".qaSimilar"#.into(),
r#"CREATE TABLE "archive.db:1"."qa_%"."t_%""q" (quoted_only INT PRIMARY KEY)"#.into(),
r#"COMMENT ON TABLE "archive.db:1"."qa_%"."t_%""q" IS 'Archive table'"#.into(),
r#"COMMENT ON COLUMN "archive.db:1"."qa_%"."t_%""q".quoted_only IS 'In the archive'"#.into(),
r#"CREATE TABLE "archive.db:1".qaSimilar."t_%""q" (wrong_schema INT)"#.into(),
r#"COMMENT ON TABLE "archive.db:1".qaSimilar."t_%""q" IS 'Wrong schema table'"#.into(),
r#"COMMENT ON COLUMN "archive.db:1".qaSimilar."t_%""q".wrong_schema IS 'Outside the schema'"#.into(),
] {
pool.query(&sql, 0, 1, &stop).await?;
}
}
#[tokio::test]
async fn exchange_rejects_unexpected_acknowledgements() {
let cancel = CancellationToken::new();
let mut sink = tokio::io::sink();
let mut reply = &[0, 0, 0, 1, 1u8][..];
assert_eq!(
exchange(&mut sink, &mut reply, encode(1, &["query"]).unwrap(), &cancel).await.unwrap(),
Some(vec![1])
);
for cancelled in [false, true] {
if cancelled {
cancel.cancel();
}
let mut duplicate_ack = &[0u8; 8][..];
assert!(exchange(&mut sink, &mut duplicate_ack, encode(1, &["query"]).unwrap(), &cancel).await.is_err());
let catalogs = pool.metadata(&["catalogs"]).await?;
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
let schemas = pool.metadata(&["schemas", archive]).await?;
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
assert_eq!(tables.len(), 1);
assert_eq!(tables[0][0].as_deref(), Some(r#"t_%"q"#));
assert_eq!(tables[0][2].as_deref(), Some("Archive table"));
for (catalog, column, primary) in
[("memory", "root_only", "0"), ("first", "first_only", "1"), (archive, "archive_only", "0")]
{
let columns = pool.metadata(&["columns", "main", "dupe", catalog]).await?;
assert_eq!(columns.len(), 1);
assert_eq!(columns[0][0].as_deref(), Some(column));
assert_eq!(columns[0][4].as_deref(), Some(primary));
}
let (mut peer, mut output) = tokio::io::duplex(4);
peer.write_u32(0).await.unwrap();
let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err();
assert_eq!(error.message, cancel_timeout().message);
let quoted = pool.metadata(&["columns", "qa_%", r#"t_%"q"#, archive]).await?;
assert_eq!(quoted.len(), 1);
assert_eq!(quoted[0][0].as_deref(), Some("quoted_only"));
assert_eq!(quoted[0][4].as_deref(), Some("1"));
let all = schema_columns(pool.metadata(&["schemaColumns", "qa_%", archive]).await?);
assert_eq!(all.len(), 1);
assert_eq!(all[r#"t_%"q"#][0].name, "quoted_only");
assert_eq!(all[r#"t_%"q"#][0].comment.as_deref(), Some("In the archive"));
pool.query("USE first", 0, 1, &stop).await?;
let catalogs = pool.metadata(&["catalogs"]).await?;
assert!(catalogs.contains(&vec![Some("first".into()), Some("1".into())]));
let legacy = pool.metadata(&["columns", "main", "dupe"]).await?;
assert_eq!(legacy[0][0].as_deref(), Some("first_only"));
pool.query("USE memory", 0, 1, &stop).await?;
pool.query("DETACH first", 0, 1, &stop).await?;
let catalogs = pool.metadata(&["catalogs"]).await?;
assert!(!catalogs.iter().any(|r| r[0].as_deref() == Some("first")));
assert!(pool.metadata(&["schemas", "first"]).await?.is_empty());
assert!(pool.metadata(&["tables", "main", "first"]).await?.is_empty());
assert!(pool.metadata(&["columns", "main", "dupe", "first"]).await?.is_empty());
pool.close().await;
Ok(())
}
#[test]
+440 -113
Переглянути файл
@@ -8,6 +8,7 @@ mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
mod local_settings;
mod manual_session;
mod route;
mod tunnel_approval;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
@@ -31,7 +32,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};
@@ -42,7 +43,7 @@ use parking_lot::Mutex;
use secrets::SecretStore;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
@@ -146,6 +147,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 +162,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)]
@@ -166,12 +175,40 @@ pub struct IndexInfo {
pub name: String,
pub unique: bool,
pub columns: Vec<String>,
/// The key this index enforces; such an index is dropped with its constraint, not `drop index`.
/// `None` for a plain index, and on engines that don't tell.
#[serde(default)]
#[specta(optional)]
pub key: Option<DbKeyKind>,
}
/// A table key backed by an index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbKeyKind {
Primary,
Unique,
}
impl DbKeyKind {
/// The [`sql::indexes`] key column: `p` (primary key), `u` (unique constraint).
fn from_catalog(v: Option<&str>) -> Option<Self> {
match v {
Some("p") => Some(Self::Primary),
Some("u") => Some(Self::Unique),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[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 +237,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)]
@@ -294,9 +335,37 @@ pub struct DbManager {
on_disk: Mutex<Option<Vec<DataSource>>>,
}
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
use manual_session::Session;
/// A SQL editor's connection identity within the owning project's lifetime.
#[derive(Clone, Copy)]
pub struct ConsoleId<'a> {
pub window: &'a str,
pub path: &'a str,
expected_manual: Option<bool>,
}
impl<'a> ConsoleId<'a> {
pub const fn new(window: &'a str, path: &'a str) -> Self {
Self { window, path, expected_manual: None }
}
pub fn expecting_manual(mut self, manual: Option<bool>) -> Self {
self.expected_manual = manual;
self
}
}
fn postgres_console_mode_changed() -> IdeError {
IdeError::new(
ErrorKind::OutOfSync,
"PostgreSQL console transaction mode changed. Set the mode again before running SQL.",
)
}
const MAX_META_ROWS: usize = 100_000;
/// Completion columns of the default schema, which are read without the shared cap.
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
@@ -366,6 +435,41 @@ fn tunnel_target(source: &DataSource) -> (&str, u16) {
(if source.host.trim().is_empty() { "localhost" } else { source.host.trim() }, port)
}
fn is_duckdb(source: &DataSource) -> bool {
const PREFIX: &str = "jdbc:duckdb:";
source.driver == DbDriver::Jdbc
&& (source.vendor == "duckdb"
|| source.url.trim().get(..PREFIX.len()).is_some_and(|url| url.eq_ignore_ascii_case(PREFIX)))
}
async fn duckdb_catalog(pool: &Pool, database: &str) -> IdeResult<Vec<CatalogSchema>> {
// List empty schemas too and put all schema names before the bounded table rows.
const MAX_CATALOG_ROWS: usize = 20_000;
let name = sql::quote_literal(DbDriver::Jdbc, database);
let query = format!(
"SELECT schema_name AS schema, NULL::VARCHAR AS name, NULL::VARCHAR AS kind, NULL::VARCHAR AS comment \
FROM system.main.duckdb_schemas() WHERE database_name = {name} \
UNION ALL \
SELECT table_schema, table_name, lower(table_type), table_comment \
FROM system.information_schema.tables WHERE table_catalog = {name} \
ORDER BY name NULLS FIRST, schema LIMIT {MAX_CATALOG_ROWS}"
);
let mut schemas = BTreeMap::<String, Vec<TableInfo>>::new();
for row in pool.rows(&query, MAX_CATALOG_ROWS).await? {
let mut values = row.into_iter();
let Some(Some(schema)) = values.next() else { continue };
let tables = schemas.entry(schema).or_default();
if let Some(Some(name)) = values.next() {
tables.push(TableInfo {
name,
kind: DbTableKind::from_catalog(values.next().flatten().as_deref()),
comment: values.next().flatten().filter(|comment| !comment.is_empty()),
});
}
}
Ok(schemas.into_iter().map(|(name, tables)| CatalogSchema { name, tables }).collect())
}
pub fn split_target(target: &str) -> (&str, Option<&str>) {
match target.split_once(':') {
Some((id, db)) if !db.is_empty() => (id, Some(db)),
@@ -404,12 +508,7 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
/// Rolls back a session's transaction and releases its connection.
async fn end_session(session: &Session) {
let held = session.lock().await.take();
if let Some(mut conn) = held
&& (conn.finish_manual(false).await.is_err() || conn.restore_default().await.is_err())
{
conn.discard().await;
}
let _ = session.rollback_and_release().await;
}
impl DbManager {
@@ -558,6 +657,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 {
@@ -948,12 +1059,30 @@ impl DbManager {
Ok(())
}
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
/// What databases this data source can see, including DuckDB's live attachments.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
let introspection = self.source(id)?.introspection;
let source = self.source(id)?;
let introspection = &source.introspection;
let system = introspection.show_system;
let pool = self.pool(id).await?;
if let Pool::Jdbc(p) = &*pool
&& is_duckdb(&source)
{
let mut current = String::new();
let mut names = Vec::new();
for mut row in p.metadata(&["catalogs"]).await? {
if let [Some(name), active] = row.as_mut_slice() {
if active.as_deref() == Some("1") {
current = name.clone();
names.insert(0, std::mem::take(name));
} else if system || name != "system" {
names.push(std::mem::take(name));
}
}
}
return Ok(Databases { current, names });
}
if pool.driver() == DbDriver::SqlServer {
let first =
|rows: Vec<Vec<Option<String>>>| rows.into_iter().filter_map(|r| r.into_iter().next().flatten());
@@ -992,12 +1121,13 @@ impl DbManager {
Ok(Databases { current, names })
}
/// The schemas of `database` of data source `id` with their tables and views (Snowflake):
/// what completion needs to follow `database.schema.table` without the tree being opened.
/// The result is also saved ([`DbManager::saved_catalog`]) for the next run.
/// The schemas of `database` with their tables and views for qualified SQL completion.
/// Snowflake's result is also saved ([`DbManager::saved_catalog`]) for the next run.
pub async fn database_catalog(&self, id: &str, database: &str) -> IdeResult<Vec<CatalogSchema>> {
let id = split_target(id).0;
let schemas = match &*self.pool(id).await? {
let pool = self.pool(id).await?;
let schemas = match &*pool {
Pool::Jdbc(_) if is_duckdb(&self.source(id)?) => return duckdb_catalog(&pool, database).await,
Pool::Snowflake(p) => snowflake::meta::catalog(p, database).await?,
_ => return Err(IdeError::invalid("this data source does not list other databases")),
};
@@ -1093,19 +1223,54 @@ 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())
}
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let source = self.source(id)?;
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
}
self.pool(id).await
}
pub async fn catalog_table_details(
&self,
id: &str,
catalog: &str,
schema: &str,
table: &str,
) -> IdeResult<TableDetails> {
let pool = self.duckdb_catalog_pool(id).await?;
Self::table_details_on(&pool, Some(catalog), schema, table).await
}
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
let pool = self.pool(id).await?;
if let Pool::Snowflake(p) = &*pool {
Self::table_details_on(&pool, None, schema, table).await
}
async fn table_details_on(
pool: &Pool,
catalog: Option<&str>,
schema: &str,
table: &str,
) -> IdeResult<TableDetails> {
if let Pool::Snowflake(p) = pool {
return snowflake::meta::table_details(p, schema, table).await;
}
let driver = pool.driver();
let rows = match &*pool {
Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?,
let rows = match pool {
Pool::Jdbc(p) => match catalog {
Some(catalog) => p.metadata(&["columns", schema, table, catalog]).await?,
None => p.metadata(&["columns", schema, table]).await?,
},
_ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?,
};
let columns = rows
@@ -1117,11 +1282,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? {
@@ -1132,7 +1304,12 @@ impl DbManager {
};
match indexes.last_mut() {
Some(last) if last.name == name => last.columns.push(col),
_ => indexes.push(IndexInfo { name, unique: flag(&unique), columns: vec![col] }),
_ => indexes.push(IndexInfo {
name,
unique: flag(&unique),
columns: vec![col],
key: DbKeyKind::from_catalog(it.next().flatten().as_deref()),
}),
}
}
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
@@ -1173,7 +1350,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
@@ -1383,10 +1570,13 @@ impl DbManager {
}
DbDriver::Postgres => {
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
let (oid, kind) = match rel.as_deref() {
Some([Some(oid), Some(kind)]) => {
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
}
let (oid, kind, owner, comment) = match rel.as_deref() {
Some([Some(oid), Some(kind), owner, comment]) => (
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
kind.clone(),
owner.clone(),
comment.clone(),
),
_ => return Err(missing()),
};
if kind == "v" || kind == "m" {
@@ -1407,6 +1597,7 @@ impl DbManager {
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
})
.collect::<Vec<_>>();
@@ -1420,7 +1611,18 @@ impl DbManager {
})
.collect::<Vec<_>>();
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
let grants = pool
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
})
.collect();
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
let extras = sql::DdlExtras { comment, owner, grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
}
}
}
@@ -1429,13 +1631,34 @@ impl DbManager {
let pool = self.pool(id).await?;
let driver = pool.driver();
let mut tables: Vec<CompletionTable> = Vec::new();
if let Pool::Jdbc(p) = &*pool {
return self.jdbc_completion(id, p).await;
}
let default_schema = match sql::current_schema(driver) {
None => "main".to_owned(),
Some(q) => pool
.rows(q, 1)
.await?
.into_iter()
.next()
.and_then(|r| r.into_iter().next().flatten())
.unwrap_or_default(),
};
let rows = match &*pool {
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
Pool::Snowflake(p) => {
tables = snowflake::meta::completion(p).await?;
Vec::new()
}
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
// The default schema is read in full: under a shared row cap, a schema with many
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
_ if !default_schema.is_empty() => {
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
rows
}
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
};
for r in rows {
let mut it = r.into_iter().map(Option::unwrap_or_default);
@@ -1447,6 +1670,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;
@@ -1471,16 +1695,6 @@ impl DbManager {
})
};
let foreign_keys = group_foreign_keys(fk_rows, &tables);
let default_schema = match sql::current_schema(driver) {
None => "main".to_owned(),
Some(q) => pool
.rows(q, 1)
.await?
.into_iter()
.next()
.and_then(|r| r.into_iter().next().flatten())
.unwrap_or_default(),
};
Ok(CompletionModel { default_schema, tables, foreign_keys })
}
@@ -1498,13 +1712,26 @@ impl DbManager {
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
self.validate_console_script(id, statements, None).await
}
pub async fn validate_console_script(
&self,
id: &str,
statements: &[split::SqlStatement],
console: Option<ConsoleId<'_>>,
) -> IdeResult<()> {
if statements.len() > 1
&& self.source(id).is_ok_and(|s| s.driver == DbDriver::Postgres && s.read_only)
&& self.pool(id).await?.transaction_read_only()
{
for statement in statements {
if let Err(error) = conn::validate_pg_read_only(&statement.text) {
self.finish_transaction(id, false).await?;
if let Some(console) = console {
self.finish_postgres_console_transaction(id, console, false).await?;
} else {
self.finish_transaction(id, false).await?;
}
return Err(IdeError::invalid(error));
}
}
@@ -1525,7 +1752,22 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, skip, max_rows, cancel, schema).await;
self.execute_in_console(id, statement, skip, max_rows, cancel, schema, None).await
}
/// Executes in the originating editor's transaction or session when supported by the driver.
#[allow(clippy::too_many_arguments)]
pub async fn execute_in_console(
&self,
id: &str,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
let r = self.run(id, statement, skip, max_rows, cancel, schema, console).await;
let ran = match &r {
Ok(_) => true,
Err(e) => !matches!(e.kind, ErrorKind::Cancelled | ErrorKind::PermissionDenied),
@@ -1547,12 +1789,34 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, false).await
self.read_console_row(id, statement, row, cancel, schema, None).await
}
pub async fn read_console_row(
&self,
id: &str,
statement: &str,
row: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, console, false).await
}
/// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed).
pub fn release_result(&self, id: &str, statement: &str, schema: Option<&str>) {
self.cursors.release(&conn::CursorKey::new(id, statement, schema));
self.release_console_result(id, statement, schema, None);
}
pub fn release_console_result(
&self,
id: &str,
statement: &str,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) {
self.cursors.release(&conn::CursorKey::new(id, statement, schema).with_console(console));
}
fn remember_statement(&self, id: &str, statement: &str) {
@@ -1585,9 +1849,35 @@ impl DbManager {
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<Vec<PlanNode>> {
let driver = self.pool(id).await?.driver();
if driver == DbDriver::Jdbc {
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
self.explain_in_console(id, statement, cancel, schema, None).await
}
pub async fn explain_in_console(
&self,
id: &str,
statement: &str,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<Vec<PlanNode>> {
let pool = self.pool(id).await?;
let driver = pool.driver();
if let Pool::Jdbc(jdbc) = &*pool {
if self.source(id)?.vendor != "duckdb" || !jdbc.version.starts_with("DuckDB ") {
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
}
let sql = statement.trim().trim_end_matches(';');
if sql.contains(';') {
// The driver can execute a whole script. Have DuckDB count its statements before prefixing EXPLAIN.
let literal = sql::quote_literal(driver, sql);
let check = format!("SELECT json_array_length(json_serialize_plan({literal}), '$.plans')");
let result = self.run(id, &check, 0, 1, cancel, schema, console).await?;
if result.rows.first().and_then(|r| r.first()).and_then(Option::as_deref) != Some("1") {
return Err(IdeError::invalid("Choose one statement to explain"));
}
}
let result = self.run(id, &format!("EXPLAIN (FORMAT JSON) {sql}"), 0, 3, cancel, schema, console).await?;
return plan::duckdb(&result);
}
if driver == DbDriver::Oracle {
// EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately.
@@ -1606,18 +1896,21 @@ impl DbManager {
MAX_META_ROWS,
cancel,
schema,
None,
)
.await?;
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None).await?;
let result = self.run(id, &plan::oracle_plan_query(&plan_id), 0, MAX_META_ROWS, cancel, None, None).await?;
let nodes = plan::parse(driver, &result);
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None).await;
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
return nodes;
}
let result =
self.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema).await?;
let result = self
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
.await?;
plan::parse(driver, &result)
}
#[allow(clippy::too_many_arguments)]
async fn run(
&self,
id: &str,
@@ -1626,8 +1919,9 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
self.run_paged(id, statement, skip, max_rows, cancel, schema, console, true).await
}
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
@@ -1640,13 +1934,31 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
console: Option<ConsoleId<'_>>,
paging: bool,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
let connection = self.connection(id).await?;
let pool = connection.pool;
let expected_manual = console.and_then(|console| console.expected_manual);
if expected_manual.is_some() && !matches!(&*pool, Pool::Postgres(_)) {
return Err(postgres_console_mode_changed());
}
if let Pool::Jdbc(p) = &*pool {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
return p.query_in_console(statement, skip, max_rows, cancel, schema, console).await;
}
if let Pool::Clickhouse(p) = &*pool
&& console.is_some()
{
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
}
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
let session = match console {
Some(console) => connection.console_transactions.session(console),
None => self.sessions.lock().get(id).cloned(),
};
if expected_manual.is_some_and(|manual| manual != session.is_some()) {
return Err(postgres_console_mode_changed());
}
let session = self.sessions.lock().get(id).cloned();
let protected = pool.transaction_read_only();
let cursor = protected || conn::cursor_statement(statement);
if !cursor || (protected && skip == 0 && paging) {
@@ -1654,7 +1966,7 @@ impl DbManager {
self.cursors.release_target(id);
}
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
let key = conn::CursorKey::new(id, statement, schema);
let key = conn::CursorKey::new(id, statement, schema).with_console(console);
let started = std::time::Instant::now();
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
Some(page) => page,
@@ -1690,44 +2002,9 @@ impl DbManager {
if pool.driver() == DbDriver::Clickhouse {
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
}
let mut held = session.lock().await;
if pool.transaction_read_only() {
// Own the session during awaits so a dropped request cannot return an unfinished transaction.
let mut conn = match held.take() {
Some(conn) => conn,
None => {
let mut conn = Held::acquire(&pool).await?;
conn.begin_manual(pool.driver()).await?;
conn
}
};
let result = async {
conn.apply_context(schema).await?;
conn.execute_from(&pool, statement, skip, max_rows, cancel).await
}
.await;
if result.is_ok() {
*held = Some(conn);
} else if cancel.is_cancelled() || conn.finish_manual(false).await.is_err() {
conn.discard().await;
}
return result;
}
if held.is_none() {
let mut conn = Held::acquire(&pool).await?;
conn.apply_context(schema).await?;
conn.begin_manual(pool.driver()).await?;
*held = Some(conn);
}
let conn = held.as_mut().expect("opened above");
conn.apply_context(schema).await?;
let r = conn.execute_from(&pool, statement, skip, max_rows, cancel).await;
if cancel.is_cancelled() {
// The server rolls the transaction back with the connection.
held.take().expect("opened above").discard().await;
return Err(IdeError::cancelled());
}
r
session
.execute(&pool, &connection.console_transactions.capacity, statement, skip, max_rows, cancel, schema)
.await
}
/// Switches `id` between auto-commit and manual commit. Leaving manual
@@ -1760,23 +2037,37 @@ impl DbManager {
}
let session = self.sessions.lock().get(id).cloned();
let Some(session) = session else { return Ok(()) };
let mut held = session.lock().await;
let Some(mut conn) = held.take() else { return Ok(()) };
if let Err(e) = conn.finish_manual(commit).await {
// Discarding a Snowflake connection doesn't end its session, which the data source's
// other targets share: the transaction stays open, so it stays held to be ended again.
if matches!(conn, conn::Held::Snowflake(..)) {
*held = Some(conn);
} else {
conn.discard().await;
session.finish(commit).await
}
/// Changes manual-commit mode for one PostgreSQL console. Returns whether it opened a new mode entry.
pub async fn set_postgres_console_manual(&self, id: &str, console: ConsoleId<'_>, manual: bool) -> IdeResult<bool> {
if self.source(id)?.driver != DbDriver::Postgres {
return Err(IdeError::invalid("Scoped manual transactions require a PostgreSQL data source"));
}
if manual {
self.connection(id).await?.console_transactions.enable(console)
} else {
if let Some(connection) = self.opened_connection(id) {
connection.console_transactions.release(console).await?;
}
return Err(e);
Ok(false)
}
if let Err(e) = conn.restore_default().await {
conn.discard().await;
return Err(e);
}
/// Commits or rolls back work held by this PostgreSQL console.
pub async fn finish_postgres_console_transaction(
&self,
id: &str,
console: ConsoleId<'_>,
commit: bool,
) -> IdeResult<()> {
let session =
self.opened_connection(id).and_then(|connection| connection.console_transactions.session(console));
match session {
Some(session) => session.finish(commit).await,
None => Err(postgres_console_mode_changed()),
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
@@ -1791,18 +2082,54 @@ impl DbManager {
limit: u64,
cancel: &CancellationToken,
) -> IdeResult<TablePage> {
let details = self.table_details(id, schema, table).await?;
let pool = self.pool(id).await?;
let mut result = if let Pool::Jdbc(p) = &*pool {
Self::table_page_on(&pool, None, schema, table, filter, sort, offset, limit, cancel).await
}
#[allow(clippy::too_many_arguments)]
pub async fn catalog_table_page(
&self,
id: &str,
catalog: &str,
schema: &str,
table: &str,
filter: Option<&str>,
sort: &[SortKey],
offset: u64,
limit: u64,
cancel: &CancellationToken,
) -> IdeResult<TablePage> {
let pool = self.duckdb_catalog_pool(id).await?;
Self::table_page_on(&pool, Some(catalog), schema, table, filter, sort, offset, limit, cancel).await
}
#[allow(clippy::too_many_arguments)]
async fn table_page_on(
pool: &Pool,
catalog: Option<&str>,
schema: &str,
table: &str,
filter: Option<&str>,
sort: &[SortKey],
offset: u64,
limit: u64,
cancel: &CancellationToken,
) -> IdeResult<TablePage> {
let details = Self::table_details_on(pool, catalog, schema, table).await?;
let mut result = if let Pool::Jdbc(p) = pool {
let q = &p.identifier_quote;
let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str()));
let names =
catalog.into_iter().chain((catalog.is_some() || !schema.is_empty()).then_some(schema)).chain([table]);
if q.is_empty()
&& names.into_iter().any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
&& names
.clone()
.chain(sort.iter().map(|k| k.column.as_str()))
.any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
{
return Err(IdeError::invalid("This JDBC driver cannot quote the selected identifier"));
}
let quote = |s: &str| format!("{q}{}{q}", s.replace(q, &format!("{q}{q}")));
let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) };
let name = names.map(quote).collect::<Vec<_>>().join(".");
let sql = sql::table_select(&name, filter, sort, quote);
p.page(&sql, offset, limit, cancel).await?
} else {
+202
Переглянути файл
@@ -0,0 +1,202 @@
use crate::{ConsoleId, Held, Pool, QueryResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{Mutex as AsyncMutex, OwnedSemaphorePermit, Semaphore};
pub(super) type Session = Arc<ManualSession>;
type ConsoleKey = (String, String);
struct Transaction {
connection: Held,
_permit: Option<OwnedSemaphorePermit>,
}
impl Transaction {
async fn acquire(pool: &Pool, capacity: &Arc<Semaphore>) -> IdeResult<Self> {
let permit = if matches!(pool, Pool::Postgres(_)) {
Some(capacity.clone().try_acquire_owned().map_err(|_| {
IdeError::unavailable("PostgreSQL manual transactions are using the available slots. Commit or roll back an open transaction.")
})?)
} else {
None
};
Ok(Self { connection: Held::acquire(pool).await?, _permit: permit })
}
}
#[derive(Default)]
pub(super) struct ManualSession {
transaction: AsyncMutex<Option<Transaction>>,
retired: CancellationToken,
}
impl ManualSession {
#[allow(clippy::too_many_arguments)]
pub(super) async fn execute(
&self,
pool: &Pool,
capacity: &Arc<Semaphore>,
statement: &str,
skip: usize,
max_rows: usize,
request: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let cancel = self.retired.child_token();
let mut held = tokio::select! {
biased;
() = request.cancelled() => return Err(IdeError::cancelled()),
() = cancel.cancelled() => return Err(IdeError::cancelled()),
held = self.transaction.lock() => held,
};
let execute = async {
if pool.transaction_read_only() {
// Own the connection while applying the guard so a dropped call cannot return an open transaction.
let mut tx = match held.take() {
Some(tx) => tx,
None => {
let mut tx = Transaction::acquire(pool, capacity).await?;
tx.connection.begin_manual(pool.driver()).await?;
tx
}
};
let result = async {
tx.connection.apply_context(schema).await?;
tx.connection.execute_from(pool, statement, skip, max_rows, &cancel).await
}
.await;
if result.is_ok() {
*held = Some(tx);
} else if cancel.is_cancelled() || tx.connection.finish_manual(false).await.is_err() {
tx.connection.discard().await;
}
return result;
}
if held.is_none() {
let mut tx = Transaction::acquire(pool, capacity).await?;
tx.connection.apply_context(schema).await?;
tx.connection.begin_manual(pool.driver()).await?;
*held = Some(tx);
}
let conn = &mut held.as_mut().expect("opened above").connection;
conn.apply_context(schema).await?;
let result = conn.execute_from(pool, statement, skip, max_rows, &cancel).await;
if cancel.is_cancelled() {
held.take().expect("opened above").connection.discard().await;
return Err(IdeError::cancelled());
}
result
};
tokio::pin!(execute);
tokio::select! {
biased;
() = request.cancelled() => {
cancel.cancel();
execute.await
}
result = &mut execute => result,
}
}
pub(super) async fn finish(&self, commit: bool) -> IdeResult<()> {
let mut held = self.transaction.lock().await;
if commit && self.retired.is_cancelled() {
return Err(IdeError::cancelled());
}
let Some(mut tx) = held.take() else { return Ok(()) };
if let Err(error) = tx.connection.finish_manual(commit).await {
// Snowflake targets share the same server session, so keep the failed transaction to be ended again.
if matches!(tx.connection, Held::Snowflake(..)) {
*held = Some(tx);
} else {
tx.connection.discard().await;
}
return Err(error);
}
if let Err(error) = tx.connection.restore_default().await {
tx.connection.discard().await;
return Err(error);
}
Ok(())
}
pub(super) async fn rollback_and_release(&self) -> IdeResult<()> {
let transaction = self.transaction.lock().await.take();
let Some(mut tx) = transaction else { return Ok(()) };
if let Err(error) = tx.connection.finish_manual(false).await {
tx.connection.discard().await;
return Err(error);
}
if let Err(error) = tx.connection.restore_default().await {
tx.connection.discard().await;
return Err(error);
}
Ok(())
}
async fn retire(&self) -> IdeResult<()> {
self.retired.cancel();
self.rollback_and_release().await
}
}
pub(super) struct ConsoleTransactions {
sessions: Mutex<HashMap<ConsoleKey, Session>>,
closed: CancellationToken,
/// The four-slot pool also serves ordinary work and one retained result cursor.
pub(super) capacity: Arc<Semaphore>,
}
impl Default for ConsoleTransactions {
fn default() -> Self {
Self { sessions: Mutex::default(), closed: CancellationToken::new(), capacity: Arc::new(Semaphore::new(2)) }
}
}
fn key(console: ConsoleId<'_>) -> ConsoleKey {
(console.window.to_owned(), console.path.to_owned())
}
impl ConsoleTransactions {
pub(super) fn session(&self, console: ConsoleId<'_>) -> Option<Session> {
self.sessions.lock().get(&key(console)).cloned()
}
pub(super) fn enable(&self, console: ConsoleId<'_>) -> IdeResult<bool> {
let mut sessions = self.sessions.lock();
if self.closed.is_cancelled() {
return Err(IdeError::cancelled());
}
match sessions.entry(key(console)) {
std::collections::hash_map::Entry::Occupied(_) => Ok(false),
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert(Session::default());
Ok(true)
}
}
}
pub(super) async fn release(&self, console: ConsoleId<'_>) -> IdeResult<()> {
let session = self.sessions.lock().remove(&key(console));
if let Some(session) = session {
session.retire().await?;
}
Ok(())
}
pub(super) async fn close(&self) {
let sessions = {
let mut sessions = self.sessions.lock();
self.closed.cancel();
std::mem::take(&mut *sessions)
};
for session in sessions.values() {
session.retired.cancel();
}
for session in sessions.into_values() {
let _ = session.rollback_and_release().await;
}
}
}
+68 -12
Переглянути файл
@@ -90,6 +90,54 @@ fn prop(name: &str, value: impl Into<String>) -> PlanProperty {
PlanProperty { name: name.to_owned(), value: value.into() }
}
fn json_property(name: &str, value: &Value) -> PlanProperty {
let as_text = |v: &Value| v.as_str().map_or_else(|| v.to_string(), str::to_owned);
let text = match value {
Value::Array(items) => items.iter().map(as_text).collect::<Vec<_>>().join(", "),
other => as_text(other),
};
prop(name, text)
}
/// DuckDB's explain_output may request the physical plan, the optimized logical plan, or all three.
pub(crate) fn duckdb(result: &QueryResult) -> IdeResult<Vec<PlanNode>> {
#[derive(Deserialize)]
struct Operator {
name: String,
#[serde(default)]
children: Vec<Operator>,
#[serde(default)]
extra_info: serde_json::Map<String, Value>,
}
fn append(node: Operator, parent: Option<u32>, out: &mut Vec<PlanNode>) {
let index = out.len() as u32;
let properties = node.extra_info.iter().map(|(k, v)| json_property(k, v)).collect();
let params = ["Table", "Conditions", "Filters", "Projections"]
.iter()
.find_map(|key| node.extra_info.get(*key).map(|v| json_property(key, v).value))
.unwrap_or_default();
out.push(PlanNode { parent, operation: node.name.trim().to_owned(), params, properties });
for child in node.children {
append(child, Some(index), out);
}
}
let json = ["physical_plan", "logical_opt", "logical_plan"]
.iter()
.find_map(|kind| {
result.rows.iter().find(|r| r.first().and_then(Option::as_deref) == Some(*kind))?.get(1)?.as_deref()
})
.ok_or_else(|| IdeError::invalid("DuckDB returned no execution plan"))?;
let roots: Vec<Operator> =
serde_json::from_str(json).map_err(|e| IdeError::invalid(format!("DuckDB plan: {e}")))?;
let mut out = Vec::new();
for root in roots {
append(root, None, &mut out);
}
Ok(out)
}
/// SQLite rows: `id, parent, notused, detail` (`SCAN o`, `SEARCH c USING INTEGER PRIMARY KEY (rowid=?)`).
fn sqlite(rows: &[Vec<Option<String>>]) -> Vec<PlanNode> {
let mut ids: Vec<String> = Vec::new();
@@ -149,18 +197,7 @@ fn postgres(node: &Value, parent: Option<u32>, out: &mut Vec<PlanNode>) {
.into_iter()
.flatten()
.filter(|(k, _)| k.as_str() != "Plans")
.map(|(k, v)| {
let value = match v {
Value::String(s) => s.clone(),
Value::Array(a) => a
.iter()
.map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned))
.collect::<Vec<_>>()
.join(", "),
other => other.to_string(),
};
prop(k, value)
})
.map(|(k, v)| json_property(k, v))
.collect();
let me = out.len() as u32;
out.push(PlanNode { parent, operation, params: params.join(" "), properties });
@@ -287,6 +324,25 @@ mod tests {
}
}
#[test]
fn duckdb_prefers_the_physical_plan_and_preserves_operator_details() {
let physical = r#"[{"name":"PROJECTION","extra_info":{"Projections":["a","b"]},"children":[{"name":"SEQ_SCAN ","extra_info":{"Table":"items"}}]}]"#;
let rows = result(
&["explain_key", "explain_value"],
vec![vec![Some("logical_opt"), Some("[]")], vec![Some("physical_plan"), Some(physical)]],
);
let nodes = duckdb(&rows).unwrap();
assert_eq!(nodes.len(), 2);
assert_eq!((nodes[0].parent, nodes[0].params.as_str()), (None, "a, b"));
assert_eq!(
(nodes[1].parent, nodes[1].operation.as_str(), nodes[1].params.as_str()),
(Some(0), "SEQ_SCAN", "items")
);
assert_eq!(nodes[1].properties, [prop("Table", "items")]);
assert!(duckdb(&result(&[], vec![])).is_err());
assert!(duckdb(&result(&[], vec![vec![Some("physical_plan"), Some("invalid")]])).is_err());
}
#[test]
fn explains_per_dialect() {
assert_eq!(explain_statement(DbDriver::Sqlite, "select 1;"), "EXPLAIN QUERY PLAN select 1");
+38 -1
Переглянути файл
@@ -55,6 +55,7 @@ pub(super) type Routes = Mutex<HashMap<String, CachedRoute>>;
#[derive(Clone)]
pub(super) struct Connection {
pub(super) pool: Arc<Pool>,
pub(super) console_transactions: Arc<crate::manual_session::ConsoleTransactions>,
route: Option<RouteSlot>,
}
@@ -211,7 +212,7 @@ impl DbManager {
if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(Connection { pool, route })
Ok(Connection { pool, route, console_transactions: Default::default() })
}
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
@@ -223,10 +224,46 @@ impl DbManager {
}
self.cursors.release_target(id);
if let Some(c) = slot.value.get() {
c.console_transactions.close().await;
c.pool.close().await;
}
}
pub(super) fn opened_connection(&self, id: &str) -> Option<Connection> {
self.pools.lock().get(id).and_then(|slot| slot.value.get()).cloned()
}
/// Retires a closed editor's sessions without opening any data sources.
pub async fn release_console(&self, console: crate::ConsoleId<'_>) -> IdeResult<()> {
self.release_target_console(console, None).await
}
pub async fn release_target_console(&self, console: crate::ConsoleId<'_>, target: Option<&str>) -> IdeResult<()> {
self.cursors.release_console(console, target);
let connections: Vec<_> = self
.pools
.lock()
.iter()
.filter(|(id, _)| target.is_none_or(|target| id.as_str() == target))
.filter_map(|(_, slot)| slot.value.get().cloned())
.collect();
let mut result = Ok(());
for connection in connections {
let released = match &*connection.pool {
Pool::Clickhouse(pool) => {
pool.release_console(console);
Ok(())
}
Pool::Jdbc(pool) => pool.release_console(console).await,
_ => connection.console_transactions.release(console).await,
};
if let Err(error) = released {
result = Err(error);
}
}
result
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
+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();
+59 -1
Переглянути файл
@@ -26,6 +26,49 @@ enum State {
BlockComment,
}
// Starts just after the opening `/*`. ClickHouse supports nested block comments.
fn after_clickhouse_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
while let Some(at) = text.find(['/', '*']) {
text = &text[at..];
if let Some(rest) = text.strip_prefix("/*") {
text = rest;
depth += 1;
} else if let Some(rest) = text.strip_prefix("*/") {
text = rest;
depth -= 1;
if depth == 0 {
return text;
}
} else {
text = &text[1..];
}
}
""
}
/// Consume an unquoted leading word, leaving quoted identifiers and SQL literals alone.
pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
let mut text = *sql;
loop {
text = text.trim_start_matches(|ch: char| ch.is_whitespace() || ch == '\u{feff}');
if let Some(comment) = text.strip_prefix('#').or_else(|| text.strip_prefix("--")) {
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
} else if let Some(comment) = text.strip_prefix("/*") {
text = after_clickhouse_block_comment(comment);
} else {
break;
}
}
let end = text.find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_').unwrap_or(text.len());
if end == 0 {
return None;
}
let (keyword, rest) = text.split_at(end);
*sql = rest;
Some(keyword)
}
/// Every statement of `text` that contains more than whitespace and comments.
pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
let mysql = driver == DbDriver::Mysql;
@@ -134,6 +177,12 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
has_code = true;
}
'/' if next == Some('*') => {
if clickhouse {
let rest = after_clickhouse_block_comment(&text[byte_at(i + 2)..]);
let end = text.len() - rest.len();
i = chars.partition_point(|&(offset, _)| offset < end);
continue;
}
state = State::BlockComment;
i += 1;
}
@@ -154,7 +203,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
state = State::LineComment;
i += 1;
}
'#' if mysql => state = State::LineComment,
'#' if mysql || clickhouse => state = State::LineComment,
// The `//` of `file://…` (PUT, GET) or another URL is not a comment.
'/' if snowflake && next == Some('/') && chars[..i].last().is_some_and(|&(_, c)| c == ':') => {
has_code = true;
@@ -416,6 +465,15 @@ fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
mod tests {
use super::*;
#[test]
fn clickhouse_session_settings_split_after_comments_and_quoted_values() {
let set = "# leading ;\n/* outer /* nested ; */ tail ; */ SET log_comment='a;b', max_threads=1";
let query = "SELECT getSetting('log_comment')";
let script = format!("{set}; {query};");
let statements: Vec<_> = split(&script, DbDriver::Clickhouse).into_iter().map(|item| item.text).collect();
assert_eq!(statements, [set, query]);
}
fn texts(sql: &str, d: DbDriver) -> Vec<String> {
split(sql, d).into_iter().map(|s| s.text).collect()
}
+318 -78
Переглянути файл
@@ -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,7 +214,30 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
/// 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, key` (one row per indexed column, in order); `key` is
/// `p` for the primary key's index, `u` for a unique constraint's, NULL otherwise (ClickHouse: absent).
// 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
// table's rows through the catalog's index first.
@@ -219,11 +252,14 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
WHERE database = {s} AND table = {t}) ORDER BY index_name"
),
DbDriver::Sqlite => format!(
"SELECT il.name, il.\"unique\", ii.name FROM pragma_index_list({t}, {s}) il \
"SELECT il.name, il.\"unique\", ii.name, CASE il.origin WHEN 'pk' THEN 'p' WHEN 'u' THEN 'u' END \
FROM pragma_index_list({t}, {s}) il \
JOIN pragma_index_info(il.name, {s}) ii ORDER BY il.name, ii.seqno"
),
DbDriver::Postgres => format!(
"SELECT i.relname, CASE WHEN ix.indisunique THEN 1 ELSE 0 END, a.attname \
"SELECT i.relname, CASE WHEN ix.indisunique THEN 1 ELSE 0 END, a.attname, \
CASE WHEN ix.indisprimary THEN 'p' WHEN EXISTS (SELECT 1 FROM pg_constraint con \
WHERE con.conindid = ix.indexrelid AND con.conrelid = ix.indrelid AND con.contype = 'u') THEN 'u' END \
FROM pg_index ix JOIN pg_class t ON t.oid = ix.indrelid JOIN pg_class i ON i.oid = ix.indexrelid \
JOIN pg_namespace n ON n.oid = t.relnamespace \
JOIN generate_series(0, current_setting('max_index_keys')::int - 1) AS k(ord) ON k.ord < ix.indnatts \
@@ -231,12 +267,14 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
WHERE n.nspname = {s} AND t.relname = {t} ORDER BY i.relname, k.ord"
),
DbDriver::Mysql => format!(
"SELECT index_name, CASE WHEN non_unique = 0 THEN 1 ELSE 0 END, column_name \
"SELECT index_name, CASE WHEN non_unique = 0 THEN 1 ELSE 0 END, column_name, \
CASE WHEN index_name = 'PRIMARY' THEN 'p' WHEN non_unique = 0 THEN 'u' END \
FROM information_schema.statistics WHERE table_schema = {s} AND table_name = {t} \
ORDER BY index_name, seq_in_index"
),
DbDriver::SqlServer => format!(
"SELECT i.name, CASE WHEN i.is_unique = 1 THEN 1 ELSE 0 END, c.name \
"SELECT i.name, CASE WHEN i.is_unique = 1 THEN 1 ELSE 0 END, c.name, \
CASE WHEN i.is_primary_key = 1 THEN 'p' WHEN i.is_unique_constraint = 1 THEN 'u' END \
FROM sys.indexes i JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id \
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id \
WHERE OBJECT_SCHEMA_NAME(i.object_id) = {s} AND OBJECT_NAME(i.object_id) = {t} AND i.name IS NOT NULL \
@@ -244,7 +282,9 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
),
DbDriver::Snowflake => "SELECT '', 0, '' WHERE 1 = 0".to_owned(),
DbDriver::Oracle => format!(
"SELECT i.index_name, CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END, ic.column_name \
"SELECT i.index_name, CASE WHEN i.uniqueness = 'UNIQUE' THEN 1 ELSE 0 END, ic.column_name, \
(SELECT MIN(LOWER(con.constraint_type)) FROM all_constraints con WHERE con.owner = i.table_owner \
AND con.table_name = i.table_name AND con.index_name = i.index_name AND con.constraint_type IN ('P', 'U')) \
FROM all_indexes i JOIN all_ind_columns ic \
ON ic.index_owner = i.owner AND ic.index_name = i.index_name \
WHERE i.owner = {s} AND i.table_name = {t} ORDER BY i.index_name, ic.column_position"
@@ -252,54 +292,72 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// Which schemas a [`completion_columns`] query reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionScope<'a> {
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
All,
/// One schema, in full.
Only(&'a str),
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
Except(&'a str),
}
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
pub const COMPLETION_ROW_CAP: usize = 50_000;
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
/// for SQL completion, grouped by table in column order.
pub fn completion_columns(driver: DbDriver) -> &'static str {
match driver {
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
let (query, schema, order) = match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => {
DbDriver::Clickhouse => (
"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 \
ORDER BY c.database, c.table, c.position LIMIT 50000"
}
DbDriver::Sqlite => {
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
"c.database",
"c.database, c.table, c.position",
),
DbDriver::Sqlite => (
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
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 '\\' ORDER BY m.name, p.cid"
}
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
DbDriver::Postgres => {
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
"'main'",
"m.name, p.cid",
),
DbDriver::Postgres => (
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
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') \
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
}
DbDriver::Mysql => {
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
"n.nspname",
"n.nspname, c.relname, a.attnum",
),
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') \
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::SqlServer => {
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
"c.table_schema",
"c.table_schema, c.table_name, c.ordinal_position",
),
DbDriver::SqlServer => (
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
@@ -307,37 +365,53 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
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') \
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
}
DbDriver::Snowflake => {
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
"c.TABLE_SCHEMA",
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
),
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' \
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
}
DbDriver::Oracle => {
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
"c.table_schema",
"c.table_schema, c.table_name, c.ordinal_position",
),
DbDriver::Oracle => (
"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 \
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
}
}
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
"c.owner",
"c.owner, c.table_name, c.column_id",
),
};
let filter = match scope {
CompletionScope::All => String::new(),
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
};
let cap = match (scope, driver) {
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
};
format!("{query}{filter} ORDER BY {order}{cap}")
}
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
@@ -600,21 +674,22 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind` of a PostgreSQL relation.
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
pub fn postgres_relation(schema: &str, name: &str) -> String {
format!(
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
pub fn postgres_ddl_columns(oid: u32) -> String {
format!(
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
)
@@ -637,6 +712,27 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
)
}
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
/// changed (`relacl` null) grants none.
pub fn postgres_ddl_grants(oid: u32) -> String {
format!(
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
)
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32) -> String {
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
ORDER BY tgname"
)
}
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
@@ -876,6 +972,18 @@ pub struct DdlColumn {
pub data_type: String,
pub not_null: bool,
pub default: Option<String>,
pub comment: Option<String>,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
pub comment: Option<String>,
pub owner: Option<String>,
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
pub grants: Vec<(String, String, bool)>,
/// `CREATE TRIGGER …` statements.
pub triggers: Vec<String>,
}
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
@@ -885,6 +993,7 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let mut items: Vec<String> = columns
@@ -901,9 +1010,31 @@ pub fn postgres_table_ddl(
})
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
for i in indexes {
out.push_str(&format!("\n{i};\n"));
let target = qualified(d, schema, table);
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
if let Some(comment) = &extras.comment {
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
}
for c in columns {
if let Some(comment) = &c.comment {
let column = format!("{target}.{}", quote_ident(d, &c.name));
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
}
}
if let Some(owner) = &extras.owner {
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
}
if !extras.grants.is_empty() {
out.push('\n');
}
for (grantee, privileges, grantable) in &extras.grants {
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
let option = if *grantable { " with grant option" } else { "" };
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
}
for statement in indexes.iter().chain(&extras.triggers) {
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
}
out
}
@@ -924,6 +1055,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;
@@ -941,6 +1106,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(')"));
@@ -950,7 +1116,7 @@ mod tests {
let keys = indexes(driver, "default", "events");
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
let completion = completion_columns(driver);
let completion = completion_columns(driver, CompletionScope::All);
assert!(completion.contains("c.is_in_primary_key, 1"));
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
}
@@ -1056,11 +1222,12 @@ 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"));
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
}
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
@@ -1074,7 +1241,7 @@ mod tests {
tables(d, "dbo"),
columns(d, "dbo", "t"),
indexes(d, "dbo", "t"),
completion_columns(d).to_owned(),
completion_columns(d, CompletionScope::All),
foreign_keys(d).to_owned(),
table_foreign_keys(d, "dbo", "t"),
routines(d, "dbo").unwrap(),
@@ -1132,8 +1299,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')"));
@@ -1141,7 +1310,7 @@ mod tests {
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
@@ -1222,12 +1391,13 @@ mod tests {
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "name".into(),
data_type: "character varying(40)".into(),
not_null: false,
default: Some("'x'::character varying".into()),
comment: None,
},
];
assert_eq!(
@@ -1236,12 +1406,53 @@ mod tests {
"t",
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlExtras::default(),
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
);
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "note".into(),
data_type: "text".into(),
not_null: false,
default: None,
comment: Some("what's this".into()),
},
];
let extras = DdlExtras {
comment: Some("Orders".into()),
owner: Some("app owner".into()),
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
triggers: vec![
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
],
};
assert_eq!(
postgres_table_ddl(
"public",
"t",
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
\ncomment on table \"public\".\"t\" is 'Orders';\n\
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
\ngrant select on \"public\".\"t\" to public;\n\
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
);
}
#[test]
fn snowflake_quotes_names_and_reads_its_information_schema() {
let driver = DbDriver::Snowflake;
@@ -1256,7 +1467,7 @@ mod tests {
let columns = columns(driver, "PUBLIC", "ORDERS");
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
assert!(completion_columns(driver).contains("LIMIT 50000"));
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
assert_eq!(
@@ -1268,6 +1479,35 @@ mod tests {
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
}
#[test]
fn completion_reads_the_default_schema_without_the_shared_cap() {
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
// sorting last had no columns.
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
for (driver, column) in [
(DbDriver::Postgres, "n.nspname"),
(DbDriver::Mysql, "c.table_schema"),
(DbDriver::Clickhouse, "c.database"),
(DbDriver::Snowflake, "c.table_schema"),
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
(DbDriver::Sqlite, "'main'"),
] {
let only = completion_columns(driver, CompletionScope::Only("app"));
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
let rest = completion_columns(driver, CompletionScope::Except("app"));
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
}
}
#[test]
fn postgres_catalog_queries_run_on_older_servers() {
let pg = DbDriver::Postgres;
@@ -1279,7 +1519,7 @@ mod tests {
tables(pg, "s"),
columns(pg, "s", "t"),
indexes(pg, "s", "t"),
completion_columns(pg).to_owned(),
completion_columns(pg, CompletionScope::All),
foreign_keys(pg).to_owned(),
table_foreign_keys(pg, "s", "t"),
triggers(pg, "s", "t"),
@@ -1290,7 +1530,7 @@ mod tests {
let upper = q.to_uppercase();
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
}
assert_eq!(postgres_legacy(completion_columns(pg)), None);
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
+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");
+91 -1
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, DbSslMode, SortKey, sql};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -134,3 +134,93 @@ async fn clickhouse_cloud_manager_catalogs_and_session_table() -> IdeResult<()>
cleanup?;
Ok(())
}
#[tokio::test]
#[ignore = "requires a disposable loopback ClickHouse console fixture"]
async fn clickhouse_named_console_sessions_run_concurrently_and_preserve_state() -> IdeResult<()> {
use std::time::Duration;
let port = std::env::var("CLICKHOUSE_CONSOLE_TEST_PORT")
.expect("set the disposable loopback console fixture's port")
.parse()
.expect("numeric console fixture port");
let password = std::env::var("CLICKHOUSE_CONSOLE_TEST_PASSWORD").expect("set the console fixture password");
let tmp = tempfile::tempdir()?;
let root = tmp.path().to_path_buf();
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
let source = DataSource {
id: "clickhouse".into(),
name: "ClickHouse console fixture".into(),
driver: DbDriver::Clickhouse,
host: "127.0.0.1".into(),
port: Some(port),
user: "console_fixture".into(),
database: "default".into(),
..Default::default()
};
let observer = DataSource { id: "observer".into(), ..source.clone() };
db.save_sources(vec![source, observer]).await?;
for id in ["clickhouse", "observer"] {
db.set_password(id, Some(password.clone()), false).await?;
db.execute(id, "SELECT 1", 1, &CancellationToken::new()).await?;
}
let a = ConsoleId::new("window-a", "/console.sql");
let b = ConsoleId::new("window-a", "/console_1.sql");
let other_window = ConsoleId::new("window-b", "/console.sql");
let idle = CancellationToken::new();
let run = |console, sql, cancel| db.execute_in_console("clickhouse", sql, 0, 1, cancel, None, Some(console));
run(b, "SELECT 1", &idle).await?;
run(a, "SET max_threads = 2", &idle).await?;
run(a, "CREATE TEMPORARY TABLE console_state (id UInt8)", &idle).await?;
run(a, "INSERT INTO console_state VALUES (17)", &idle).await?;
let cancel = CancellationToken::new();
let long_sql = "SELECT sum(sleepEachRow(1)) FROM numbers(12) SETTINGS max_block_size=1";
let running = run(a, long_sql, &cancel);
let other = async {
let checked = tokio::time::timeout(Duration::from_secs(4), async {
loop {
let observed = db
.execute(
"observer",
"SELECT count() FROM system.processes WHERE startsWith(query, 'SELECT sum(sleepEachRow(1))')",
1,
&idle,
)
.await?;
if observed.rows[0][0].as_deref() == Some("1") {
break;
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
run(b, "SELECT 2", &idle).await
})
.await;
cancel.cancel();
checked.map_err(|_| IdeError::invalid("console B did not complete while console A was active"))?
};
let (cancelled, other) = tokio::time::timeout(Duration::from_secs(17), async { tokio::join!(running, other) })
.await
.expect("console queries and cancellation should drain");
assert_eq!(other?.rows, vec![vec![Some("2".into())]]);
assert_eq!(cancelled.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
let first = run(a, "SELECT getSetting('max_threads'), id FROM console_state", &idle).await?;
assert_eq!(first.rows, vec![vec![Some("2".into()), Some("17".into())]]);
for console in [b, other_window] {
let second = run(console, "SELECT id FROM console_state", &idle).await;
assert!(second.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
}
run(b, "CREATE TEMPORARY TABLE console_state (id UInt8)", &idle).await?;
db.release_console(a).await?;
let reopened = run(a, "SELECT id FROM console_state", &idle).await;
assert!(reopened.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
assert!(run(b, "SELECT id FROM console_state", &idle).await?.rows.is_empty());
db.disconnect_source("clickhouse").await;
let reset = run(b, "SELECT id FROM console_state", &idle).await;
assert!(reset.is_err_and(|error| error.message.contains("UNKNOWN_TABLE")));
Ok(())
}
+386 -9
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey};
use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
use std::{path::Path, sync::Arc};
fn manager(dir: &Path) -> DbManager {
@@ -89,21 +89,25 @@ async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_ty
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
fn register_duckdb(db: &DbManager, vendor: Option<&str>) -> IdeResult<()> {
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]);
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: None,
vendor: vendor.map(str::to_owned),
jars: vec![jar],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})?;
})
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, None)?;
let source = DataSource {
id: "test".into(),
name: "DuckDB".into(),
@@ -118,9 +122,12 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
let db = manager(tmp.path());
let c = CancellationToken::new();
db.execute("test", "create table items(id int primary key, label varchar)", 1, &c).await?;
db.execute("test", "comment on table items is 'Local items'", 1, &c).await?;
db.execute("test", "insert into items values (1, NULL), (2, 'row')", 1, &c).await?;
assert!(db.schemas("test").await?.iter().any(|v| v == "main"));
assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "items"));
let tables = db.tables("test", "main").await?;
let items = tables.iter().find(|table| table.name == "items").expect("items");
assert_eq!(items.comment.as_deref(), Some("Local items"));
let details = db.table_details("test", "main", "items").await?;
assert_eq!(details.columns.len(), 2);
let result = db.execute("test", "select id, label from items order by id", 1, &c).await?;
@@ -150,6 +157,40 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
assert!(!last.has_more);
let past = db.table_page("test", "main", "items", None, &sort, 2, 1, &c).await?.result;
assert!(past.rows.is_empty() && !past.has_more);
let path = tmp.path().join("attachment.duckdb");
let path = ide_db::sql::quote_literal(DbDriver::Jdbc, &path.to_string_lossy());
let catalog = "archive.db:'1";
let quoted = ide_db::sql::quote_ident(DbDriver::Jdbc, catalog);
for statement in [
format!("ATTACH {path} AS {quoted}"),
format!("CREATE SCHEMA {quoted}.empty"),
format!("CREATE TABLE {quoted}.main.items(remote_only INTEGER)"),
format!("COMMENT ON TABLE {quoted}.main.items IS 'Archived items'"),
format!("CREATE VIEW {quoted}.main.remote_view AS SELECT * FROM {quoted}.main.items"),
format!("COMMENT ON VIEW {quoted}.main.remote_view IS 'Archived view'"),
] {
db.execute("test", &statement, 1, &c).await?;
}
let databases = db.databases("test").await?;
assert_eq!(databases.current, "local");
assert!(databases.names.iter().any(|name| name == catalog));
let schemas = db.database_catalog("test", catalog).await?;
assert!(schemas.iter().any(|schema| schema.name == "empty" && schema.tables.is_empty()));
let main = schemas.iter().find(|schema| schema.name == "main").expect("main");
assert_eq!(
main.tables.iter().map(|table| (table.name.as_str(), table.kind, table.comment.as_deref())).collect::<Vec<_>>(),
[
("items", ide_db::DbTableKind::Table, Some("Archived items")),
("remote_view", ide_db::DbTableKind::View, Some("Archived view")),
]
);
assert!(db.saved_catalog("test").await?.is_none());
db.execute("test", &format!("USE {quoted}"), 1, &c).await?;
assert_eq!(db.databases("test").await?.current, catalog);
db.execute("test", "USE local", 1, &c).await?;
db.execute("test", &format!("DETACH {quoted}"), 1, &c).await?;
assert!(!db.databases("test").await?.names.iter().any(|name| name == catalog));
assert!(db.database_catalog("test", catalog).await?.is_empty());
db.disconnect("test").await;
let reopened = manager(tmp.path());
assert_eq!(reopened.execute("test", "select count(*) from items", 1, &c).await?.rows, [vec![Some("2".into())]]);
@@ -157,6 +198,276 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
let file = tmp.path().join("example.duckdb");
let mut source = DataSource {
id: "test".into(),
name: "DuckDB".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: format!("jdbc:duckdb:{}", file.display()),
file: Some(file.clone().into()),
read_only: true,
..Default::default()
};
let cancel = CancellationToken::new();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
assert!(!file.exists());
source.read_only = false;
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table items (id int)", 1, &cancel).await?;
db.execute("test", "insert into items values (1)", 1, &cancel).await?;
db.disconnect("test").await;
source.read_only = true;
let reopened = manager(tmp.path());
assert!(reopened.test(&source, None, None).await?.to_lowercase().contains("duckdb"));
let mut conflicting = source.clone();
for options in ["; access_mode = READ_WRITE", "; duckdb.read_only = false"] {
conflicting.url = format!("{}{options}", source.url);
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
}
conflicting.url = source.url.clone();
conflicting.properties.push(DbProperty { name: "ACCESS_MODE".into(), value: "READ_WRITE".into() });
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
reopened.save_sources(vec![source.clone()]).await?;
assert_eq!(reopened.source("test")?.vendor, "duckdb");
assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]);
for console in [None, Some(ConsoleId::new("window", "/reader.sql"))] {
for query in ["insert into items values (2)", "create table added (id int)"] {
let err = reopened.execute_in_console("test", query, 0, 1, &cancel, None, console).await.unwrap_err();
assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message);
}
}
assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added"));
reopened.disconnect("test").await;
source.read_only = false;
reopened.save_sources(vec![source]).await?;
reopened.execute("test", "insert into items values (2)", 1, &cancel).await?;
assert_eq!(
reopened.execute("test", "select count(*) from items", 1, &cancel).await?.rows,
[vec![Some("2".into())]]
);
reopened.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
let mut source = DataSource {
id: "test".into(),
name: "DuckDB (memory)".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
};
let cancel = CancellationToken::new();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
source.read_only = true;
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
source.url = url.into();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
}
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_named_catalog_page_uses_the_source_session_and_exact_names() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "DuckDB".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
}])
.await?;
let stop = CancellationToken::new();
let file = tmp.path().join("attachment.duckdb");
let file = ide_db::sql::quote_literal(DbDriver::Jdbc, &file.to_string_lossy());
let catalog = r#"archive.db:with/"quote"#;
let schema = "some.schema_%";
let table = r#"same."table"#;
let quote = |name: &str| ide_db::sql::quote_ident(DbDriver::Jdbc, name);
let base_table = format!("memory.{}.{}", quote(schema), quote(table));
let attached_table = format!("{}.{}.{}", quote(catalog), quote(schema), quote(table));
db.execute_in_console(
"test",
&format!("ATTACH {file} AS {}", quote(catalog)),
0,
1,
&stop,
None,
Some(ConsoleId::new("window", "/attach.sql")),
)
.await?;
for statement in [
"SET threads = 1".into(),
format!("CREATE SCHEMA memory.{}", quote(schema)),
format!("CREATE SCHEMA {}.{}", quote(catalog), quote(schema)),
format!("CREATE TABLE {base_table} (base_only INTEGER PRIMARY KEY)"),
format!("CREATE TABLE {attached_table} (attached_only INTEGER PRIMARY KEY)"),
format!("INSERT INTO {base_table} VALUES (3)"),
format!("INSERT INTO {attached_table} VALUES (42), (41)"),
] {
db.execute("test", &statement, 1, &stop).await?;
}
let details = db.catalog_table_details("test", catalog, schema, table).await?;
assert_eq!(details.columns.len(), 1);
assert_eq!(details.columns[0].name, "attached_only");
assert!(details.columns[0].primary_key);
let sort = [SortKey { column: "attached_only".into(), descending: true }];
let attached = db.catalog_table_page("test", catalog, schema, table, None, &sort, 0, 1, &stop).await?;
assert_eq!(attached.result.rows, [vec![Some("42".into())]]);
assert!(attached.result.has_more);
assert_eq!(db.connected(), ["test"]);
db.execute("test", &format!("USE {}.{}", quote(catalog), quote(schema)), 1, &stop).await?;
let initial = db.catalog_table_page("test", "memory", schema, table, None, &[], 0, 1, &stop).await?;
assert_eq!(initial.result.rows, [vec![Some("3".into())]]);
assert_eq!(initial.details.columns[0].name, "base_only");
assert_eq!(db.databases("test").await?.current, catalog);
db.execute("test", "USE memory", 1, &stop).await?;
db.execute("test", &format!("DETACH {}", quote(catalog)), 1, &stop).await?;
assert!(db.catalog_table_page("test", catalog, schema, table, None, &[], 0, 1, &stop).await.is_err());
assert_eq!(db.connected(), ["test"]);
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_consoles_share_catalog_but_isolate_transactions_and_temporary_tables() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "DuckDB in memory".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
let a = ConsoleId::new("first", "/console.sql");
let b = ConsoleId::new("second", "/console.sql");
let run = |console, sql: &'static str| db.execute_in_console("test", sql, 0, 10, &cancel, None, Some(console));
db.execute("test", "CREATE TABLE durable (id INTEGER)", 1, &cancel).await?;
run(a, "CREATE TEMP TABLE local_only AS SELECT 7 AS id").await?;
assert!(run(b, "SELECT id FROM local_only").await.is_err(), "B must not see A's temporary table");
run(b, "CREATE TEMP TABLE local_only AS SELECT 9 AS id").await?;
assert_eq!(run(a, "SELECT id FROM local_only").await?.rows, [vec![Some("7".into())]]);
run(a, "BEGIN TRANSACTION").await?;
run(a, "INSERT INTO durable VALUES (1)").await?;
assert_eq!(run(a, "SELECT id FROM durable").await?.rows, [vec![Some("1".into())]]);
assert!(run(b, "SELECT id FROM durable").await?.rows.is_empty());
db.release_target_console(a, Some("test")).await?;
assert_eq!(run(b, "SELECT id FROM local_only").await?.rows, [vec![Some("9".into())]]);
assert!(run(a, "SELECT id FROM local_only").await.is_err(), "a reopened console starts a fresh session");
assert!(run(a, "SELECT id FROM durable").await?.rows.is_empty(), "closing A rolls back its transaction");
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires SQLITE_JDBC_CLASSPATH, H2_JDBC_JAR and a local Java 17+ runtime"]
async fn anonymous_jdbc_databases_stay_shared_across_consoles() -> IdeResult<()> {
let sqlite = std::env::split_paths(&std::env::var_os("SQLITE_JDBC_CLASSPATH").expect("SQLITE_JDBC_CLASSPATH"))
.map(|p| p.display().to_string())
.collect();
let h2 = vec![std::env::var("H2_JDBC_JAR").expect("H2_JDBC_JAR")];
for (class_name, jars, url) in
[("org.sqlite.JDBC", sqlite, "jdbc:sqlite::memory:"), ("org.h2.Driver", h2, "jdbc:h2:mem:;DB_CLOSE_DELAY=-1")]
{
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "private".into(),
class_name: class_name.into(),
name: class_name.into(),
vendor: None,
jars,
url_template: String::new(),
})?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "Anonymous memory".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "private".into(),
url: url.into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
let a = ConsoleId::new("window", "/a.sql");
let b = ConsoleId::new("window", "/b.sql");
let run = |console, sql: &'static str| db.execute_in_console("test", sql, 0, 1, &cancel, None, Some(console));
db.execute("test", "CREATE TABLE preserved (id INTEGER)", 1, &cancel).await?;
run(a, "INSERT INTO preserved VALUES (1)").await?;
db.release_target_console(a, Some("test")).await?;
assert_eq!(run(b, "SELECT id FROM preserved").await?.rows, [vec![Some("1".into())]]);
db.disconnect("test").await;
}
Ok(())
}
#[tokio::test]
#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"]
async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
@@ -261,6 +572,72 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn unresponsive_console_cancellation_keeps_other_jdbc_connections() -> IdeResult<()> {
use std::time::Duration;
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let started = tmp.path().join("started");
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
vendor: None,
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
db.save_sources(vec![DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: format!("jdbc:fixture:{}", started.display()),
..Default::default()
}])
.await?;
let a = ConsoleId::new("window", "/a.sql");
let b = ConsoleId::new("window", "/b.sql");
let stop = CancellationToken::new();
let normal = CancellationToken::new();
let (ran_a, sibling) = tokio::time::timeout(Duration::from_secs(15), async {
tokio::join!(db.execute_in_console("test", "ignore cancel", 0, 1, &stop, None, Some(a)), async {
while !started.is_file() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let sibling = tokio::time::timeout(Duration::from_secs(2), async {
let b = db.execute_in_console("test", "from B", 0, 1, &normal, None, Some(b)).await?;
let service = db.execute("test", "service", 1, &normal).await?;
Ok::<_, ide_core::IdeError>((b.affected, service.affected))
})
.await;
stop.cancel();
sibling
})
})
.await
.expect("cancellation must remain bounded");
assert_eq!(sibling.expect("B and service can finish while A is executing")?, (Some(1.0), Some(1.0)));
assert!(ran_a.unwrap_err().message.contains("Cancellation timed out"));
assert_eq!(db.connected(), ["test"]);
// The fixture's update count is cumulative within a physical connection.
assert_eq!(db.execute_in_console("test", "still B", 0, 1, &normal, None, Some(b)).await?.affected, Some(2.0));
assert_eq!(db.execute_in_console("test", "new session A", 0, 1, &normal, None, Some(a)).await?.affected, Some(1.0));
assert!(db.execute("test", "drop", 1, &normal).await.unwrap_err().message.contains("connection reset"));
assert!(db.is_connected("test"), "a lost service connection must not retire the console sessions");
assert_eq!(
db.execute_in_console("test", "B after service failure", 0, 1, &normal, None, Some(b)).await?.affected,
Some(3.0)
);
db.release_target_console(a, Some("test")).await?;
db.release_target_console(b, Some("test")).await?;
assert!(!db.is_connected("test"), "the failed service pool can be re-established after the last console");
assert_eq!(db.execute("test", "new service session", 1, &normal).await?.affected, Some(1.0));
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
+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 `用户`"));
}
+122
Переглянути файл
@@ -0,0 +1,122 @@
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
use ide_db::{ConsoleId, DataSource, DbDriver, DbManager, QueryResult};
use std::sync::Arc;
use std::time::Duration;
const TARGET: &str = "fixture";
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
const C: ConsoleId<'static> = ConsoleId::new("other", "a.sql");
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str, token: &CancellationToken) -> IdeResult<QueryResult> {
db.execute_in_console(TARGET, sql, 0, 10, token, Some("public"), Some(console)).await
}
#[tokio::test]
#[ignore = "requires a disposable local PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT and console_fixture db/user"]
async fn console_transactions_have_independent_commit_stop_and_release() -> IdeResult<()> {
let dir = tempfile::tempdir()?;
let root = dir.path();
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: TARGET.into(),
name: "Local PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "127.0.0.1".into(),
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").expect("disposable fixture port").parse().unwrap()),
user: "console_fixture".into(),
database: "console_fixture".into(),
..Default::default()
}])
.await?;
let cancel = CancellationToken::new();
let observer = db.pool(TARGET).await?;
db.execute(TARGET, "CREATE TABLE public.console_tx (id int PRIMARY KEY)", 0, &cancel).await?;
for console in [A, B, C] {
assert!(db.set_postgres_console_manual(TARGET, console, true).await?);
assert!(!db.set_postgres_console_manual(TARGET, console, true).await?);
}
run(&db, A, "INSERT INTO public.console_tx VALUES (1)", &cancel).await?;
let status = "SELECT pg_backend_pid(), txid_current(), count(*) FROM public.console_tx";
let a = run(&db, A, status, &cancel).await?.rows;
let b = run(&db, B, status, &cancel).await?.rows;
assert_ne!(a[0][0], b[0][0]);
assert_ne!(a[0][1], b[0][1]);
assert_eq!(a[0][2].as_deref(), Some("1"));
assert_eq!(b[0][2].as_deref(), Some("0"));
let error = run(&db, C, "SELECT 1", &cancel).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::Unavailable);
assert!(error.message.contains("Commit or roll back"));
let rows = "SELECT id FROM public.console_tx ORDER BY id";
assert!(observer.rows(rows, 10).await?.is_empty());
run(&db, B, "INSERT INTO public.console_tx VALUES (2)", &cancel).await?;
db.finish_postgres_console_transaction(TARGET, B, true).await?;
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())]]);
db.release_target_console(A, Some("other-target")).await?;
let retained =
db.read_console_row(TARGET, rows, 0, &cancel, Some("public"), Some(A.expecting_manual(Some(true)))).await?;
assert_eq!(retained.rows, [[Some("1".into())]]);
let a_after_b = run(&db, A, status, &cancel).await?.rows;
assert_eq!(&a_after_b[0][..2], &a[0][..2]);
assert_eq!(a_after_b[0][2].as_deref(), Some("2"));
println!("Separate backend/transaction IDs: A {:?}, B {:?}; observer sees only B's committed row", a[0], b[0]);
run(&db, B, "INSERT INTO public.console_tx VALUES (3)", &cancel).await?;
let stop = CancellationToken::new();
let slow = "SELECT pg_sleep(8) AS scoped_manual_a";
let mut a_slow = std::pin::pin!(run(&db, A, slow, &stop));
let active = async {
loop {
let rows = observer.rows(
"SELECT pid FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(8) AS scoped_manual_a'",
1,
).await?;
if !rows.is_empty() {
return IdeResult::Ok(());
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
};
tokio::select! {
result = &mut a_slow => panic!("A ended before observer saw it: {result:?}"),
observed = tokio::time::timeout(Duration::from_secs(3), active) => observed.expect("A reached PostgreSQL")?,
}
let waiting = CancellationToken::new();
let still_running = async {
let (waited, ()) = tokio::join!(run(&db, A, "SELECT 1", &waiting), async {
tokio::time::sleep(Duration::from_millis(100)).await;
waiting.cancel();
});
assert_eq!(waited.unwrap_err().kind, ErrorKind::Cancelled);
let b = run(&db, B, rows, &cancel).await?;
assert_eq!(b.rows, [[Some("2".into())], [Some("3".into())]]);
IdeResult::Ok(())
};
tokio::select! {
result = &mut a_slow => panic!("A ended before B finished: {result:?}"),
result = tokio::time::timeout(Duration::from_secs(2), still_running) => result.expect("B did not wait for A")?,
}
stop.cancel();
let error = tokio::time::timeout(Duration::from_secs(4), &mut a_slow).await.expect("A stopped").unwrap_err();
assert_eq!(error.kind, ErrorKind::Cancelled);
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())]]);
db.finish_postgres_console_transaction(TARGET, B, true).await?;
assert_eq!(observer.rows(rows, 10).await?, [[Some("2".into())], [Some("3".into())]]);
run(&db, A, "INSERT INTO public.console_tx VALUES (4)", &cancel).await?;
db.release_console(A).await?;
let stale = run(&db, A.expecting_manual(Some(true)), "INSERT INTO public.console_tx VALUES (5)", &cancel)
.await
.unwrap_err();
assert_eq!(stale.kind, ErrorKind::OutOfSync);
let stale_commit = db.finish_postgres_console_transaction(TARGET, A, true).await.unwrap_err();
assert_eq!(stale_commit.kind, ErrorKind::OutOfSync);
assert_eq!(run(&db, C, rows, &cancel).await?.rows, [[Some("2".into())], [Some("3".into())]]);
db.finish_postgres_console_transaction(TARGET, C, false).await?;
db.disconnect(TARGET).await;
println!(
"Stop A rolled back only A. B committed afterward, and releasing A rolled back its next transaction and freed a slot."
);
Ok(())
}
+71 -1
Переглянути файл
@@ -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"]);
@@ -384,6 +393,8 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
let details = db.table_details("p", "oi_keys", "refs").await?;
let indexes: Vec<_> = details.indexes.iter().map(|i| (i.name.as_str(), i.unique, i.columns.join(","))).collect();
assert_eq!(indexes, [("refs_pkey", true, "id".into()), ("refs_yx", true, "y,x".into())]);
let keys: Vec<_> = details.indexes.iter().map(|i| i.key).collect();
assert_eq!(keys, [Some(ide_db::DbKeyKind::Primary), None]);
let key = |k: &ide_db::ForeignKey| (k.columns.join(","), k.ref_table.clone(), k.ref_columns.join(","));
assert_eq!(
details.foreign_keys.iter().map(key).collect::<Vec<_>>(),
@@ -414,7 +425,29 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
let objects = db.schema_objects("p", "oi_keys").await?;
assert_eq!(objects.sequences.len(), 1);
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
let plain = db.ddl("p", "oi_keys", "refs").await?;
assert!(plain.contains("FOREIGN KEY"), "{plain}");
assert!(plain.contains("\n owner to "), "{plain}");
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
// Comments, privileges and triggers come back too, so the script rebuilds the table.
for statement in [
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
] {
db.execute("p", statement, 10, &c).await?;
}
let full = db.ddl("p", "oi_keys", "refs").await?;
for part in [
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
"grant insert, select on \"oi_keys\".\"refs\" to public;",
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
] {
assert!(full.contains(part), "{part}\n{full}");
}
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
Ok(())
}
@@ -779,3 +812,40 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
}
Ok(())
}
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
/// the other schemas, and the tables sorting last lost theirs (#6118).
#[tokio::test]
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
let mut sources = db.sources()?;
let mut source = sources[0].clone();
source.id = "wide".into();
source.options.startup_script = format!("SET search_path = {schema}");
sources.push(source);
let password = server().map(|(.., password)| password);
db.save_sources(sources).await?;
db.set_password("wide", password, false).await?;
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
let fill = format!(
"DO $$ DECLARE cols text; BEGIN \
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
END LOOP; END $$"
);
let result = async {
db.execute("p", &fill, 1, &c).await?;
let completion = db.completion("wide").await?;
assert_eq!(completion.default_schema, schema);
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
assert_eq!(wide.len(), 260);
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
Ok(())
}
.await;
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
result
}
+29 -2
Переглянути файл
@@ -2,8 +2,8 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{
CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection, DbTableKind,
DbVisibilityChange, QueryResult, SortKey,
CellValue, DataSource, DbDriver, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection,
DbTableKind, DbVisibilityChange, QueryResult, SortKey,
};
async fn setup() -> (tempfile::TempDir, DbManager) {
@@ -47,6 +47,7 @@ async fn introspects_schemas_tables_columns_and_indexes() -> IdeResult<()> {
assert_eq!(d.indexes[0].name, "users_name");
assert!(d.indexes[0].unique);
assert_eq!(d.indexes[0].columns, vec!["name"]);
assert_eq!(d.indexes[0].key, None, "a unique index is not a constraint");
let completion = db.completion("s1").await?;
assert_eq!(completion.default_schema, "main");
let users = completion.tables.iter().find(|t| t.name == "users").unwrap();
@@ -64,6 +65,32 @@ async fn introspects_schemas_tables_columns_and_indexes() -> IdeResult<()> {
Ok(())
}
/// The indexes SQLite makes for a non-rowid primary key and a UNIQUE constraint say which
/// key they enforce: Modify Table cannot drop those with `drop index`.
#[tokio::test]
async fn tells_key_indexes_from_plain_ones() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let c = CancellationToken::new();
for stmt in [
"CREATE TABLE codes (region TEXT, code TEXT, label TEXT, PRIMARY KEY (region, code), UNIQUE (label))",
"CREATE INDEX codes_label ON codes (label, code)",
] {
db.execute("s1", stmt, 1, &c).await?;
}
let d = db.table_details("s1", "main", "codes").await?;
let mut keys: Vec<_> = d.indexes.iter().map(|i| (i.columns.join(","), i.unique, i.key)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
keys,
vec![
("label".into(), true, Some(DbKeyKind::Unique)),
("label,code".into(), false, None),
("region,code".into(), true, Some(DbKeyKind::Primary)),
]
);
Ok(())
}
#[tokio::test]
async fn completion_model_has_foreign_keys() -> IdeResult<()> {
let (_tmp, db) = setup().await;
+1 -1
Переглянути файл
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
drop(pool);
master
+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
+126 -16
Переглянути файл
@@ -46,6 +46,13 @@ pub enum Capability {
/// the manifest does not list; each answer applies to one host. Plain
/// HTTP elsewhere always needs `net.http:<host>`.
NetAsk,
/// The host of the `string` setting `key`, approved when the user applies
/// its value in Settings (`net:setting:server`, `net.http:setting:server`).
/// HTTPS (and loopback HTTP) unless `http`.
NetSetting {
http: bool,
key: String,
},
/// Unencrypted HTTP to one host.
NetHttp(String),
/// A local socket or named pipe on the project machine.
@@ -62,6 +69,8 @@ pub enum Capability {
/// Load the plugin's Java agent into the JVMs of Java run configurations. Never
/// declared: it comes from `[[contributes.javaAgents]]`.
JavaAgent,
/// Fork a recorded native agent session into a new task in the open project (API 1.18).
Agents,
}
/// How a grant is presented (plan 4.2).
@@ -87,11 +96,13 @@ impl Capability {
| Self::VcsWrite
| Self::Net(_)
| Self::NetAsk
| Self::NetSetting { .. }
| Self::NetHttp(_)
| Self::Secrets
| Self::InputEvents
| Self::Clipboard
| Self::ClipboardRead => Risk::Medium,
| Self::ClipboardRead
| Self::Agents => Risk::Medium,
// A trusted project's own files name the programs the IDE starts (its settings, its
// build scripts), so writing them is running code.
Self::ProjectWrite
@@ -136,6 +147,12 @@ impl Capability {
"Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones"
.into()
}
Self::NetSetting { http, key } if *http => {
format!("Connect to the host set in the `{key}` setting over unencrypted HTTP (from the machine the project is on)")
}
Self::NetSetting { http: _, key } => {
format!("Connect to the host set in the `{key}` setting (from the machine the project is on)")
}
Self::NetHttp(host) => {
format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)")
}
@@ -149,6 +166,7 @@ impl Capability {
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
Self::JavaAgent => "Run code inside the Java applications you start".into(),
Self::Agents => "Fork a recorded agent session into a new task in the open project".into(),
}
}
@@ -180,6 +198,19 @@ pub fn host_matches(pattern: &str, host: &str) -> bool {
}
}
/// Validates a manifest-style host (letters, digits and `-` labels, at most 253
/// bytes) and returns it lowercased. A `*` is never valid here — only a
/// `net:`/`net.http:` grant itself may carry the `*.` subdomain pattern, and a
/// host taken from a setting value never does.
pub fn manifest_host(host: &str) -> Result<String, String> {
let valid = !host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|label| {
!label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
});
valid.then(|| host.to_ascii_lowercase()).ok_or_else(|| "invalid host".into())
}
/// Validates a socket path; a grant may use `*` in its last segment only.
pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> {
let pipe = name.starts_with(r"\\.\pipe\");
@@ -269,6 +300,8 @@ impl fmt::Display for Capability {
Self::ClipboardRead => f.write_str("clipboard.read"),
Self::Net(h) => write!(f, "net:{h}"),
Self::NetAsk => f.write_str("net:ask"),
Self::NetSetting { http, key } if *http => write!(f, "net.http:setting:{key}"),
Self::NetSetting { http: _, key } => write!(f, "net:setting:{key}"),
Self::NetHttp(h) => write!(f, "net.http:{h}"),
Self::Ipc(p) => write!(f, "ipc:{p}"),
Self::Process(b) => write!(f, "process:{b}"),
@@ -276,6 +309,7 @@ impl fmt::Display for Capability {
Self::FsRead(p) => write!(f, "fs.read:{p}"),
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
Self::JavaAgent => f.write_str("java.agent"),
Self::Agents => f.write_str("agents"),
}
}
}
@@ -295,23 +329,27 @@ impl FromStr for Capability {
if kind == "net" && arg == "ask" {
return Ok(Self::NetAsk);
}
let host = arg.strip_prefix("*.").unwrap_or(arg);
let valid = !host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|label| {
!label.is_empty()
&& label.len() <= 63
&& label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
});
if valid {
Ok(if kind == "net" {
Self::Net(arg.to_ascii_lowercase())
// `net:setting:<key>` names the plugin's `string` setting the
// host comes from; the same key rule as a settings schema.
if let Some(key) = arg.strip_prefix("setting:") {
let valid_key = !key.is_empty()
&& key.len() <= 64
&& key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
return if valid_key {
Ok(Self::NetSetting { http: kind == "net.http", key: key.to_owned() })
} else {
Self::NetHttp(arg.to_ascii_lowercase())
})
} else {
Err(format!("invalid host in {s:?}"))
Err(format!("invalid setting key in {s:?}"))
};
}
manifest_host(arg.strip_prefix("*.").unwrap_or(arg))
.map(|_| {
if kind == "net" {
Self::Net(arg.to_ascii_lowercase())
} else {
Self::NetHttp(arg.to_ascii_lowercase())
}
})
.map_err(|_| format!("invalid host in {s:?}"))
}
"ipc" => {
validate_ipc_name(arg, true)?;
@@ -355,6 +393,7 @@ impl FromStr for Capability {
"clipboard" => Self::Clipboard,
"clipboard.read" => Self::ClipboardRead,
"java.agent" => Self::JavaAgent,
"agents" => Self::Agents,
_ => return Err(format!("unknown capability {s:?}")),
})
}
@@ -549,6 +588,77 @@ mod net_ask_tests {
}
}
#[cfg(test)]
mod net_setting_tests {
use super::*;
/// `net:setting:<key>` names a settings key instead of a host: the host
/// comes from the setting's value and is approved when the user sets it
/// (#3809).
#[test]
fn setting_derived_grants_parse_and_print() {
for s in ["net:setting:server", "net.http:setting:server"] {
let cap: Capability = s.parse().unwrap();
assert_eq!(cap.to_string(), s, "{s}");
assert_eq!(cap.risk(), Risk::Medium, "{s}");
}
assert_eq!(
"net:setting:server".parse::<Capability>().unwrap(),
Capability::NetSetting { http: false, key: "server".into() }
);
assert_eq!(
"net.http:setting:server".parse::<Capability>().unwrap(),
Capability::NetSetting { http: true, key: "server".into() }
);
assert!(!"net:setting:server".parse::<Capability>().unwrap().auto_migrates());
let derived = "net:setting:server".parse::<Capability>().unwrap();
assert!(derived.describe().contains("`server`"));
assert!("net.http:setting:server".parse::<Capability>().unwrap().describe().contains("unencrypted"));
}
#[test]
fn setting_derived_grants_stay_strict() {
for s in ["net:setting:", "net:setting:a b", "net:setting:a:b", "net.http:setting:"] {
assert!(s.parse::<Capability>().is_err(), "{s}");
}
}
/// The derivation covers nothing by itself: a literal-host grant and a
/// setting-derived grant are different grants, and the host materializes
/// only after the user approves the setting's value.
#[test]
fn derived_grants_do_not_cover_literal_hosts() {
let derived: Capability = "net:setting:server".parse().unwrap();
let literal: Capability = "net:gitlab.intranet.example".parse().unwrap();
assert!(!derived.covers(&literal));
assert!(!literal.covers(&derived));
assert!(!derived.covers(&"net.http:gitlab.intranet.example".parse().unwrap()));
assert!(!derived.covers(&"net:setting:other".parse().unwrap()));
}
/// The host of a setting value passes the same rules as a manifest host,
/// and a `*` is refused (`net:*` stays impossible).
#[test]
fn value_hosts_follow_the_manifest_host_rules() {
assert_eq!(manifest_host("GitLab.Intranet.Example").unwrap(), "gitlab.intranet.example");
for bad in
["", "*", "*.example.com", "a b", "under_score.example", "gitlab.intranet.example.", &"a".repeat(254)]
{
assert!(manifest_host(bad).is_err(), "{bad}");
}
let long = ["a".repeat(61), "b".repeat(61), "c".repeat(61), "d".repeat(61)].join(".");
assert_eq!(long.len(), 247);
assert!(manifest_host(&long).is_ok());
assert!(
manifest_host(&["a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63)].join(".")).is_err(),
"over 253 bytes"
);
assert!(manifest_host(&"a".repeat(64)).is_err(), "over 63 bytes per label");
// Pattern grants keep working: only a value (and a bare host) refuses `*`.
assert!("net:*.github.com".parse::<Capability>().is_ok());
}
}
#[cfg(test)]
mod database_tests {
use super::*;
+89
Переглянути файл
@@ -58,6 +58,10 @@ pub struct Grant {
/// Exact hosts approved through `net:ask`, separate from manifest grants.
#[serde(default)]
pub net_hosts: BTreeSet<String>,
/// Hosts approved for `net:setting:<key>` / `net.http:setting:<key>`
/// grants, keyed by the grant: the user approved the value in Settings.
#[serde(default)]
pub setting_hosts: BTreeMap<String, String>,
/// Optional capabilities the user declined (not asked again until re-confirmed).
#[serde(default)]
pub declined: BTreeSet<String>,
@@ -209,6 +213,7 @@ impl Ledger {
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
grant.net_hosts.clear();
}
retain_setting_hosts(grant, req);
if !grant.confirmed {
return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true };
}
@@ -236,6 +241,7 @@ impl Ledger {
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
grant.net_hosts.clear();
}
retain_setting_hosts(grant, req);
grant.plugin_id = req.plugin_id.to_owned();
grant.version = req.version.to_owned();
grant.package_hash = req.package_hash.to_owned();
@@ -269,6 +275,9 @@ impl Ledger {
if cap == &Capability::NetAsk {
grant.net_hosts.clear();
}
if matches!(cap, Capability::NetSetting { .. }) {
grant.setting_hosts.remove(&s);
}
if let Capability::Process(_) | Capability::JavaAgent = cap {
grant.binaries.remove(&s);
for binaries in grant.project_binaries.values_mut() {
@@ -292,6 +301,21 @@ impl Ledger {
self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host))
}
/// Remembers the host the user approved for a `net:setting:` grant: it
/// covers requests only while the setting still holds it.
pub fn remember_setting_host(&mut self, subject: &Subject, cap: &Capability, host: &str) -> bool {
let Some(grant) = self.grants.get_mut(subject) else { return false };
if !grant.confirmed || !grant.has(cap) || host.contains('*') {
return false;
}
grant.setting_hosts.insert(cap.to_string(), host.to_owned());
true
}
pub fn forget_setting_host(&mut self, subject: &Subject, cap: &Capability) -> bool {
self.grants.get_mut(subject).is_some_and(|g| g.setting_hosts.remove(&cap.to_string()).is_some())
}
/// Records the program approved for a `process:` grant (or the jar of a `java.agent` one).
pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) {
if let Some(grant) = self.grants.get_mut(subject) {
@@ -393,6 +417,19 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
groups.into_iter().map(|(r, v)| (r.0, v)).collect()
}
/// Drops setting-derived hosts the manifest no longer asks for, like
/// `net_hosts` are dropped when `net:ask` is removed.
fn retain_setting_hosts(grant: &mut Grant, req: &Request<'_>) {
let declared: Vec<String> = req
.required
.iter()
.chain(&req.optional)
.filter(|c| matches!(c, Capability::NetSetting { .. }))
.map(|c| c.to_string())
.collect();
grant.setting_hosts.retain(|cap, _| declared.contains(cap));
}
/// Pins an explicitly selected executable, retaining a multicall shim's filename.
pub fn approve_program(path: &Path) -> Result<BinaryGrant, String> {
if !path.is_absolute() || !is_executable(path) {
@@ -589,6 +626,58 @@ mod tests {
assert!(l.get(&r.subject).unwrap().net_hosts.is_empty());
}
/// A setting-derived host is approved per grant, survives re-confirmation,
/// is replaced by the next approval, and goes when the grant or the
/// manifest declaration goes (#3809).
#[test]
fn setting_hosts_are_approved_per_grant_and_drop_with_it() {
let mut l = Ledger::in_memory();
let r = req("1.0.0", "h", &["project.read"], &["net:setting:server", "net.http:setting:server"]);
l.confirm(
&r,
&["net:setting:server".parse().unwrap(), "net.http:setting:server".parse().unwrap()],
BTreeMap::new(),
);
let cap: Capability = "net:setting:server".parse().unwrap();
let other: Capability = "net.http:setting:server".parse().unwrap();
// Not granted (declined optional, or not confirmed): refused.
let declined = req("1.0.0", "h", &["project.read"], &["net:setting:server"]);
let mut l2 = Ledger::in_memory();
l2.confirm(&declined, &[], BTreeMap::new());
assert!(!l2.remember_setting_host(&declined.subject, &cap, "jira.corp.example"), "declined optional");
let never = req("1.0.0", "h", &["project.read"], &[]);
let mut l3 = Ledger::in_memory();
assert!(!l3.remember_setting_host(&never.subject, &cap, "jira.corp.example"), "never confirmed");
assert!(l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example"));
assert!(!l.remember_setting_host(&r.subject, &cap, "*"), "a wildcard value is refused");
assert_eq!(
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
Some("gitlab.intranet.example")
);
// The other transport is its own record; the derived grant itself covers no host.
assert!(l.remember_setting_host(&r.subject, &other, "jira.corp.example"));
assert!(!l.get(&r.subject).unwrap().has(&Capability::Net("gitlab.intranet.example".into())));
// Re-confirmation keeps the approval; a manifest that drops the grant drops the record.
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
assert_eq!(
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
Some("gitlab.intranet.example")
);
let without = req("2.0.0", "h2", &["project.read"], &[]);
assert!(matches!(l.decide(&without), Decision::Allowed { .. }), "same or fewer needs: silent");
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty(), "records follow the manifest");
// Revoking the capability clears its record.
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example");
assert!(l.set(&r.subject, &cap, false));
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty());
// Forgetting without a record is an error.
assert!(!l.forget_setting_host(&r.subject, &cap));
}
#[test]
fn migration_grants_low_risk_only() {
let tmp = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -26,7 +26,9 @@ mod resolve;
mod ui;
mod when;
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
pub use capability::{
Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name,
};
pub use index::ContributionIndex;
pub use manifest::{
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
+44 -1
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.17.0";
pub const ENGINE_VERSION: &str = "1.18.0";
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
@@ -168,6 +168,8 @@ pub const EVENT_KINDS: &[&str] = &[
"action-performed",
"vcs-changed",
"problems-changed",
"project-closed",
"watched-files-changed",
];
impl std::fmt::Display for ActivationEvent {
@@ -367,6 +369,12 @@ impl Manifest {
if matches!(cap, Capability::ClipboardRead) {
self.needs_api(&format!("capability `{cap}`"), 11)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
if matches!(cap, Capability::NetSetting { .. }) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
if matches!(cap, Capability::JavaAgent) {
return Err(
"`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into()
@@ -403,6 +411,10 @@ impl Manifest {
if matches!(event, ActivationEvent::Event(kind) if kind == "files-changed") {
self.needs_api("`on-event:files-changed`", 3)?;
}
if matches!(event, ActivationEvent::Event(kind) if kind == "project-closed" || kind == "watched-files-changed")
{
self.needs_api(&format!("`{event}`"), 18)?;
}
if !seen.insert(event) {
return Err(format!("duplicate activation event {event}"));
}
@@ -758,6 +770,20 @@ required = [\"lsp:phoxite\"]
assert_eq!(m.capabilities.optional, [Capability::ClipboardRead]);
}
#[test]
fn setting_derived_net_capabilities_need_the_current_api_minor() {
for cap in ["net:setting:server", "net.http:setting:server"] {
let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n");
assert!(
err(&format!("{}{caps}", BASE.replace("^1.2", "^1.17"))).contains("new in plugin API 1.18"),
"{cap}"
);
let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).unwrap();
assert_eq!(m.capabilities.optional.len(), 1, "{cap}");
assert_eq!(m.capabilities.optional[0].to_string(), cap);
}
}
#[test]
fn java_agent_capability_is_not_declared() {
for list in ["required", "optional"] {
@@ -962,4 +988,21 @@ mod net_ask_api_tests {
}
}
}
#[test]
fn project_closed_and_watched_files_events_require_api_1_18() {
for kind in ["project-closed", "watched-files-changed"] {
for engine in ["^1.17", "^1.18"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:{kind}\"]\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.18" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{kind} {engine}");
}
}
}
}
}
-1
Переглянути файл
@@ -12,4 +12,3 @@ serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
which = "8"
+37 -18
Переглянути файл
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;
/// API calls normally answer within a few seconds.
const QUICK: Duration = Duration::from_secs(60);
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
/// install or remove a managed copy in its tools directory at runtime).
pub fn gh_executable() -> Option<PathBuf> {
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
GH.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("gh") {
return Some(found);
}
let candidates: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
})
.clone()
ide_core::tool_path::find_gh_executable()
}
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
@@ -386,3 +371,37 @@ pub fn prepare_diff(
let files = repo.diff_files(&base, head_oid)?;
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
}
#[cfg(test)]
mod tests {
#[test]
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let search = std::env::join_paths([&dir]).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
std::fs::remove_file(&gh).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
+8 -1
Переглянути файл
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
ide-search.workspace = true
ide-lsp.workspace = true
ide-vcs.workspace = true
ide-github.workspace = true
ide-dap.workspace = true
ide-heap.workspace = true
ide-jvm-attach.workspace = true
@@ -66,11 +67,17 @@ serde_json = { workspace = true, features = ["raw_value"] }
toml.workspace = true
specta.workspace = true
specta-typescript.workspace = true
tokio = { workspace = true, features = ["io-std"] }
bytes = "1"
flate2.workspace = true
http-body-util = "0.1"
hyper = { version = "1", features = ["http1", "server"] }
hyper-util = { version = "0.1", default-features = false, features = ["tokio"] }
tokio = { workspace = true, features = ["io-std", "net", "signal"] }
tracing.workspace = true
url = "2"
tracing-subscriber.workspace = true
parking_lot.workspace = true
notify.workspace = true
dunce.workspace = true
dirs.workspace = true
uuid.workspace = true
Loaded 100 of 1700 files, more files were not shown because too many files have changed in this diff. Show more