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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 7dee96dc64 fix(docker): show container logs, processes and image layers without the docker CLI
Connections reached through the Engine API (an SSH tunnel, a socket or a
TCP daemon) still ran `docker logs`, `docker top` and `docker image
history`, so on a machine without the docker CLI the Log and Processes
tabs and an image's layers failed. They now come from the Engine API
when the CLI is missing: the log streams and follows over its own
connection, undoing the chunked encoding and the per-stream frames (or a
TTY container's raw stream), and stops when the request is cancelled.
2026-11-20 11:45:38 +08:00
l0ng-ai 9293b13737 feat(vcs): show the Rollback Changes files as a checkable tree (#4684)
Rollback Changes listed the files flat. It now uses the checkable change tree of the Shelve and Create Patch dialogs: files grouped by directory under the repository, with tri-state boxes on repository and directory rows; the summary follows the selection.
2026-11-20 11:45:27 +08:00
l0ng-ai d1f79d05b3 fix(project-tree): add Manage Remotes and Clone to the Project view's Git menu (#4680)
The Project view's Git submenu stopped at Stash / Unstash; it now ends with Manage Remotes… and Clone…, like the editor's Git submenu and IDEA's Git context menu. Covered by a new e2e test in editorGitMenu.spec.ts.
2026-11-20 11:39:28 +08:00
l0ng-ai 176c43c908 fix(editor): make the paste history preview resizable (#4677)
Paste from History gives the preview more room by default and remembers the divider position (a resizable split). Delete moves beside the filter as a toolbar button; the snippets and preview use the active editor's font and zoom, and the preview drops line numbers to use its full width.
2026-11-20 11:33:27 +08:00
Nc 20b6b0aed5 fix(maven): sort sidebar profiles by ID (#4679)
The Maven sidebar listed profiles in model order. Profiles within each project group now sort by ID ignoring case, as IntelliJ's Maven tool window does; the -P argument keeps the model order.

Co-authored-by: qiany-sui <[email protected]>
2026-11-20 11:30:31 +08:00
l0ng-ai 101a0862e4 fix(database): reconnect a custom JDBC data source whose session was lost (#4675)
When a proxy or tunnel dropped an idle custom JDBC connection, every later statement failed and the source still showed Connected: the cached pool was only marked closed when the IDE closed it. After a failed statement the bridge now checks Connection.isValid (new valid op); an invalid or orphaned session closes the pool so the next statement or Connect reconnects. Keep-alive for JDBC uses the same check (and its option shows in the dialog); failures log at info.
2026-11-20 11:29:35 +08:00
Bin b48f0b6071 fix(vcs): enlarge deleted line marker hit area (#4669)
The deleted-lines marker is drawn above its gutter row, but clicks were resolved from the pointer's row, so clicking the triangle near the line boundary could miss the deletion. The marker gets a 12x12 transparent hit area (same triangle) with a pointer cursor, and clicks on it resolve to the deletion's row. Verified with vcs hunks and editor cm vitest, typecheck, and in the app (clicking the marker's upper half opens the Deleted lines popup).

Co-authored-by: ffgenius <[email protected]>
2026-11-20 11:23:37 +08:00
l0ng-ai a9b16c3e06 fix(debugger): keep call stack locations visible in narrow docks (#4671)
Call stack locations stay visible in narrow debug docks. Verified with e2e debugStackLayout, debugger vitest and typecheck.
2026-11-20 11:13:32 +08:00
l0ng-ai abd55f88b5 fix(search): make the editor switcher fit the workbench (#4660)
The editor switcher fits the workbench. Verified with e2e switcherLayout, search vitest and typecheck.
2026-11-20 11:13:20 +08:00
l0ng-ai dac4db0994 fix(settings): separate file type associations from ignore rules (#4657)
File Types settings separate file type associations from ignore rules. Verified with e2e fileTypesLayout, settings/locales vitest and typecheck.
2026-11-20 11:13:08 +08:00
Deng Liuтаdengliu b0d0ea868b feat(agents): configure GitHub Copilot authentication account (#4663)
Copilot launched with whichever GitHub CLI account was active outside the IDE. GitHub Copilot's settings get a GitHub account field: at launch the IDE asks gh for that account's token and passes it as COPILOT_GITHUB_TOKEN, without storing it; the account (not a credential) is kept with the agent's settings and scopes the catalog cache. Also adds the field's text to the en/zh catalog. Verified with cargo test -p ide-agent, clippy, agents and locale vitest, typecheck, and the field in Settings › Agents › Coding Agents.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:11:05 +08:00
Deng Liuтаdengliu d86ff872af fix(agents): recover model controls for fallback sessions (#4662)
A session whose agent fell back to a configuration without a model option kept a stale model label and offered no way to pick another model. The composer rebuilds the model control from the provider's catalog and set_config accepts a model from that catalog, switching through the same path as other discovered models. Verified with cargo test -p ide-agent, clippy, agents vitest and typecheck.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:07:37 +08:00
Deng Liuтаdengliu dbef3cdc96 fix(agents): support Auto-only Copilot catalogs (#4661)
Copilot can return an enabled Auto tier with an empty direct-model list; the catalog parser treated that as an empty catalog and forced the fallback transport. An enabled Auto tier now yields the auto model. Verified with cargo test -p ide-agent copilot and clippy.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:06:32 +08:00
C3B6 c483c3b76f perf(http-client): limit cached response details to four (#4659)
The HTTP Client kept every exchange's full request and response in memory for the whole session, even after its row left the backend's 100-entry history. The history list is capped at 100 like the backend, and only the four most recently viewed exchanges keep their details; older rows reload theirs from the saved history (which stores the full exchange) when selected. Verified with http-client vitest and typecheck.

Co-authored-by: 0xC3B6 <[email protected]>
2026-11-20 11:05:24 +08:00
HEOJUNFO da79a73def fix(http-client): keep the whole value of a Spring params/headers condition (#4666)
Spring params/headers conditions were split with split("=", 2), which drops everything after a second '='; only the first '=' divides name and value now, as in Spring. Verified with http-client vitest.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-20 11:04:44 +08:00
akshathayadav378-boopтаakshathayadav378-boop 2cc54b35f6 test(markdown): allow large render test to finish (#4664)
The large Markdown re-render test renders plugins/README.md repeatedly and can exceed Vitest's default 5 s timeout under full-suite load; it gets a 20 s timeout like other heavy tests.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 11:04:36 +08:00
zhzhsxтаzhzhsx 097221c1b3 fix(editor): colour Go's default like the other keywords (#4654)
@lezer/go tags every keyword except default, and gopls sends no keyword semantic tokens, so default in a Go switch/select rendered as plain text. Go now gets an extra style tag for default. Verified with editor cm vitest and typecheck.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:25:05 +08:00
l0ng-ai 1bb4ffe6b2 Keep the color scheme preview visible while editing (#4653)
The color scheme preview stays visible while editing scheme options. Verified with e2e colorSchemeLayout/editorFontLayout, settings and platform vitest and typecheck; main merged in (locale conflict resolved).
2026-11-20 10:22:05 +08:00
l0ng-ai 51e525336b Keep Welcome project search and actions in one row (#4652)
Welcome project search and actions stay in one row. Verified with e2e welcomeProjectsLayout, full vitest and typecheck.
2026-11-20 10:21:06 +08:00
l0ng-ai 1b47bc2c14 Keep the editor font preview visible while changing settings (#4649)
The editor font preview stays visible while changing font settings. Verified with e2e editorFontLayout, full vitest and typecheck.
2026-11-20 10:20:59 +08:00
l0ng-ai aa1326496b Show both commit ranges in Git branch comparisons (#4642)
Git branch comparison shows both commit ranges side by side in resizable panes. Verified with e2e branchCompareLayout, full vitest and typecheck.
2026-11-20 10:20:51 +08:00
leenтаleen2175 7850429174 fix(vcs): open existing worktrees over SSH (#4465)
Opening a linked worktree from an SSH or WSL project treated the remote directory as a local path. The Worktrees toolbar, row double-click and the checkout prompt's Open now go through openWorktree, which reuses the session's remote target and opens a remote window; local projects are unchanged. Verified with vcs and remote-dev vitest and typecheck on macOS (local path); the SSH flow was verified by the author in the native Linux app.

Co-authored-by: leen2175 <[email protected]>
2026-11-20 10:17:09 +08:00
Mansur Akhmadiтаmansur-akhmadi 3dd5c75fa0 feat(debugger): Remove All Watches in the Variables view's context menu (#4647)
A watch row's context menu in the Variables view gets Remove All Watches next to Remove Watch; it empties the project's stored watch list. Verified with debugger and locale vitest and typecheck; main merged in (locale conflict resolved).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:56 +08:00
Mansur Akhmadiтаmansur-akhmadi 36ecb53159 feat(run): Fold Lines Like This in the Run console's context menu (#4635)
The Run console's context menu gets Fold Lines Like This: it opens Settings › Build, Execution, Deployment › Console with the selected single-line text, or the right-clicked line, added to the fold patterns. Verified with full vitest, typecheck, and in the app (pattern added, Cancel leaves settings unchanged).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:00 +08:00
006405ca11 fix(remote): restore WSL projects onto a live connection (#4103)
* fix(remote): restore WSL projects onto a live connection

A reopened WSL window kept sending commands to a remote host it was no
longer connected to. Remember the remote location, and do not drop a
connection that a later open or a superseded attempt still needs.

Co-authored-by: Cursor <[email protected]>

* Use ? for the last remote location prefix (clippy::question_mark)

* fix(remote): save window session after connecting

---------

Co-authored-by: 胡长贵 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-11-20 10:12:35 +08:00
Mollo-i 40b95650cf fix(maven): custom project.* properties and bare built-in shorthands resolve to their definition (#4651)
Every project.* name was treated as a Maven built-in, so custom properties such as project.port never navigated, and the bare built-in shorthand (@artifactId@) did not either. Non-coordinate project.* names now fall through to the <properties> lookup along the parent chain, and the bare shorthand resolves to the pom's own coordinate unless a custom property of that name exists. Verified with cargo test -p ide-build (maven tests pass; the one failing Go workspace test is unrelated to this change and fails from the local go toolchain) and clippy.

Co-authored-by: Greenker <[email protected]>
2026-11-20 10:08:09 +08:00
zhzhsxтаzhzhsx 0a571c0b4d fix(libraries): keep a Go module inside the project editable (#4639)
go list -m reports a replace target's own folder as the module's Dir, so a local replacement inside the project was registered as a read-only library root. Modules whose source sits inside the opened project (outside vendor/) are no longer library roots. Also passes the project root in the zig_groups test added on main. Verified with cargo test -p ide-sdk (new go_modules test passes; three go command tests fail the same way without this change, from the local go shim) and clippy.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:06:44 +08:00
l0ng-ai b1f88bf79c Separate shelves from the files they contain (#4640)
Shelf tool window separates the list of shelves from the files of the selected shelf in resizable panes. Verified with e2e shelfLayout, full vitest and typecheck.
2026-11-20 09:21:25 +08:00
l0ng-ai 0a6b3d011f Keep plugin list and details visible in narrow settings (#4636)
Plugins settings keep the list and details visible in narrow settings with a resizable split. Verified with e2e pluginsLayout, plugins/settings/locales vitest and typecheck.
2026-11-20 09:17:56 +08:00
l0ng-ai fd9b20fa05 Give interactive rebase plans and messages separate panes (#4637)
Interactive rebase shows the plan and the commit message in separate resizable panes. Verified with e2e interactiveRebaseLayout, full vitest and typecheck.
2026-11-20 09:17:14 +08:00
l0ng-ai 4f5622d72c refactor(agents): remove playful words from the working status (#4555)
Removes Settings › Agents › Working Status and its playfulStatus / playfulAfterSeconds / playfulWords settings. The line under a working conversation keeps saying what the agent is doing (Reading…, Running a command…); stored values of the removed settings are ignored.
2026-11-20 09:13:57 +08:00
l0ng-ai f4a7a7bafb perf(ui): smoother editor scrolling, tab switching and first file open (#4633)
Removes selectors that restyled whole subtrees on every inserted editor line or focus change (CodeMirror via a pnpm patch; selectorCost.test.ts guards them), measures space width once per font, shares one tooltip host, builds tab menus lazily, caches parsed SVG icons, prewarms an off-screen editor at idle, stats project-tree entries in parallel, and keeps the Git tool window at its size during a live window resize. Verified with full vitest, typecheck, ide-vfs cargo test and clippy, gitLog e2e, and a window resize in the app.
2026-11-20 09:13:29 +08:00
l0ng-ai 737afc6a8d Keep keymap search and shortcuts readable in narrow settings (#4632)
Keymap settings group the scheme selector with its actions and move the search controls to a second line in narrow settings; long action names scroll inside the tree. Verified with e2e keymapLayout/compactSettingsControls, settings vitest and typecheck.
2026-11-20 09:11:52 +08:00
l0ng-ai 6bf75155b6 Keep hierarchy symbols and source context readable (#4630)
Hierarchy view keeps symbol names and source context readable in narrow panes. Verified with e2e hierarchyLayout, code-insight vitest and typecheck.
2026-11-20 08:26:29 +08:00
l0ng-ai bbedf7e1f6 Make Inspections panes fit narrow settings windows (#4629)
Inspections settings panes resize and fit narrow settings windows. Verified with e2e inspectionsLayout/settingsFormLayout, full vitest and typecheck.
2026-11-20 08:26:21 +08:00
l0ng-ai 42fd0fa8e0 Organize Code Style settings into tabs (#4627)
Code Style settings are organized into tabs. Verified with e2e codeStyleLayout, settings vitest and typecheck.
2026-11-20 08:22:50 +08:00
l0ng-ai 97a41ae983 Give line bookmark text room in the tool window (#4624)
Bookmarks tool window rows give line bookmark text room. Verified with e2e bookmarkTreeLayout, search vitest and typecheck.
2026-11-20 08:22:42 +08:00
l0ng-ai f29903b698 Give the Stash dialog room for branch names and messages (#4623)
Stash dialog gives branch names and the message field room. Verified with e2e stashDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:35 +08:00
l0ng-ai 610fe23f88 Make the Pull dialog fit long branch names (#4622)
Pull dialog wraps long branch names instead of overflowing. Verified with e2e pullDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:26 +08:00
l0ng-ai 59376b9718 Improve the Update Project dialog layout (#4621)
Update Project dialog options and actions lay out cleanly at any width. Verified with e2e updateProject, vcs vitest and typecheck.
2026-11-20 08:22:18 +08:00
l0ng-ai 170fd735dd fix(vcs): keep clone fields usable in narrow dialogs (#4618)
Clone dialog fields stay usable and inside the dialog in narrow windows. Verified with e2e cloneLayout, vcs vitest and typecheck.
2026-11-20 08:22:11 +08:00
l0ng-ai e0ae9e764c fix(app): fit the New Project wizard in narrow windows (#4617)
The New Project wizard's template form fits narrow windows and keeps edits when resized. Verified with e2e newProjectLayout, app vitest and typecheck.
2026-11-20 08:07:19 +08:00
l0ng-ai 19c1b72650 fix(settings): fit SDK details within Project Structure (#4616)
Project Structure SDK details now wrap and stay inside the pane in narrow windows; the Home Path row reuses the shared path field. Verified with e2e projectSdkLayout/sdkFieldLayout, settings vitest and typecheck.
2026-11-20 07:53:11 +08:00
lleviathe 06ff2e51c3 fix(editor): even out the spacing of editor tabs (#4606)
Editor tabs sit 4px apart and keep an 18px close slot at one edge: before the icon when the close button is on the left, after the label when it is on the right, so switching sides no longer resizes tabs. The drag ghost keeps the strip's classes so it renders with the same layout. Verified with e2e editorTabClose/editor, src/ui vitest, typecheck, and both close positions in the app.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 07:52:02 +08:00
l0ng-ai 6ae31b8148 test(keymap): list Shelve/Unshelve Silently in the VS Code and Eclipse presets (#4628)
#4620 added vcs.shelveSilently and vcs.unshelveSilently to the IntelliJ keymaps only, so the check that the VS Code preset covers every IntelliJ action id failed on main. Both the VS Code (macOS) and Eclipse (Windows) presets now list them unbound, like the other changelist actions.
2026-11-20 07:42:36 +08:00
Mansur Akhmadiтаmansur-akhmadi 3783b601b5 feat(vcs): copy a path from its repository's root in Copy Path/Reference… (#4626)
Copy Path/Reference... gains Path From Repository Root, as in IDEA: each selected path relative to the root of the Git repository holding it (innermost for nested repositories, a repository root as '.'), one per line, through the same copyPath menu group the hosting link uses. Paths outside every repository are left out, and the item is hidden when none is inside one.

Closes #4625

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 07:38:35 +08:00
l0ng-ai 37044dcd89 fix(vcs): give Local History diffs room in narrow panes (#4613)
Local History gave its revision list a fixed share of the pane, so in narrow panes the diff had little room and long labels were clipped. The list and diff are now a resizable split with sensible minimums, revision rows truncate with full text in tooltips, and the diff keeps room in narrow panes.
2026-11-20 07:37:21 +08:00
l0ng-ai 1a2adab237 fix(editor): align Reformat Code dialog groups and controls (#4611)
The Reformat Code dialog's option groups and controls were laid out ad hoc, so labels and checkboxes misaligned and the scope group wrapped awkwardly. The dialog now uses shared dialog fieldsets with aligned groups and controls, the same as the other analysis dialogs.
2026-11-20 07:12:25 +08:00
l0ng-ai 9ed87d77a7 fix(project-tree): make the Move dialog readable in narrow windows (#4609)
The Move dialog's title, target field and validation were laid out for a wide window, so in narrow ones the path and Browse button were clipped. The dialog now names what it moves (file, directory or N items), the target row wraps with its Browse button, and invalid targets (a folder into itself, the same directory) are explained inline.
2026-11-20 06:55:23 +08:00
Mansur Akhmadiтаmansur-akhmadi 9f4731189d feat(vcs): Shelve Silently and Unshelve Silently (#4620)
Shelving and unshelving always opened a dialog. As in IDEA, Shelve Silently (Changes toolbar, Ctrl+Shift+H / Shift+Cmd+H) shelves the Commit selection, or the active changelist, without a dialog, one shelf per changelist named as the Shelve dialog would suggest; Unshelve Silently (Ctrl+Alt+U / Opt+Cmd+U in the Shelf) applies the selected shelf or file into the matching changelist and honours Remove applied files from the shelf. The Shelve and Unshelve dialogs share the same helpers, and both actions are in the IntelliJ keymaps and IDEA_ACTIONS.

Closes #4619

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 06:39:35 +08:00
l0ng-ai 92ccfac192 fix(debugger): keep breakpoint details usable in narrow windows (#4605)
The Breakpoints dialog had a fixed list width beside the details, so in narrow windows locations were clipped and the details' controls ran off the dialog. The list and details are now a resizable split that stacks vertically below 560px (each layout remembered), the dialog itself can be resized, and locations show the file name and line with the full path in the tooltip.
2026-11-20 06:38:09 +08:00
l0ng-ai 60d335eec0 fix(refactor): keep the Change Signature parameter table readable (#4602)
The Change Signature dialog's parameter table had fixed column widths and a one-line preview, so in narrow windows types and names were clipped and long signatures ran off the preview. The table columns now share the width with truncation, the preview puts each parameter on its own line as IDEA's does, and the dialog's sections keep their controls visible.
2026-11-20 06:05:24 +08:00
Hafiz Faizan ul hassanтаfaizanalhassan a679e8086f feat(database): pick data source, then database and schema in the query console (#4614)
The query console's Data source dropdown mixed databases into the source list, and SQL Server's second dropdown listed databases. As in DataGrip, the dropdown now lists data sources only, and a database.schema switcher next to it opens a searchable database -> schema tree that loads a database's schemas on expand and moves the console to the picked database; one-level drivers keep a flat schema list and SQLite has none. SQL Server's console schema is now a real schema (SCHEMA_NAME()) that scopes resolution and completion, since a session's default schema can't be changed, while the pooled connection still returns to its database. Tree speed search also opens with Cmd/Ctrl+F, as in IDEA.

Closes #4577

Co-authored-by: faizanalhassan <[email protected]>
2026-11-20 06:04:34 +08:00
Mr0Bread 4c20aa5c8d test(editor): cover missing-file and malformed session restore (#4615)
Adds regression tests for editor session recovery: a deleted selected file is dropped quietly and the remaining tab restores with its caret, a permission-denied tab stays open with its error inline, and truncated session JSON loads as null without writing storage until a valid session replaces it. No production changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 06:00:56 +08:00
l0ng-ai d19d74120b fix(debugger): keep values visible in narrow variables panes (#4600)
In narrow Variables panes the name and type kept their full width, so values were cut to nothing and the Show button could be pushed out. Names and types now truncate within caps, the value and its Show button share a group that keeps a minimum width, overflow is measured against that group, and full names and types are in tooltips.
2026-11-20 06:00:12 +08:00
Mr0Bread 4e1cec5233 refactor(ipc): enforce typed error-kind comparisons (#4612)
IPC error kinds were compared as untyped strings (`(e as { kind?: string }).kind === "notFound"`), so a misspelt kind compiled and silently never matched. A typed `isErrorKind(error, kind)` helper, taking a kind from the generated `IdeError["kind"]`, now handles wrapped and raw IPC errors in document sync, editor session restore, Spring service identity, plugin commands and recent projects.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:41:29 +08:00
l0ng-ai 150eacc3de fix(editor): keep parameter info readable in narrow panes (#4599)
Parameter Info had a fixed 640px cap and a 12-signature window, so in narrow panes it overflowed the editor and long signatures were clipped. The popup now fits the editor's tooltip bounds and height, uses the editor's current font size, wraps long signatures with a hanging indent, scrolls when needed and keeps the current parameter in view.
2026-11-20 05:40:20 +08:00
l0ng-ai d1cc3cf68a fix(vcs): make merge panes resizable and keep actions visible (#4597)
The merge editor's three panes had fixed widths with decorative dividers, so in narrow windows they could not be resized and the toolbar actions overflowed. The panes are now a SplitGroup whose two handles carry the connector bands, each pane has its own title (branch and side), and the toolbar status is announced.
2026-11-20 05:25:12 +08:00
Mr0Bread 7c00ce4fa1 test(e2e): enforce TypeScript contract checking (#4610)
The e2e TypeScript project was never type checked: its tsconfig didn't inherit the app's settings, so @/ imports didn't resolve and hundreds of diagnostics went unnoticed. e2e/tsconfig.json now extends the root config (plus Node/Vite types and ES2024), pnpm typecheck runs tsrs -p e2e, and the remaining real type errors in the specs and fixtures are fixed; the code-style docs list the new project.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:19:07 +08:00
l0ng-ai 6539a95cb8 fix(vcs): keep push review readable in narrow windows (#4594)
The Push dialog's commits, changed files and diff panes had pixel minimums and fixed options rows, so narrow or short windows clipped the review and the target controls. The commits and changes now stack vertically below 640px with their own remembered split, the changed files come before the commit details, panes use relative minimums, and the target bar, options and tag options wrap.
2026-11-20 05:07:24 +08:00
l0ng-ai 08613ca800 fix(debugger): keep evaluation results readable in short dialogs (#4592)
The Evaluate dialog's result had a 220px minimum height, so in short windows the dialog overflowed and the result and buttons were cut off. The dialog now caps its height to the window, the expression field scrolls within half of it, imports wrap, and the result takes the remaining space; the expression uses the editor font and its label is tied to the field.
2026-11-20 04:49:29 +08:00
l0ng-ai 1ad8b06a1a fix(markdown): keep the Project view clickable in Preview only (#4604)
In Preview only the editor panel stays mounted but hidden, with no separator. react-resizable-panels adds an implicit resize region between two enabled panels without a separator; with the hidden panel's rect at zero it spanned everything left of the preview, showing a resize cursor and swallowing clicks in the Project view. The hidden editor panel is now disabled, leaving the group a single resizable panel.

Fixes #4589
2026-11-20 04:35:55 +08:00
l0ng-ai 2ca0e195e5 fix(editor): keep inline find controls inside narrow panes (#4588)
The inline find/replace bar used a fixed grid with a 220px minimum field, so in narrow editor panes the counter, option buttons and Close spilled outside the pane. The bar is now a container-query layout: fields shrink, the action groups wrap, and below 500px (and again below 224px) the actions and replace field move to their own rows while Show Replace and Close stay reachable.
2026-11-20 04:33:34 +08:00
Mr0Bread 750d35dd6e fix(vcs): discard stale status after project switch (#4598)
The VCS store reset on project switch, but replies to refreshes started for the previous project still wrote to it, restoring its branch, changed files and decorations and firing conflict notifications. A project generation, bumped on every switch (also when reopening the same folder), now gates full and incremental refresh results, errors and discovered roots; queued paths are dropped on switch, and the refresh queue still drains for the active project.

Closes #4596

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 04:10:23 +08:00
l0ng-ai f0273690b9 fix(run): keep test results readable in narrow panes (#4586)
The test tree's header held the counts, duration and every toolbar action in one 28px row, so narrow Run panes clipped the counts and buttons. As in IDEA's new layout, the status (icon, counts, total duration) now sits above the console, Expand All, Collapse All and Export Test Results move into a More Actions menu, and the tree and console stack vertically below 560px with their own remembered split.
2026-11-20 04:07:52 +08:00
l0ng-ai 04611c0388 fix(database): show a running SQL statement in the editor and results (#4601)
The console tracked the running request only for Run and Cancel; statement marks and result tabs arrived after it ended, and the Results view said "No results" meanwhile. While a request runs, the submitted statements are highlighted with a gutter spinner and a ticking elapsed time, and the Results view opens with an executing bar above the previous result. Edits during the run move the marks and the outcomes land on their statements; cancel or an error clears the indication and keeps the previous result.

Fixes #4565
2026-11-20 04:06:41 +08:00
l0ng-ai 1cfc71ae58 fix(editor): make symbol rename and its preview readable in narrow windows (#4583)
The symbol rename prompt was a caret-anchored popup that could be clipped in narrow windows, and its preview truncated long names. When in-place rename isn't available, Rename now opens a dialog with the symbol context, a New name field in the editor font, and an optional note; the refactoring preview keeps the context, wraps occurrence snippets in the editor font and theme, and truncates long file names with the full path in the tooltip.
2026-11-20 03:56:29 +08:00
l0ng-ai 8daaef38d9 fix(run): keep Run Anything controls visible on short windows (#4581)
Run Anything had a fixed 620px popup with a 360px list cap and a footer that could fall off short windows. The popup now fits the viewport as a column whose list shrinks, uses the shared search field with combobox semantics, shows the completion of the selected entry in the field, pages by the visible row count (compact-aware), and keeps a wrapping footer with the navigation hints.
2026-11-20 03:39:37 +08:00
Chris Schofield efd4e454ee feat(appearance): make Compact Mode match IntelliJ's compact density (#4593)
Compact Mode only lowered the title bar and narrowed the stripes: row heights, toolbar widgets and icons were fixed in code, and nothing in JS (where virtualised list row heights are set) could tell whether the mode was on. A small density store now mirrors the setting for JS, and Compact Mode uses IntelliJ's *.compact theme values: tree/list rows 22 (VCS log 24), toolbar widgets 26, toolbar and stripe icons 16, status bar 24, island gap 4, and chrome text 1px smaller.

Co-authored-by: ChildishForces <[email protected]>
2026-11-20 03:26:32 +08:00
l0ng-ai 0379c37a49 fix(usages): keep results and previews readable in narrow windows (#4580)
The Show Usages popup and the Find usages view used fixed header heights, a flexible spacer and a fixed preview height, so in narrow windows the title, file names and line numbers were clipped and the preview pushed results off screen. Headers now wrap their actions, rows use a file / line / text grid with truncation, and the preview shrinks with the viewport.
2026-11-20 03:21:33 +08:00
l0ng-ai 98da80b2b3 fix(editor): keep the current breadcrumb visible (#4579)
Long breadcrumb trails hid the current file or symbol when the editor or status bar ran out of room. Both trails now scroll to the current location (with edge fades) and keep earlier entries reachable by wheel, trackpad or keyboard. The status bar reserves a minimum width for the path and moves lower-priority widgets into its overflow menu. Code breadcrumbs use the editor font and highlight the symbol at the caret.
2026-11-20 03:05:31 +08:00
l0ng-ai 5c2e7ff92a fix(editor): fit intention previews beside or below the list (#4578)
The intention preview had a fixed 420px width beside the list, which pushed the action list away from the caret or got clipped in narrow windows. The preview now opens to the right when there is room, to the left when that keeps the list by the caret, and below the list in narrow windows. Preview code follows the editor's font settings and theme and wraps long lines.
2026-11-20 02:54:44 +08:00
l0ng-ai e86a853048 fix(run): keep configuration names visible in narrow sidebars (#4573)
A long run target could take the whole row in the Run/Debug Configurations sidebar, leaving the configuration name at zero width and forcing horizontal scrolling. Target labels now truncate in wide panes, narrow panes (container query) hide the muted target and scope, and the row tooltip carries the full name, target, scope and command. Type headings are semibold.
2026-11-20 02:53:44 +08:00
l0ng-ai fd8f0eb99c fix(editor): make quick documentation fit narrow windows (#4568)
Quick Documentation used a fixed 600px cap and kept its caret anchor after the window shrank, so short documents looked cramped and the actions could end up off screen. The popup now sizes to a 300-500px content width, keeps its actions together in the lower-right corner while the document scrolls, and clamps the anchor to the current viewport.
2026-11-20 02:52:46 +08:00
l0ng-ai 121e1fa535 fix(completion): fit the lookup to the editor and its font (#4566)
The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size.
2026-11-20 02:51:47 +08:00
lleviathe 5859cf9f5b feat(mcp): show background projects in the status bar (#4590)
A Background Projects status bar item shows how many projects the MCP server holds open without a window, only while there are any (and never in a remote window). Its popup lists each project with its badge, state and path, opens one in its own window or unloads it, and offers Unload All and MCP Server Settings. The Settings page's Open now list uses the same rows.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 02:49:08 +08:00
l0ng-ai 21b187f2d5 test: fix main's spacing-scale and model-refresh failures (#4591)
pnpm test failed on main twice: the HTTP Client's redirect list from #4519 used gap: 2px instead of --space-0-5, and the agent model-refresh test's IPC mock lacked vcsRemotes, which the session's origin lookup reads since #4554.
2026-11-20 02:47:51 +08:00
Aditya Aggarwalтаaditya-786 121d7edc15 feat(spring): find Feign clients for a controller endpoint (#4584)
A Spring controller endpoint gets Find Feign Clients (gutter menu, editor context menu, Find Action; Java and Kotlin): it matches the HTTP method and literal route across the trusted workspace and uses the controller module's spring.application.name to leave out clients of other services. One known match opens directly; otherwise a chooser lists the interface methods, with unresolved service names and explicit URLs marked Possible match.

Co-authored-by: aditya-786 <[email protected]>
2026-11-20 02:44:16 +08:00
Gabriel Gondim b9256a7260 fix(deployment): use Commit selection for upload shortcuts (#4585)
Deployment actions run by shortcut, Find Action or the Tools menu used the Project view's selection (else the editor's file) even in the Commit tool window, where only the context menu passed the selected changes. The changes tree now provides its selection while Commit or Git > Local Changes is focused, without deleted files, and Deployment takes it after a menu's paths.

Co-authored-by: GGVidal <[email protected]>
2026-11-20 02:28:50 +08:00
Mansur Akhmadiтаmansur-akhmadi 47b4cb55ba feat(run): Sort Alphabetically / Sort by Duration in the test results toolbar (#4576)
The test results toolbar gets Sorting Options with Sort Alphabetically (by name at every level, ignoring case, numbers by value) and Sort by Duration (slowest first at every level, a suite by its total, untimed last; disabled and not applied while the run is in progress). The two replace each other, run after the filters and are kept with Show Passed / Show Ignored.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 01:31:29 +08:00
Vadim LazukтаInf1mum da1bcd67cd fix(http-client): keep the request method across redirects and show the hops (#4519)
reqwest's automatic redirects turned a POST into a plain GET on a 301 or 302, such as the http to https redirect in #4486, and hid the redirect. Redirects are now followed by hand, as IntelliJ's HTTP Client does: 301, 302, 303, 307 and 308, at most 50 times. A 303 continues as GET without the body; the other statuses keep the method and body. Authorization and cookie headers are not re-sent to another host. The followed hops are listed in the response view.

Co-authored-by: Inf1mum <[email protected]>
2026-11-20 01:30:22 +08:00
Mr0Bread 67a4797cf4 fix(editor): preserve dirty state across concurrent saves (#4571)
Typing while a save was pending could leave the editor clean although the newest edit was not written: the save reply cleared the dirty flag even after a dirty event for a newer version, and a delayed clean event for the earlier write could clear it too. DocDirty now carries the document version from under the backend lock; the editor applies a clean transition only when that version is the synced one and no edits are pending, and a save reply only confirms the version it sent.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 01:28:48 +08:00
l0ng-ai 39523bc419 fix(terminal): float search over the output area (#4560)
Find in Terminal took a full-width row and shrank the grid. Wide, tall panes now show a compact search bar over the output's upper-right corner, keeping the full grid; it moves to the lower right when it would cover the active match. Short panes use an inline bar and narrow panes put the controls in two rows.
2026-11-20 01:23:38 +08:00
Mr0Bread 639c76d54c test(documents): protect dirty state on failed saves (#4567)
Tests that a failed save keeps the edited buffer dirty and emits no clean-state event: text the encoding can't represent, permission denial (Unix, with a retry after restoring permissions) and a file replaced by a directory. Disk bytes and the replacement directory stay untouched.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 01:21:12 +08:00
l0ng-ai d5f29ea256 fix(build-tools): keep toolbar actions reachable in narrow panes (#4558)
The Maven and Gradle toolbars used one fixed row, which clipped actions in narrow panes. Narrow panes keep reload or cancel, run and execute visible and group the rest in More Actions; widening the pane restores the full toolbar, keeping the offline and skip-tests toggle states.
2026-11-20 01:06:13 +08:00
l0ng-ai f9455549a7 fix(vcs): keep branch rows readable in narrow popups (#4551)
Git Branches uses the interface font for branch names, tracked branches and refs, tapers indentation at deeper levels and limits the width of secondary refs, so deeply nested branches keep room for the name, commit counts and submenu arrow. The full branch and tracked ref show on hover.
2026-11-20 00:45:28 +08:00
l0ng-ai dd14e8b040 fix(run): keep classpath and target probes from opening console windows on Windows (#4562)
On Windows the GUI-subsystem app gave console children their own window unless they were spawned with CREATE_NO_WINDOW. Three probes used a bare std Command: the Maven classpath probe behind delegated Run/Debug, the .NET target-path probe and go list for file-scoped Go tests. The first two now go through ide_core::process::prepare; the Go probe, whose environment is already built, gets the flag. The other backend spawn sites already prepare.
2026-11-20 00:42:56 +08:00
Paweł SzymańskiтаPawelSzymanski89 efce16d45d feat(agents): add Hermes Agent with a profile picker and richer tool-call view (#4542)
Adds Hermes Agent as a built-in ACP agent, with a Hermes profile picker. The tool-call view also gets richer: kind icons, duration, status, exit codes, a terminal block for commands, and links to the files a tool touched (omitted when the title already names the file).

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-20 00:32:51 +08:00
l0ng-ai 977ce62bf0 fix(search): improve recent file and location layouts (#4548)
Recent Files keeps directories beside file names and gives the list and filter more room in narrow windows. Recent Locations snippets follow the editor font and line spacing, and long file names leave room for the change label and timestamp.
2026-11-20 00:22:22 +08:00
l0ng-ai 479123dcf3 fix(plugins): give a child's status only with the last of its output (#4572)
poll and wait returned the exit status as soon as the process ended. Reader threads could still be copying its pipes, or more output could be buffered than one chunk holds, so a caller stopping at the first status parsed a truncated result. The status now comes only with the chunk that drains the output once both pipes reached the end. WIT, SDK and guide docs say so, and point to run_command for a command's whole output.
2026-11-20 00:18:30 +08:00
l0ng-ai 09301ca12d test(bench): skip browser tests where Playwright's Chromium isn't installed (#4570)
Since #4489 and #4491, harness tests under pnpm test launched Chromium, but CI's Frontend job installs no Playwright browsers, so Frontend failed on every pull request. Those tests now skip when the build they launch (headless shell, or the full browser for the chromium channel) is missing. The legacy artifact-date test compares whole seconds, which every file system keeps.
2026-11-20 00:03:28 +08:00
l0ng-ai 485c1ac40b fix(search): fit Search Everywhere within a compact popup (#4546)
Search Everywhere opens at 700 px wide and up to 600 px tall, query and footer included. Long lists and the code preview fit inside that height, so more of the editor stays visible.
2026-11-20 00:02:05 +08:00
l0ng-ai 6d756ec472 fix(editor): keep diagnostics in place through edits when another source updates (#4563)
Whenever any diagnostic source published, the editor converted every source's stored line/column ranges against the current text again. So lists published earlier, notably checks of the saved file (build, PHPStan, Kotlin bridge), jumped to the wrong code after typing. Each source's list is now anchored to the text it arrived for, and placed through the edits made since then. The editor-side counterpart of #4482.
2026-11-19 23:40:34 +08:00
517 змінених файлів з 17120 додано та 4765 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -5017,6 +5017,7 @@ dependencies = [
"ignore",
"notify",
"parking_lot",
"rayon",
"rustix",
"serde",
"serde_json",
+1 -1
Переглянути файл
@@ -51,7 +51,7 @@ async fn run_once(
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
})
.await
.map_err(|e| e.to_string())?;
.map_err(|e| e.to_string())??;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
+22 -1
Переглянути файл
@@ -3,7 +3,7 @@
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentUsage,
AgentModelPricing, AgentTokens, AgentUsage,
};
use serde_json::{Value, json};
@@ -272,6 +272,18 @@ pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)?, cost })
}
/// The `usage` of a `session/prompt` result: `{ inputTokens, cachedReadTokens, outputTokens }`.
pub(crate) fn tokens_of(result: &Value) -> Option<AgentTokens> {
let usage = result.get("usage")?;
let tokens = |key: &str| usage.get(key).and_then(Value::as_u64).map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX));
let tokens = AgentTokens {
input: tokens("inputTokens"),
cached: tokens("cachedReadTokens"),
output: tokens("outputTokens"),
};
(tokens != AgentTokens::default()).then_some(tokens)
}
/// The usage-limit windows a [`crate::LIMITS_UPDATE`] carries; malformed entries are skipped.
pub(crate) fn limits_of(update: &Value) -> Vec<AgentLimit> {
let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten();
@@ -368,6 +380,15 @@ mod tests {
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect()
}
#[test]
fn a_hermes_prompt_result_reports_the_turns_tokens() {
let result = json!({"stopReason": "end_turn", "usage": {"cachedReadTokens": 51306, "inputTokens": 77284,
"outputTokens": 509, "thoughtTokens": 0, "totalTokens": 77793}});
assert_eq!(tokens_of(&result), Some(AgentTokens { input: 77284, cached: 51306, output: 509 }));
assert_eq!(tokens_of(&json!({"stopReason": "end_turn"})), None);
assert_eq!(tokens_of(&json!({"usage": {}})), None);
}
#[test]
fn config_options_win_over_the_older_fields() {
let r = json!({
+111
Переглянути файл
@@ -0,0 +1,111 @@
//! Hermes Agent profiles on disk: `default` is the Hermes home itself, the others are
//! `<home>/profiles/<name>` directories holding one of Hermes' identity files.
use std::path::{Path, PathBuf};
use serde::Serialize;
use specta::Type;
const PROFILE_FILES: &[&str] = &["config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db"];
/// Hermes' home directory (`~/.hermes`; `%LOCALAPPDATA%\hermes` on Windows).
pub fn root(home: Option<&Path>) -> Option<PathBuf> {
#[cfg(windows)]
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
return Some(PathBuf::from(local).join("hermes"));
}
home.map(|h| h.join(".hermes"))
}
/// The profile names under `root`: `default` first, then the others by name; none without `root`.
pub fn profiles(root: &Path) -> Vec<String> {
if !root.is_dir() {
return Vec::new();
}
let mut named: Vec<String> = std::fs::read_dir(root.join("profiles"))
.into_iter()
.flatten()
.flatten()
.filter(|e| PROFILE_FILES.iter().any(|f| e.path().join(f).exists()))
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
.filter(|name| name != "default")
.collect();
named.sort();
std::iter::once("default".to_owned()).chain(named).collect()
}
/// A profile and the name Hermes shows for it (`hermes profile list`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
pub struct HermesProfile {
/// What `hermes -p` takes; `default` is the Hermes home itself.
pub name: String,
/// `display_name` from the profile's `profile.yaml`, else the name.
pub label: String,
}
/// [`profiles`] with the names Hermes shows for them.
pub fn labeled_profiles(root: &Path) -> Vec<HermesProfile> {
profiles(root)
.into_iter()
.map(|name| {
let home = if name == "default" { root.to_path_buf() } else { root.join("profiles").join(&name) };
let label = display_name(&home).unwrap_or_else(|| name.clone());
HermesProfile { name, label }
})
.collect()
}
/// The top-level `display_name:` of `<home>/profile.yaml`, the only key read (no YAML parser).
fn display_name(home: &Path) -> Option<String> {
let text = std::fs::read_to_string(home.join("profile.yaml")).ok()?;
let value = text.lines().find_map(|l| l.strip_prefix("display_name:"))?;
let value = value.trim().trim_matches(['"', '\'']).trim();
(!value.is_empty()).then(|| value.to_owned())
}
/// The home of the profile an agent id stands for: `hermes` and `hermes-default` are the
/// default profile, `hermes-<slug>` the profile whose name slugifies to `<slug>`.
pub fn profile_home(root: &Path, provider: &str) -> Option<PathBuf> {
let slug = match provider {
"hermes" | "hermes-default" => return Some(root.to_path_buf()),
_ => provider.strip_prefix("hermes-")?,
};
profiles(root).into_iter().find(|p| crate::provider::slugify_id(p) == slug).map(|p| root.join("profiles").join(p))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lists_default_and_profiles_with_an_identity_file() {
let dir = tempfile::tempdir().unwrap();
assert!(profiles(&dir.path().join("missing")).is_empty());
let root = dir.path().join(".hermes");
std::fs::create_dir_all(root.join("profiles/empty")).unwrap();
assert_eq!(profiles(&root), ["default"]);
for (name, file) in [("work", "config.yaml"), ("Dom 2", "SOUL.md"), ("db", "state.db")] {
std::fs::create_dir_all(root.join("profiles").join(name)).unwrap();
std::fs::write(root.join("profiles").join(name).join(file), "").unwrap();
}
std::fs::write(root.join("profiles/stray.yaml"), "").unwrap();
assert_eq!(profiles(&root), ["default", "Dom 2", "db", "work"]);
assert_eq!(profile_home(&root, "hermes"), Some(root.clone()));
assert_eq!(profile_home(&root, "hermes-dom-2"), Some(root.join("profiles/Dom 2")));
assert_eq!(profile_home(&root, "hermes-empty"), None);
assert_eq!(profile_home(&root, "claude"), None);
}
#[test]
fn labels_profiles_with_their_display_name() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join(".hermes");
std::fs::create_dir_all(root.join("profiles/work")).unwrap();
std::fs::write(root.join("profile.yaml"), "description: mine\ndisplay_name: \"qb\"\n").unwrap();
std::fs::write(root.join("profiles/work/profile.yaml"), "ui_meta:\n display_name: nested\n").unwrap();
let label = |name: &str, label: &str| HermesProfile { name: name.into(), label: label.into() };
assert_eq!(labeled_profiles(&root), [label("default", "qb"), label("work", "work")]);
std::fs::remove_file(root.join("profile.yaml")).unwrap();
assert_eq!(labeled_profiles(&root)[0], label("default", "default"));
}
}
+62 -15
Переглянути файл
@@ -14,6 +14,7 @@ mod config;
mod conversation;
mod elicitation;
mod external;
pub mod hermes;
pub mod mcp;
mod model;
mod native;
@@ -131,6 +132,7 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
github_account: Option<String>,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
@@ -192,6 +194,7 @@ impl Shared {
let metadata = std::fs::metadata(&executable).ok();
CopilotBinaryKey {
command: executable.to_string_lossy().into_owned(),
github_account: provider::copilot_github_account(&spec.env),
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
@@ -709,7 +712,8 @@ impl AgentManager {
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed.
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
/// its profile's skills).
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
@@ -743,10 +747,18 @@ impl AgentManager {
offered.push(command);
}
}
let home = self.shared.paths.home_dir.clone();
if provider == "hermes" || provider.starts_with("hermes-") {
let found = blocking(move || {
let profile = hermes::root(home.as_deref()).and_then(|root| hermes::profile_home(&root, &provider));
Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default())
})
.await?;
return Ok(skills::merge(offered, found));
}
if provider != "claude" && provider != "claude-acp" {
return Ok(offered);
}
let home = self.shared.paths.home_dir.clone();
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
Ok(skills::merge(offered, found))
}
@@ -832,6 +844,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
task: task.clone(),
@@ -949,6 +962,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
stats: Box::default(),
};
let file = TaskFile {
task: task.clone(),
@@ -1114,6 +1128,16 @@ impl AgentManager {
/// Changes a session setting (model, mode…): right away when the agent runs, else when it next starts.
pub async fn set_config(&self, id: &str, option: &str, value: String) -> IdeResult<()> {
let task = self.task(id)?;
let provider = task.state.lock().task.provider.clone();
let discovered = self
.shared
.paths
.catalogs
.cached(&self.shared, &provider)
.config
.iter()
.find(|o| o.id == option && o.category.as_deref() == Some("model"))
.cloned();
let (target, change) = {
let mut s = task.state.lock();
let busy = s.busy;
@@ -1134,17 +1158,19 @@ impl AgentManager {
task.emit_task();
return Ok(());
}
let target = s
.task
.config
.iter()
.find(|o| o.id == option)
.ok_or_else(|| IdeError::not_found("no such setting"))?
.clone();
let session_target = s.task.config.iter().find(|o| o.id == option).cloned();
let recovered_model = session_target.is_none();
let target = match session_target {
Some(target) => target,
None if discovered.is_some() => discovered.unwrap(),
None => return Err(IdeError::not_found("no such setting")),
};
if s.pending_model.is_some() && config::is_per_model_option(&target) {
return Err(IdeError::invalid("This setting is not available on the selected model"));
}
if !target.values.iter().any(|v| v.value == value) {
if recovered_model {
(target, None)
} else if !target.values.iter().any(|v| v.value == value) {
if target.category.as_deref() != Some("model") {
return Err(IdeError::invalid(format!("{} has no value {value}", target.name)));
}
@@ -1316,6 +1342,7 @@ impl AgentManager {
resets_ms: None,
retry: None,
background: Box::default(),
stats: Box::default(),
..s.task.clone()
};
TaskFile {
@@ -2653,7 +2680,13 @@ impl Task {
.await;
}
match result {
Ok(v) => Ok(v.get("stopReason").and_then(Value::as_str).unwrap_or("end_turn").to_owned()),
Ok(v) => {
if let Some(tokens) = config::tokens_of(&v) {
self.state.lock().task.stats.tokens = Some(tokens);
self.emit_task();
}
Ok(v.get("stopReason").and_then(Value::as_str).unwrap_or("end_turn").to_owned())
}
Err(e) => Err(self.failure(e)),
}
}
@@ -2780,9 +2813,12 @@ impl Task {
pending_model: Option<&PendingModel>,
) -> Result<Live, SessionOpenError> {
let launch_cwd = cwd.to_path_buf();
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
let mut spec = tokio::task::spawn_blocking(move || {
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
})
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| SessionOpenError { message: e, allow_acp_fallback: false })?;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
@@ -3187,6 +3223,17 @@ impl Task {
return;
}
if kind == "session_info_update" {
let depth = update.pointer("/_meta/hermes/sessionProvenance/compressionDepth").and_then(Value::as_u64);
if let Some(depth) = depth.and_then(|d| u32::try_from(d).ok()) {
let changed = {
let mut s = self.state.lock();
std::mem::replace(&mut s.task.stats.compressions, depth) != depth
};
if changed {
self.persist();
self.emit_task();
}
}
// The agent's own title for the session replaces the first line of the prompt,
// unless the user named the task.
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
@@ -4038,7 +4085,7 @@ fn entry_event(
entry: &AgentEntry,
) -> AgentEvent {
let text = match entry {
AgentEntry::Agent { text } | AgentEntry::Thought { text } => Some(text),
AgentEntry::Agent { text } | AgentEntry::Thought { text, .. } => Some(text),
_ => None,
};
let Some(text) = text else {
+31
Переглянути файл
@@ -108,6 +108,29 @@ pub struct AgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub mcp_overrides: BTreeMap<String, bool>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
pub stats: Box<AgentSessionStats>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionStats {
/// The last turn's tokens (`session/prompt` result `usage`).
#[serde(default)]
pub tokens: Option<AgentTokens>,
/// How many times the agent compressed the conversation (Hermes `compressionDepth`).
#[serde(default)]
pub compressions: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentTokens {
pub input: u32,
pub cached: u32,
pub output: u32,
}
/// A task the agent runs in the background while the conversation goes on.
@@ -479,6 +502,9 @@ pub enum AgentEntry {
},
Thought {
text: String,
/// When the reasoning started (ms since the epoch); `None` in tasks saved before.
#[serde(default)]
started_ms: Option<f64>,
},
Tool {
id: String,
@@ -490,6 +516,11 @@ pub enum AgentEntry {
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
/// When the call started and ended (ms since the epoch); `None` in tasks saved before.
#[serde(default)]
started_ms: Option<f64>,
#[serde(default)]
ended_ms: Option<f64>,
},
Plan {
items: Vec<AgentPlanItem>,
+2 -1
Переглянути файл
@@ -144,7 +144,8 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
})
.await
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
let args = headless_args(&launch.args);
let peer = Peer::spawn_framed(
+14 -2
Переглянути файл
@@ -312,7 +312,7 @@ impl Settings {
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when not already in the list.
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
.map(Vec::as_slice)
.unwrap_or_default();
let mut out = Vec::new();
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
@@ -344,6 +344,18 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
out
}
fn auto_model_available(list: &Value) -> bool {
let Some(auto) = list.get("auto") else { return false };
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
return false;
}
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
tiers.is_empty()
|| tiers.iter().any(|tier| {
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
})
}
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
let id = str_of(m, "id")?.to_owned();
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
+66
Переглянути файл
@@ -110,6 +110,72 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"displayName": "Standard",
"type": "auto",
"fusionTier": "standard",
"status": { "enabled": true, "pickerVisible": true }
},
{
"id": "hydrafusion",
"displayName": "High",
"type": "fusion",
"fusionTier": "high",
"status": {
"enabled": false,
"pickerVisible": true,
"reason": "user_not_eligible"
}
},
{
"id": "fast",
"displayName": "Fast",
"type": "auto",
"status": { "enabled": true, "pickerVisible": false }
}
],
"providerId": "copilot"
},
"imageModels": []
});
let catalog = models::parse_catalog(&list, None);
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
let options =
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
let model = options.iter().find(|option| option.id == MODEL).unwrap();
assert_eq!(model.current.as_deref(), Some("auto"));
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
}
#[test]
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"status": { "enabled": false, "pickerVisible": true }
}
]
}
});
assert!(models::parse_catalog(&list, None).is_empty());
}
#[test]
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
+140 -3
Переглянути файл
@@ -9,6 +9,8 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -82,6 +84,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
("kiro", "Kiro", Driver::Acp, &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."),
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
];
fn builtins() -> Vec<ProviderSpec> {
@@ -137,15 +140,31 @@ impl ProviderSpec {
/// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_with_copilot_env(cwd, strip)
self.resolve_for_launch_base(cwd, strip)
}
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
pub(crate) fn resolve_for_launch_with_copilot_env(
self,
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
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)?;
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
}
Ok(resolved)
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
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.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command =
@@ -163,6 +182,50 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
id == "copilot" || id.starts_with("copilot-")
}
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
env.iter()
.rev()
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
.map(|(_, value)| value.trim())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
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))
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
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);
}
let output = command
.output()
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.trim();
return Err(if detail.is_empty() {
format!("GitHub CLI has no authenticated account named {account}")
} else {
format!("Couldn't use GitHub account {account}: {detail}")
});
}
let token = String::from_utf8(output.stdout)
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
let token = token.trim();
if token.is_empty() {
return Err(format!("GitHub CLI returned no token for account {account}"));
}
Ok(token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -338,6 +401,31 @@ pub(crate) fn set_builtin_env(
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
&& agent.registry.is_some()
{
let existing = agent.env.clone();
let mut existing_launch_env = existing.clone();
let mut next_launch_env = env.clone();
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
if existing_launch_env != next_launch_env {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
Some(account) => {
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
}
None => {
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
}
}
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
}
@@ -503,7 +591,7 @@ fn validated_custom_id(id: &str) -> IdeResult<String> {
}
/// Turns an `acp.json` server name into a file-stem id (`"My Agent!"` → `"my-agent"`).
fn slugify_id(name: &str) -> String {
pub(crate) fn slugify_id(name: &str) -> String {
let mut id = String::with_capacity(name.len());
for c in name.chars() {
if c.is_ascii_alphanumeric() {
@@ -716,6 +804,15 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn hermes_is_built_in_over_acp() {
let spec = builtin_spec("hermes").unwrap();
assert_eq!(spec.driver, Driver::Acp);
let info = describe(&spec);
assert_eq!((info.name.as_str(), info.command.as_str()), ("Hermes Agent", "hermes acp"));
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
}
#[test]
fn qoder_global_and_cn_editions_are_both_built_in() {
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
@@ -945,6 +1042,46 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
.write(&file)
.unwrap();
set_builtin_env(
dir.path(),
None,
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".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"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
}
#[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()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+8
Переглянути файл
@@ -537,6 +537,14 @@ fn install_entry_with(
return Err(e);
}
};
let github_account = (entry.id == "copilot")
.then(|| CustomAgent::read(&file).ok())
.flatten()
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
let mut env = env;
if let Some(account) = github_account {
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
}
let agent = CustomAgent {
name: Some(entry.name.clone()),
driver: Driver::Acp,
+33 -1
Переглянути файл
@@ -1,6 +1,7 @@
//! Claude Code's slash commands on disk, for completion before (or without) a session:
//! skills (`.claude/skills/<dir>/SKILL.md`) and custom commands (`.claude/commands/**/*.md`)
//! of the working directory and every directory above it, then the user's `~/.claude`.
//! of the working directory and every directory above it, then the user's `~/.claude`; and
//! the skills of a Hermes profile (`<profile>/skills`).
use crate::{AgentCommand, AgentCommandSource};
use std::collections::HashSet;
@@ -34,6 +35,19 @@ pub(crate) fn discover(cwd: &Path, home: Option<&Path>) -> Vec<AgentCommand> {
out
}
/// The skills of a Hermes profile: `<profile>/skills/<skill>` and `<profile>/skills/<category>/<skill>`;
/// the first of a name wins.
pub(crate) fn hermes(profile: &Path) -> Vec<AgentCommand> {
let root = profile.join("skills");
let mut found = skills(&root);
for category in sorted(&root).into_iter().filter(|p| !p.join("SKILL.md").exists()) {
found.extend(skills(&category));
}
let mut seen = HashSet::new();
found.retain(|c| seen.insert(c.name.clone()));
found
}
/// `first` (the agent's own list) plus the commands of `more` it lacks.
pub(crate) fn merge(first: Vec<AgentCommand>, more: Vec<AgentCommand>) -> Vec<AgentCommand> {
let mut out = first;
@@ -256,6 +270,24 @@ mod tests {
);
}
#[test]
fn hermes_skills_flat_and_in_categories() {
let tmp = tempfile::tempdir().unwrap();
let profile = tmp.path();
assert!(hermes(profile).is_empty());
for dir in ["skills/plan", "skills/dev/review", "skills/dev/plan", "skills/empty"] {
std::fs::create_dir_all(profile.join(dir)).unwrap();
}
for dir in ["skills/plan", "skills/dev/review", "skills/dev/plan"] {
std::fs::write(profile.join(dir).join("SKILL.md"), "---\ndescription: d\n---\n").unwrap();
}
let names: Vec<_> = hermes(profile).into_iter().map(|c| (c.name, c.source)).collect();
assert_eq!(
names,
[("plan".to_owned(), AgentCommandSource::Skill), ("review".to_owned(), AgentCommandSource::Skill)]
);
}
#[test]
fn nothing_without_claude_dirs() {
let tmp = tempfile::tempdir().unwrap();
+101 -2
Переглянути файл
@@ -909,6 +909,27 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
mgr3.shutdown();
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn hermes_profiles_complete_their_own_skills() {
let tmp = tempfile::tempdir().unwrap();
let skill = |dir: &str, name: &str| {
let dir = tmp.path().join(dir).join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("SKILL.md"), format!("---\nname: {name}\ndescription: d\n---\n")).unwrap();
};
skill(".hermes/skills", "plan");
skill(".hermes/profiles/dom/skills/home", "lights");
std::fs::write(tmp.path().join(".hermes/profiles/dom/config.yaml"), "").unwrap();
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), Arc::new(FakeAgent::default()));
let names = |c: Vec<AgentCommand>| c.into_iter().map(|c| c.name).collect::<Vec<_>>();
assert!(names(mgr.commands("hermes", None).await.unwrap()).contains(&"plan".to_owned()));
let dom = names(mgr.commands("hermes-dom", None).await.unwrap());
assert!(dom.contains(&"lights".to_owned()) && !dom.contains(&"plan".to_owned()));
assert!(!names(mgr.commands("claude", None).await.unwrap()).contains(&"plan".to_owned()));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
let tmp = tempfile::tempdir().unwrap();
@@ -1877,6 +1898,32 @@ async fn real_claude_task_in_a_worktree() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn hermes_session_info_names_the_task_and_counts_compressions() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
// "again" ends the turn at once; the default prompt waits for a permission answer.
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let info = |title: &str, depth: u32| {
json!({"sessionUpdate": "session_info_update", "title": title, "updatedAt": "2026-11-18T18:35:32.068362+00:00",
"_meta": {"hermes": {"sessionProvenance": {"sessionKind": "root", "parentHermesSessionId": null,
"compressionDepth": depth}}}})
};
handle.on_update(None, &info("Make a 3-step plan and carry it out: 1) list the…", 0));
handle.on_update(None, &info("List files and edit notes.txt", 0));
let t = handle.state.lock().task.clone();
assert_eq!(t.title, "List files and edit notes.txt", "the agent's latest title wins");
assert_eq!(t.stats.compressions, 0);
handle.on_update(None, &info("List files and edit notes.txt", 2));
assert_eq!(handle.state.lock().task.stats.compressions, 2);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn renamed_titles_survive_updates_forks_and_restart() {
let tmp = tempfile::tempdir().unwrap();
@@ -2286,6 +2333,56 @@ async fn idle_model_switches_discover_controls_and_no_control_models_without_ano
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_without_a_model_option_can_select_from_a_recovered_catalog() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
]);
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude-acp".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let spec = mgr.shared.spec("claude-acp").unwrap();
let (_, flight) = mgr.shared.paths.catalogs.request(&mgr.shared, spec, true, None);
if let Some(mut ready) = flight {
tokio::time::timeout(Duration::from_secs(5), async {
while !*ready.borrow_and_update() {
ready.changed().await.unwrap();
}
})
.await
.unwrap();
}
{
let task = mgr.task(&task.id).unwrap();
let mut state = task.state.lock();
state.task.config.retain(|option| option.category.as_deref() != Some("model"));
state.task.model = Some("stale-model".into());
}
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
let task = mgr.task(&task.id).unwrap();
{
let state = task.state.lock();
assert_eq!(state.task.model.as_deref(), Some("small"));
let model = state.task.config.iter().find(|option| option.category.as_deref() == Some("model")).unwrap();
assert_eq!(model.current.as_deref(), Some("small"));
assert!(model.values.iter().any(|value| value.value == "small"));
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_model_discovery_failure_restores_the_previous_choice_without_claiming_no_controls() {
let tmp = tempfile::tempdir().unwrap();
@@ -3531,11 +3628,13 @@ fn streamed_text_is_sent_as_appends() {
);
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other"));
assert!(matches!(replaced, AgentEvent::Entry { .. }), "text that doesn't extend the sent text is sent whole");
let thought = entry_event("t", &mut streamed, None, 4, &AgentEntry::Thought { text: "hmm…".into() });
let thought = AgentEntry::Thought { text: "hmm…".into(), started_ms: None };
let thought = entry_event("t", &mut streamed, None, 4, &thought);
assert!(matches!(thought, AgentEvent::Entry { index: 4, .. }), "a new message starts whole");
let tool = AgentEntry::Error { message: "x".into() };
entry_event("t", &mut streamed, None, 4, &tool);
let again = entry_event("t", &mut streamed, None, 4, &AgentEntry::Thought { text: "hmm… ok".into() });
let again = AgentEntry::Thought { text: "hmm… ok".into(), started_ms: None };
let again = entry_event("t", &mut streamed, None, 4, &again);
assert!(matches!(again, AgentEvent::Entry { .. }), "an entry replaced by another kind forgets its text");
let long = "é".repeat(5000);
+41 -4
Переглянути файл
@@ -85,6 +85,8 @@ impl Timeline {
locations: locations(update.get("locations")),
output: None,
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
};
let index = match self.tools.get(&id) {
Some(&i) => {
@@ -134,17 +136,22 @@ impl Timeline {
fn append_text(&mut self, thought: bool, text: &str) -> usize {
match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text),
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
_ => {
let text = text.to_owned();
return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
return self.push(if thought {
AgentEntry::Thought { text, started_ms: Some(crate::now_ms()) }
} else {
AgentEntry::Agent { text }
});
}
}
self.entries.len() - 1
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
};
@@ -156,6 +163,9 @@ impl Timeline {
}
if let Some(s) = tool_status(update.get("status")) {
*status = s;
if matches!(s, AgentToolStatus::Completed | AgentToolStatus::Failed) && ended_ms.is_none() {
*ended_ms = Some(crate::now_ms());
}
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
@@ -183,6 +193,11 @@ impl Timeline {
}
}
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
@@ -432,11 +447,14 @@ mod tests {
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
t.apply(&chunk("again"));
// The thought's start is the clock's: it is there, and the rest compares exactly.
let AgentEntry::Thought { started_ms, .. } = &mut t.entries[1] else { panic!("{:?}", t.entries) };
assert!(started_ms.take().is_some());
assert_eq!(
t.entries,
vec![
AgentEntry::Agent { text: "Hello".into() },
AgentEntry::Thought { text: "hmm".into() },
AgentEntry::Thought { text: "hmm".into(), started_ms: None },
AgentEntry::Agent { text: "again".into() },
]
);
@@ -528,6 +546,25 @@ mod tests {
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
}
#[test]
fn a_hermes_terminal_call_keeps_its_command_and_times() {
let text = |t: &str| serde_json::json!([{"type": "content", "content": {"type": "text", "text": t}}]);
let mut t = Timeline::default();
t.apply(&serde_json::json!({"sessionUpdate": "tool_call", "toolCallId": "tc-0b98b5e30a28",
"kind": "execute", "title": "terminal: echo ok + 2 commands", "locations": [],
"content": text("$ echo ok >> notes.txt && wc -l notes.txt")}));
let AgentEntry::Tool { started_ms, ended_ms, .. } = &t.entries[0] else { panic!() };
assert!(started_ms.is_some() && ended_ms.is_none());
t.apply(&serde_json::json!({"sessionUpdate": "tool_call_update", "toolCallId": "tc-0b98b5e30a28",
"kind": "execute", "status": "completed",
"content": text("terminal result\n- **output:** 3 notes.txt\n- **exit_code:** 0")}));
let AgentEntry::Tool { output, status, ended_ms, .. } = &t.entries[0] else { panic!() };
assert_eq!(*status, AgentToolStatus::Completed);
assert!(ended_ms.is_some());
let expected = "$ echo ok >> notes.txt && wc -l notes.txt\nterminal result\n- **output:** 3 notes.txt\n";
assert_eq!(output.as_deref(), Some(format!("{expected}- **exit_code:** 0").as_str()));
}
#[test]
fn long_output_keeps_its_tail() {
let s = tail("é".repeat(MAX_OUTPUT));
+3 -4
Переглянути файл
@@ -236,10 +236,9 @@ fn classpath(
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &target.top.dir);
let status = ProcCommand::new(&target.top.command)
.args(&args)
.envs(&target.top.env)
.current_dir(&top_dir)
let mut command = ProcCommand::new(&target.top.command);
command.args(&args).envs(&target.top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
+88 -11
Переглянути файл
@@ -2020,11 +2020,25 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
label: name.clone(),
});
}
// Built-in coordinates: the POM's own element, else the first ancestor declaring one.
if let Some(key) = name.strip_prefix("project.") {
if !matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") {
return None; // `project.basedir`, `project.build.directory`… have no element.
// Built-in coordinates (`project.artifactId`, and the bare `@artifactId@`
// shorthand resource filtering resolves the same way): the POM's own element,
// else the first ancestor declaring one. Any other name under `project.` is a
// custom property (`project.port`, `project.servlet.path`), which the
// `<properties>` lookup below resolves.
let built_in = match name.strip_prefix("project.") {
Some(key) if matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") => Some(key),
// `project.basedir`, `project.build.directory`… have no element of their own.
Some(_) => None,
None if matches!(name.as_str(), "groupId" | "artifactId" | "version" | "packaging" | "name") => {
// The bare shorthand of a built-in; a custom property of that name wins.
if let Some(found) = properties_target(&chain, &name, &resolver) {
return Some(found);
}
Some(name.as_str())
}
None => None,
};
if let Some(key) = built_in {
for (p, text) in &chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let Some(e) = root.child(key).filter(|e| !e.text.trim().is_empty()) else { continue };
@@ -2037,30 +2051,34 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
}
return None;
}
// A property of `<properties>`: the first POM of the chain (child-first) that
// declares it, at project level or in an active profile.
for (p, text) in &chain {
properties_target(&chain, &name, &resolver)
}
/// A property of `<properties>`: the first POM of the chain (child-first) that
/// declares it, at project level or in an active profile.
fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &Resolver) -> Option<PomGoto> {
for (p, text) in chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let active: Vec<String> = parse_pom(text)
.map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect())
.unwrap_or_default();
// Project level first, then the first active profile declaring the property.
let e = root.child("properties").and_then(|props| props.child(&name)).or_else(|| {
let e = root.child("properties").and_then(|props| props.child(name)).or_else(|| {
root.list("profiles", "profile")
.into_iter()
.find(|profile| {
active.contains(&profile.child("id").map(|id| id.text.trim().to_owned()).unwrap_or_default())
&& profile.child("properties").and_then(|props| props.child(&name)).is_some()
&& profile.child("properties").and_then(|props| props.child(name)).is_some()
})?
.child("properties")?
.child(&name)
.child(name)
});
if let Some(e) = e {
return Some(PomGoto {
path: p.clone(),
range: range_of(text, e),
kind: PomGotoKind::Property,
label: name.clone(),
label: name.to_owned(),
});
}
}
@@ -3086,6 +3104,65 @@ mod tests {
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
}
#[test]
fn a_custom_project_property_is_found_like_a_plain_one() {
let text = format!(
r#"{CHILD_HEADER}<properties>
<project.port>8001</project.port>
</properties>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
<version>${{project.port}}</version>
</dependency>
</dependencies>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
let goto = goto_declaration(&text, path, at(&text, "${project.port}"), None).unwrap();
assert_eq!(goto.kind, PomGotoKind::Property);
assert_eq!(goto.label, "project.port");
assert_eq!(goto.path, path);
let from = text.find("<project.port>").unwrap();
let to = text.find("</project.port>").unwrap() + "</project.port>".len();
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
// `${project.basedir}` has no element and no custom property: still nothing.
let basedir = text.replace("${project.port}", "${project.basedir}");
assert_eq!(goto_declaration(&basedir, path, at(&basedir, "${project.basedir}"), None), None);
}
#[test]
fn the_bare_builtin_shorthand_resolves_to_the_coordinate_and_a_custom_property_wins() {
let text = format!(
r#"{CHILD_HEADER}<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
</dependency>
</dependencies>
<properties>
<groupId>custom</groupId>
</properties>
<description>${{artifactId}}-${{groupId}} docs</description>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
// `@artifactId@` in a filtered resource resolves to the own coordinate.
let goto = goto_declaration(&text, path, at(&text, "${artifactId}"), None).unwrap();
assert_eq!(goto.label, "artifactId");
let from = text.find("<artifactId>app").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
// A custom property of the bare name wins over the shorthand. The click
// sits inside the reference: the second one's `$` is behind the first's
// closing `}`, which `property_ref_at` does not take for the `$` itself.
let goto = goto_declaration(&text, path, at(&text, "groupId} docs"), None).unwrap();
assert_eq!(goto.label, "groupId");
let from = text.find("<groupId>custom").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
}
#[test]
fn an_inherited_property_reference_finds_its_definition_in_the_parent_pom() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -89,6 +89,8 @@ pub enum IdeEvent {
DocDirty {
doc: DocId,
dirty: bool,
/// Text version when this transition occurred, including when it was saved.
version: u32,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
-13
Переглянути файл
@@ -100,16 +100,6 @@ 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,
/// While the agent works, playful words fill the pauses in what it reports.
pub playful_status: bool,
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
/// from the start.
pub playful_after_seconds: u32,
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
/// the built-in ones of that activity; an empty list keeps its status factual.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, Vec<String>>)]
pub playful_words: BTreeMap<String, Vec<String>>,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -152,9 +142,6 @@ impl Default for AgentSettings {
fold_turns: true,
smooth_text: true,
fit_window_width: false,
playful_status: false,
playful_after_seconds: 0,
playful_words: BTreeMap::new(),
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
+10 -1
Переглянути файл
@@ -217,7 +217,8 @@ impl ManageConnection for MssqlConnectionManager {
let row = client.simple_query("SELECT DB_NAME()").await?.into_row().await?;
let default = row
.and_then(|r| r.get::<&str, _>(0).map(str::to_owned))
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
// Statements that `USE` another database must not move the pooled connection for good.
.map(|db| format!("USE {}", crate::sql::quote_ident(DbDriver::SqlServer, &db)));
Ok(MssqlConnection(Some(client), Context::new(default)))
}
@@ -748,6 +749,14 @@ impl Pool {
}
/// The keep-alive ping (Oracle needs a FROM clause).
/// Keep-alive: one cheap round trip on the session.
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
pub fn ping_sql(&self) -> &'static str {
match self {
Pool::Oracle(_) => "SELECT 1 FROM DUAL",
+38
Переглянути файл
@@ -458,6 +458,44 @@ impl JdbcPool {
}
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;
}
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::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;
}
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()),
+12 -7
Переглянути файл
@@ -379,8 +379,8 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
loop {
tick.tick().await;
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
if let Err(e) = p.rows(p.ping_sql(), 1).await {
tracing::debug!("keep-alive: {}", e.message);
if let Err(e) = p.ping().await {
tracing::info!("keep-alive: {}", e.message);
}
}
});
@@ -847,12 +847,12 @@ impl DbManager {
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().contains_key(id)
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().keys().cloned().collect()
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
@@ -862,8 +862,13 @@ impl DbManager {
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
if let Some(p) = self.pools.lock().get(id) {
return Ok(p.clone());
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
@@ -917,7 +922,7 @@ impl DbManager {
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect();
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
+8 -6
Переглянути файл
@@ -442,7 +442,8 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
DbDriver::Sqlite | DbDriver::Jdbc => None,
DbDriver::Postgres => Some("SELECT current_schema()"),
DbDriver::Mysql => Some("SELECT DATABASE()"),
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
// The login's default schema; the database is the console's target (IDEA's `database.schema`).
DbDriver::SqlServer => Some("SELECT SCHEMA_NAME()"),
DbDriver::Oracle => Some("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL"),
DbDriver::Snowflake => Some("SELECT CURRENT_SCHEMA()"),
}
@@ -450,12 +451,13 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
/// The statement that makes unqualified names resolve in `schema` on the
/// connection that runs it (a query console's active schema; `None`: the driver
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs, and SQL Server
/// cannot change a session's default schema, so its console schema only scopes resolution).
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
match driver {
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc | DbDriver::SqlServer => None,
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Mysql => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
DbDriver::Snowflake => Some(format!("USE SCHEMA {}", quote_ident(driver, schema))),
}
@@ -1030,7 +1032,7 @@ mod tests {
assert_eq!(quote_ident(DbDriver::SqlServer, "a]b"), "[a]]b]");
assert_eq!(qualified(DbDriver::SqlServer, "dbo", "t"), "[dbo].[t]");
assert_eq!(qualified(DbDriver::SqlServer, "", "t"), "[t]");
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT DB_NAME()"));
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT SCHEMA_NAME()"));
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
@@ -1149,7 +1151,7 @@ mod tests {
fn schema_switch_statement_per_dialect() {
assert_eq!(use_schema(DbDriver::Postgres, "app data"), Some("SET search_path TO \"app data\"".into()));
assert_eq!(use_schema(DbDriver::Mysql, "a`b"), Some("USE `a``b`".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "app] data"), Some("USE [app]] data]".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "dbo"), None);
assert_eq!(use_schema(DbDriver::Postgres, "a\"b"), Some("SET search_path TO \"a\"\"b\"".into()));
assert_eq!(use_schema(DbDriver::Oracle, "a\"b"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"a\"\"b\"".into()));
assert!(sqlserver_databases().contains("state = 0 AND HAS_DBACCESS(name) = 1"));
+33
Переглянути файл
@@ -213,3 +213,36 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
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<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
let source = DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: "jdbc:fixture:".into(),
..Default::default()
};
db.save_sources(vec![source]).await?;
let cancel = CancellationToken::new();
db.execute("test", "first", 1, &cancel).await?;
// The fixture's session reports itself invalid after "drop", like a connection a proxy reset.
assert!(db.execute("test", "drop", 1, &cancel).await.unwrap_err().message.contains("connection reset"));
assert!(!db.is_connected("test"), "a lost session is no longer listed as connected");
assert_eq!(db.execute("test", "after reconnect", 1, &cancel).await?.affected, Some(1.0));
assert!(db.is_connected("test"));
db.disconnect("test").await;
Ok(())
}
+382 -9
Переглянути файл
@@ -7,9 +7,10 @@
use crate::{
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
DockerEndpoint, DockerImage, DockerNetwork, DockerObject, DockerSnapshot, DockerVolume, split_csv,
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
DockerSnapshot, DockerVolume, split_csv,
};
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::io::{Read, Write};
@@ -193,9 +194,15 @@ fn request(addr: &Address, method: &str, path: &str, timeout: Duration) -> IdeRe
read_response(&mut conn)
}
/// Reads an HTTP/1.1 response: head until `\r\n\r\n`, then the body per its
/// framing (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
/// A response's status line and body framing.
struct Head {
status: u16,
chunked: bool,
length: Option<usize>,
}
/// Reads an HTTP/1.1 response head until `\r\n\r\n`.
fn read_head(stream: &mut impl Read) -> IdeResult<Head> {
let mut head: Vec<u8> = Vec::new();
let mut byte = [0u8; 1];
loop {
@@ -228,16 +235,27 @@ fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
length = value.parse().ok();
}
}
let body = if chunked {
Ok(Head { status, chunked, length })
}
/// Reads an HTTP/1.1 response: its head, then the body per its framing
/// (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
let head = read_head(stream)?;
let body = read_body(stream, &head)?;
Ok(Response { status: head.status, body })
}
fn read_body(stream: &mut impl Read, head: &Head) -> IdeResult<Vec<u8>> {
Ok(if head.chunked {
read_chunked(stream)?
} else if let Some(n) = length {
} else if let Some(n) = head.length {
read_exact_n(stream, n)?
} else {
let mut body = Vec::new();
stream.read_to_end(&mut body)?;
body
};
Ok(Response { status, body })
})
}
/// Reads one `\n`-terminated line (returned without it).
@@ -482,6 +500,292 @@ pub(crate) fn inspect(
})())
}
/// The processes running in a container (`docker top`).
pub(crate) fn container_top(ep: &DockerEndpoint, id: &str, timeout: Duration) -> Option<IdeResult<DockerProcessList>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/containers/{}/top", path_segment(id)), timeout)?)?;
serde_json::from_str::<ApiTop>(&body)
.map(|t| DockerProcessList { titles: t.titles, processes: t.processes })
.map_err(|e| IdeError::internal(format!("the Docker daemon's process list is not JSON: {e}")))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiTop {
titles: Vec<String>,
processes: Vec<Vec<String>>,
}
/// An image's layers, newest first (`docker image history`).
pub(crate) fn image_history(
ep: &DockerEndpoint,
id: &str,
timeout: Duration,
) -> Option<IdeResult<Vec<DockerImageLayer>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/images/{}/history", path_segment(id)), timeout)?)?;
let layers = serde_json::from_str::<Vec<ApiLayer>>(&body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's image history is not JSON: {e}")))?;
Ok(map_layers(layers, unix_now()))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiLayer {
id: String,
created: i64,
created_by: String,
size: i64,
comment: String,
}
fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
layers
.into_iter()
.map(|l| DockerImageLayer {
id: l.id,
created_by: l.created_by,
size: human_size(l.size),
created_since: human_duration((now - l.created).max(0)),
created_at: unix_utc(l.created),
comment: l.comment,
})
.collect()
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
/// How often a log stream that has nothing to read checks for cancellation.
const LOG_POLL: Duration = Duration::from_millis(200);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerInspect {
config: ApiContainerConfig,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerConfig {
tty: bool,
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// from `ep`'s daemon until they end or `cancel` fires.
#[allow(clippy::too_many_arguments)]
pub(crate) fn logs(
ep: &DockerEndpoint,
id: &str,
tail: u32,
follow: bool,
timestamps: bool,
timeout: Duration,
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> Option<IdeResult<()>> {
let addr = address(ep)?;
Some((|| {
// A TTY container's log is one raw stream; otherwise it is framed per stream.
let body = check(request(&addr, "GET", &format!("/containers/{}/json", path_segment(id)), timeout)?)?;
let tty = serde_json::from_str::<ApiContainerInspect>(&body).map(|c| c.config.tty).unwrap_or(false);
let path = format!(
"/containers/{}/logs?stdout=1&stderr=1&tail={tail}&follow={}&timestamps={}",
path_segment(id),
u8::from(follow),
u8::from(timestamps),
);
let mut conn = Conn::connect(&addr, timeout)?;
conn.write_all(
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n")
.as_bytes(),
)?;
let head = read_head(&mut conn)?;
if !(200..300).contains(&head.status) {
let body = read_body(&mut conn, &head)?;
check(Response { status: head.status, body })?;
}
conn.set_timeouts(LOG_POLL);
let mut decoder = LogDecoder::new(&head, tty);
let mut buf = [0u8; 8192];
while !decoder.done() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match conn.read(&mut buf) {
Ok(0) => break,
Ok(n) => decoder.feed(&buf[..n], &mut |line| on_line(line))?,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
) => {}
Err(e) => return Err(e.into()),
}
}
decoder.finish(&mut |line| on_line(line));
Ok(())
})())
}
/// Turns a log response body, as it arrives, into lines: undoes the chunked
/// transfer encoding, then the per-stream frames (8-byte header: stream, 3 zero
/// bytes, big-endian length) unless the container has a TTY.
struct LogDecoder {
body: BodyFraming,
tty: bool,
header: Vec<u8>,
frame_left: usize,
frame_stderr: bool,
/// Partial lines of stdout and stderr.
partial: [Vec<u8>; 2],
}
enum BodyFraming {
Chunked { state: ChunkState, line: Vec<u8> },
Length(usize),
Close,
}
#[derive(Clone, Copy, PartialEq)]
enum ChunkState {
Size,
Data(usize),
DataEnd,
Trailer,
Done,
}
impl LogDecoder {
fn new(head: &Head, tty: bool) -> Self {
let body = if head.chunked {
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
} else if let Some(n) = head.length {
BodyFraming::Length(n)
} else {
BodyFraming::Close
};
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
}
fn done(&self) -> bool {
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
}
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
let mut payload = Vec::new();
match &mut self.body {
BodyFraming::Close => payload.extend_from_slice(bytes),
BodyFraming::Length(left) => {
let take = (*left).min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
*left -= take;
}
BodyFraming::Chunked { state, line } => {
while !bytes.is_empty() {
match *state {
ChunkState::Done => break,
ChunkState::Data(n) => {
let take = n.min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
*state = if take == n { ChunkState::DataEnd } else { ChunkState::Data(n - take) };
}
_ => {
let b = bytes[0];
bytes = &bytes[1..];
if b != b'\n' {
if b != b'\r' {
line.push(b);
}
continue;
}
let text = String::from_utf8_lossy(line).into_owned();
line.clear();
*state = match *state {
ChunkState::Size => {
let size = text.split(';').next().unwrap_or_default().trim();
match usize::from_str_radix(size, 16) {
Ok(0) => ChunkState::Trailer,
Ok(n) => ChunkState::Data(n),
Err(_) => {
return Err(IdeError::internal(
"the Docker daemon answered with a malformed chunked response",
));
}
}
}
ChunkState::DataEnd => ChunkState::Size,
_ if text.is_empty() => ChunkState::Done,
other => other,
};
}
}
}
}
}
self.frames(&payload, emit);
Ok(())
}
fn frames(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
if self.tty {
self.lines(false, bytes, emit);
return;
}
while !bytes.is_empty() {
if self.frame_left == 0 {
let take = (8 - self.header.len()).min(bytes.len());
self.header.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
if self.header.len() == 8 {
self.frame_stderr = self.header[0] == 2;
self.frame_left =
u32::from_be_bytes([self.header[4], self.header[5], self.header[6], self.header[7]]) as usize;
self.header.clear();
}
continue;
}
let take = self.frame_left.min(bytes.len());
self.lines(self.frame_stderr, &bytes[..take], emit);
self.frame_left -= take;
bytes = &bytes[take..];
}
}
fn lines(&mut self, stderr: bool, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
let partial = &mut self.partial[usize::from(stderr)];
for &b in bytes {
if b == b'\n' {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
} else {
partial.push(b);
}
}
}
/// Emits the last lines that ended without a newline.
fn finish(&mut self, emit: &mut dyn FnMut(DockerLogLine)) {
for stderr in [false, true] {
let partial = &mut self.partial[usize::from(stderr)];
if !partial.is_empty() {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
}
}
}
}
fn line_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes.strip_suffix(b"\r").unwrap_or(bytes)).into_owned()
}
/// One URL path segment, percent-encoded so an id cannot change the path.
fn path_segment(id: &str) -> String {
let mut out = String::with_capacity(id.len());
@@ -817,6 +1121,75 @@ mod tests {
assert!(read_response(&mut &garbage[..]).is_err());
}
/// Feeds `body` one byte at a time, as a slow connection delivers it.
fn decode(head: Head, tty: bool, body: &[u8]) -> (Vec<(bool, String)>, bool) {
let mut lines = Vec::new();
let mut decoder = LogDecoder::new(&head, tty);
for b in body {
decoder.feed(std::slice::from_ref(b), &mut |l| lines.push((l.stderr, l.text))).unwrap();
}
let done = decoder.done();
decoder.finish(&mut |l| lines.push((l.stderr, l.text)));
(lines, done)
}
fn frame(stream: u8, text: &str) -> Vec<u8> {
let mut f = vec![stream, 0, 0, 0];
f.extend((text.len() as u32).to_be_bytes());
f.extend(text.as_bytes());
f
}
#[test]
fn engine_image_history_reads_like_the_cli() {
let layers: Vec<ApiLayer> = serde_json::from_str(
r#"[{"Id":"sha256:abc","Created":1000,"CreatedBy":"CMD [\"python3\"]","Size":20500,"Comment":"buildkit","Tags":["py:3"]},
{"Id":"<missing>","Created":940,"CreatedBy":"RUN x","Size":0,"Comment":""}]"#,
)
.unwrap();
let rows = map_layers(layers, 1000 + 2 * 7 * 86_400);
assert_eq!(
rows.iter().map(|l| (l.id.as_str(), l.size.as_str(), l.created_since.as_str())).collect::<Vec<_>>(),
[("sha256:abc", "20.5kB", "2 weeks ago"), ("<missing>", "0B", "2 weeks ago")]
);
assert_eq!(rows[0].created_by, "CMD [\"python3\"]");
let top: ApiTop = serde_json::from_str(r#"{"Titles":["PID","CMD"],"Processes":[["1","sh"]]}"#).unwrap();
assert_eq!(
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
}
#[test]
fn container_logs_split_into_stream_lines_across_chunks_and_frames() {
// Frames split mid-line, a CRLF line, and a stderr line between stdout parts.
let mut framed = frame(1, "tick 1\r\ntick");
framed.extend(frame(2, "oops\n"));
framed.extend(frame(1, " 2\nlast"));
let mut chunked = Vec::new();
for part in framed.chunks(7) {
chunked.extend(format!("{:x}\r\n", part.len()).as_bytes());
chunked.extend(part);
chunked.extend(b"\r\n");
}
chunked.extend(b"0\r\n\r\n");
let (lines, done) = decode(Head { status: 200, chunked: true, length: None }, false, &chunked);
assert!(done);
let expected = [(false, "tick 1"), (true, "oops"), (false, "tick 2"), (false, "last")];
assert_eq!(lines, expected.map(|(e, t)| (e, t.to_owned())));
// A TTY container's log is one raw stream; the body may end with the connection.
let (lines, done) = decode(Head { status: 200, chunked: false, length: None }, true, b"a\r\nb\n");
assert!(!done);
assert_eq!(lines, [(false, "a".to_owned()), (false, "b".to_owned())]);
// A Content-Length body ends after its length.
let body = frame(1, "one\n");
let (lines, done) = decode(Head { status: 200, chunked: false, length: Some(body.len()) }, false, &body);
assert!(done);
assert_eq!(lines, [(false, "one".to_owned())]);
}
#[test]
fn daemon_errors_carry_their_message() {
let resp = Response { status: 404, body: br#"{"message":"No such container: missing"}"#.to_vec() };
+15
Переглянути файл
@@ -287,6 +287,11 @@ fn check_id(id: &str) -> IdeResult<&str> {
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(layers) = engine::image_history(ep, id, QUICK)
{
return layers;
}
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
@@ -294,6 +299,11 @@ pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImage
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(processes) = engine::container_top(ep, id, QUICK)
{
return processes;
}
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
@@ -316,6 +326,11 @@ pub fn logs(
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> IdeResult<()> {
if docker_executable().is_none()
&& let Some(streamed) = engine::logs(ep, id, tail, follow, timestamps, QUICK, cancel, on_line)
{
return streamed;
}
let tail = tail.to_string();
let mut args = vec!["logs", "--tail", &tail];
if follow {
+11
Переглянути файл
@@ -33,6 +33,16 @@ pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider
Ok(providers)
}
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
#[command(trust = trusted)]
pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<ide_agent::hermes::HermesProfile>> {
host.require_trust(window)?;
let root = ide_agent::hermes::root(dirs::home_dir().as_deref());
tokio::task::spawn_blocking(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default())
.await
.map_err(join_err)
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
#[command(trust = trusted)]
pub fn agent_refresh_models(
@@ -1075,6 +1085,7 @@ ide_command::domain!(
agent_external_sessions,
agent_fork,
agent_grouped_changes,
agent_hermes_profiles,
agent_import_session,
agent_mcp_discover_sources,
agent_mcp_import,
+28 -6
Переглянути файл
@@ -406,15 +406,16 @@ impl Proc {
}
}
/// What it printed since the last call, each stream at most `max` bytes.
/// What it printed since the last call, each stream at most `max` bytes. The status
/// comes with the last chunk only: once it ended, its pipes reached the end and
/// nothing is left to read, so a caller can stop at the first chunk that has one.
fn chunk(&self, max: usize) -> ProcessChunk {
let mut state = self.state.lock();
let eof = state.readers == 0;
ProcessChunk {
stdout: take_text(&mut state.stdout, max, eof),
stderr: take_text(&mut state.stderr, max, eof),
status: state.status,
}
let stdout = take_text(&mut state.stdout, max, eof);
let stderr = take_text(&mut state.stderr, max, eof);
let drained = eof && state.stdout.is_empty() && state.stderr.is_empty();
ProcessChunk { stdout, stderr, status: state.status.filter(|_| drained) }
}
}
@@ -4126,6 +4127,27 @@ mod tests {
api.release_process(id);
}
#[cfg(unix)]
#[test]
fn the_status_comes_with_the_last_of_the_output() {
let tmp = tempfile::tempdir().unwrap();
let api = shell_api(tmp.path());
let token = CancellationToken::new();
let id = api.start_process(shell("printf 'abcdefghij'; printf 'xyz' >&2"), None, None).unwrap();
let first = api.wait_process(id, 4, Duration::from_secs(5), &token).unwrap();
assert_eq!((first.stdout.as_str(), first.stderr.as_str(), first.status), ("abcd", "xyz", None));
let mut stdout = first.stdout;
let status = loop {
let chunk = api.poll_process(id, 4).unwrap();
stdout.push_str(&chunk.stdout);
if let Some(status) = chunk.status {
break status;
}
};
assert_eq!((stdout.as_str(), status), ("abcdefghij", 0));
api.release_process(id);
}
#[test]
fn programs_run_only_as_approved() {
let tmp = tempfile::tempdir().unwrap();
+16 -1
Переглянути файл
@@ -65,8 +65,23 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P
/// The client for the current proxy settings, rebuilt when they change.
pub fn shared() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
cached_client(&CLIENT, build)
}
/// The client the HTTP Client executes requests with: redirects off, `exec`
/// follows them by hand — that is what lets a `POST` stay a `POST` on a
/// 301/302 and puts the redirect chain into the response.
pub fn shared_without_redirects() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()))
}
fn cached_client(
slot: &Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>>,
build: fn(&ProxySettings) -> IdeResult<reqwest::Client>,
) -> IdeResult<reqwest::Client> {
let proxy = ide_core::proxy_settings::proxy();
let mut cached = CLIENT.lock();
let mut cached = slot.lock();
if let Some((settings, client)) = cached.as_ref()
&& **settings == *proxy
{
+288 -15
Переглянути файл
@@ -13,6 +13,19 @@ use std::time::Instant;
/// Bodies above this are cut (the full size is still reported).
pub const MAX_BODY: usize = 16 * 1024 * 1024;
/// Redirects followed per request; beyond this the redirect response itself is
/// returned (IntelliJ's HTTP Client follows the same number).
pub const MAX_REDIRECTS: usize = 50;
/// Responses whose `Location` is followed: 301, 302, 303, 307 and 308, the set
/// IntelliJ's HTTP Client redirects on.
const REDIRECT_STATUSES: [u16; 5] = [301, 302, 303, 307, 308];
/// Request headers not re-sent to a redirect on another host. IntelliJ's HTTP
/// Client strips the same set and restores it when the redirect stays on the
/// original host.
const SENSITIVE_HEADERS: [&str; 5] = ["authorization", "cookie", "cookie2", "www-authenticate", "proxy-authorization"];
/// A request ready to send: variables substituted, includes read.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -24,6 +37,15 @@ pub struct PreparedRequest {
pub body: Option<String>,
}
/// One followed redirect: the response and the `Location` it pointed to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RedirectHop {
pub status: u16,
pub status_text: String,
pub location: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HttpResponse {
@@ -32,6 +54,9 @@ pub struct HttpResponse {
pub version: String,
pub headers: Vec<(String, String)>,
pub content_type: Option<String>,
/// Followed redirects, first hop first; empty when not redirected.
#[serde(default)]
pub redirects: Vec<RedirectHop>,
/// Body as text (lossy UTF-8); `None` for binary bodies.
pub body: Option<String>,
/// Size in bytes as received (after decompression).
@@ -128,25 +153,84 @@ fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
}
}
/// Sends `req`; cancelled when `cancel` fires.
/// The request for one hop: `req`'s headers and body against `url`, the
/// sensitive headers dropped when the redirect crosses to another host.
fn request_to(
client: &reqwest::Client,
method: &reqwest::Method,
req: &PreparedRequest,
body: Option<&str>,
original: &reqwest::Url,
url: &reqwest::Url,
) -> IdeResult<reqwest::Request> {
let same_host = url.host_str() == original.host_str();
let mut builder = client.request(method.clone(), url.clone());
for (k, v) in &req.headers {
if same_host || !SENSITIVE_HEADERS.iter().any(|s| k.eq_ignore_ascii_case(s)) {
builder = builder.header(k, v);
}
}
if let Some(body) = body {
builder = builder.body(body.to_owned());
}
builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))
}
/// Sends `request`; cancelled when `cancel` fires.
async fn send(
client: &reqwest::Client,
request: reqwest::Request,
cancel: &CancellationToken,
) -> IdeResult<reqwest::Response> {
let send = client.execute(request);
tokio::select! {
r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e))),
() = cancel.cancelled() => Err(IdeError::cancelled()),
}
}
/// Sends `req`, following redirects the way IntelliJ's HTTP Client does:
/// 301, 302, 303, 307 and 308 up to [`MAX_REDIRECTS`] times, `303` continuing
/// as `GET` without the body, the other statuses keeping the method and body —
/// so a `POST` redirected to `https` on the same host is re-sent as a `POST`.
/// Sensitive headers (Authorization, cookies, proxy credentials) are not
/// re-sent across hosts. The followed hops are reported in the response.
/// Cancelled when `cancel` fires.
pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeResult<HttpResponse> {
let client = crate::client::shared()?;
let client = crate::client::shared_without_redirects()?;
let method = reqwest::Method::from_bytes(req.method.as_bytes())
.map_err(|_| IdeError::invalid(format!("invalid method {}", req.method)))?;
let mut builder = client.request(method, &req.url);
for (k, v) in &req.headers {
builder = builder.header(k, v);
}
if let Some(body) = &req.body {
builder = builder.body(body.clone());
}
let request = builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
let original = req.url.parse::<reqwest::Url>().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
let mut url = original.clone();
let mut method = method;
let mut body = req.body.clone();
let mut redirects = Vec::new();
let started = Instant::now();
let send = client.execute(request);
let mut response = tokio::select! {
r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e)))?,
() = cancel.cancelled() => return Err(IdeError::cancelled()),
};
let mut response;
loop {
let request = request_to(&client, &method, req, body.as_deref(), &original, &url)?;
response = send(&client, request, cancel).await?;
let status = response.status();
if redirects.len() >= MAX_REDIRECTS || !REDIRECT_STATUSES.contains(&status.as_u16()) {
break;
}
let next = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|v| v.to_str().ok())
.and_then(|location| url.join(location).ok());
let Some(next) = next else { break };
redirects.push(RedirectHop {
status: status.as_u16(),
status_text: status.canonical_reason().unwrap_or("").to_owned(),
location: next.to_string(),
});
if status == reqwest::StatusCode::SEE_OTHER {
method = reqwest::Method::GET;
body = None;
}
url = next;
}
let ttfb = started.elapsed();
let status = response.status();
let version = format!("{:?}", response.version());
@@ -179,6 +263,7 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe
version,
headers,
content_type,
redirects,
body,
size: size as f64,
truncated: size > bytes.len(),
@@ -249,6 +334,47 @@ mod tests {
assert_eq!(url("GET https://api.test/cb?u=http://x\n"), "https://api.test/cb?u=http://x");
}
/// A loopback server answering each accepted connection with the next of
/// `responses`, returning every request as its head and body.
async fn scripted(responses: Vec<String>) -> (u16, tokio::task::JoinHandle<Vec<(String, String)>>) {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let handle = tokio::spawn(async move {
let mut seen = Vec::new();
for response in responses {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let (head, body) = loop {
let mut buffer = [0u8; 4096];
let read = socket.read(&mut buffer).await.unwrap();
assert!(read > 0, "request ended before its body");
request.extend_from_slice(&buffer[..read]);
let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else { continue };
let head = String::from_utf8_lossy(&request[..end]).into_owned();
let length: usize = head
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap())
})
.unwrap_or(0);
if request.len() >= end + 4 + length {
break (head, String::from_utf8_lossy(&request[end + 4..end + 4 + length]).into_owned());
}
};
seen.push((head, body));
socket.write_all(response.as_bytes()).await.unwrap();
}
seen
});
(port, handle)
}
fn response(status_line: &str, headers: &str, body: &str) -> String {
format!("HTTP/1.1 {status_line}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len())
}
#[tokio::test]
async fn sends_exact_environment_numbers_to_a_local_server() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -341,6 +467,7 @@ mod tests {
assert_eq!(r.status_text, "Created");
assert_eq!(r.body.as_deref(), Some("{\"ok\":true}"));
assert!(r.headers.iter().any(|(k, v)| k == "x-a" && v == "b"));
assert!(r.redirects.is_empty());
assert!(r.total_ms >= r.ttfb_ms);
}
@@ -369,4 +496,150 @@ mod tests {
let err = execute(&req, &cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test]
async fn post_keeps_method_and_body_on_301_302_307_308() {
for status_line in ["301 Moved Permanently", "302 Found", "307 Temporary Redirect", "308 Permanent Redirect"] {
let status: u16 = status_line[..3].parse().unwrap();
let (port, server) =
scripted(vec![response(status_line, "Location: /landing\r\n", ""), response("200 OK", "", "ok")]).await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://127.0.0.1:{port}/submit"),
headers: vec![("Content-Type".into(), "application/json".into())],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
let (head, body) = &seen[1];
assert_eq!(head.lines().next().unwrap(), "POST /landing HTTP/1.1", "{status_line}");
assert!(head.to_ascii_lowercase().contains("content-type: application/json"), "{head}");
assert_eq!(body, "{\"a\":1}", "{status_line}");
assert_eq!(r.status, 200, "{status_line}");
assert_eq!(r.body.as_deref(), Some("ok"), "{status_line}");
assert_eq!(
r.redirects,
vec![RedirectHop {
status,
status_text: status_line[4..].to_owned(),
location: format!("http://127.0.0.1:{port}/landing"),
}],
"{status_line}"
);
}
}
#[tokio::test]
async fn see_other_303_resends_as_get_without_the_body() {
let (port, server) =
scripted(vec![response("303 See Other", "Location: /after\r\n", ""), response("200 OK", "", "done")]).await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://127.0.0.1:{port}/submit"),
headers: vec![],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(seen[1].0.lines().next().unwrap(), "GET /after HTTP/1.1");
assert_eq!(seen[1].1, "");
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("done"));
assert_eq!(r.redirects[0].status, 303);
}
#[tokio::test]
async fn same_host_redirect_keeps_authorization() {
let (port, server) = scripted(vec![
response("301 Moved Permanently", "Location: /landing\r\n", ""),
response("200 OK", "", "ok"),
])
.await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/start"),
headers: vec![("Authorization".into(), "Bearer secret".into())],
body: None,
};
execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert!(seen[1].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen[1].0);
}
#[tokio::test]
async fn cross_host_redirect_keeps_the_method_but_drops_authorization() {
let (port_b, server_b) = scripted(vec![response("200 OK", "", "moved")]).await;
let (port_a, server_a) = scripted(vec![response(
"301 Moved Permanently",
&format!("Location: http://127.0.0.1:{port_b}/x\r\n"),
"",
)])
.await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://localhost:{port_a}/start"),
headers: vec![("Authorization".into(), "Bearer secret".into())],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen_a = server_a.await.unwrap();
let seen_b = server_b.await.unwrap();
assert!(seen_a[0].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen_a[0].0);
assert_eq!(seen_b[0].0.lines().next().unwrap(), "POST /x HTTP/1.1");
assert!(!seen_b[0].0.to_ascii_lowercase().contains("authorization"), "{}", seen_b[0].0);
assert_eq!(seen_b[0].1, "{\"a\":1}");
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("moved"));
assert_eq!(r.redirects.len(), 1);
}
#[tokio::test]
async fn redirects_beyond_the_limit_return_the_last_redirect_response() {
let responses = vec![response("301 Moved Permanently", "Location: /loop\r\n", ""); MAX_REDIRECTS + 1];
let (port, server) = scripted(responses).await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/start"),
headers: vec![],
body: None,
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(r.status, 301);
assert_eq!(r.status_text, "Moved Permanently");
assert_eq!(r.redirects.len(), MAX_REDIRECTS);
assert_eq!(seen.len(), MAX_REDIRECTS + 1);
}
#[tokio::test]
async fn redirect_chain_is_recorded_across_hops() {
let (port, server) = scripted(vec![
response("302 Found", "Location: /b\r\n", ""),
response("302 Found", "Location: /c\r\n", ""),
response("200 OK", "", "end"),
])
.await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/a"),
headers: vec![],
body: None,
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("end"));
assert_eq!(r.redirects.len(), 2);
assert_eq!(r.redirects[0].status, 302);
assert_eq!(r.redirects[0].location, format!("http://127.0.0.1:{port}/b"));
assert_eq!(r.redirects[1].status, 302);
assert_eq!(r.redirects[1].location, format!("http://127.0.0.1:{port}/c"));
assert_eq!(seen[2].0.lines().next().unwrap(), "GET /c HTTP/1.1");
}
}
+1 -1
Переглянути файл
@@ -1 +1 @@
9ec6fcb9763867a747206b0efaf8bbeac7934a4ec0d1915623557839cf2dba5e
b59392bcc1999048f0ab922ec659bc21d9e825c696fa41d9f0a40c85627a5b2c
+1 -1
Переглянути файл
@@ -1 +1 @@
2015380825fc406a6466f90658443f824ef06311894b82acae2ecc1446ff0813
034b99891313c03eb2a6b8c3cb2e4784129e1936965be803512f1d869b1768c2
+1 -1
Переглянути файл
@@ -1 +1 @@
7388e5ef7a5bff42f41ed613bfb75a8da835f93a63f8fb26358bb50b77b44c00
29ec0a96e2a0f6965915c7c25e35036743fc27a49037df588c217e8abfff93e3
+1 -1
Переглянути файл
@@ -1 +1 @@
aded25a93667f14a683b0bbb7547b35eed23e4971fdf2761496b09fd898b5034
87b367cfdd65c360920eff7be4d6a8d6b939721f6398aa6a01e39a289590699e
+1 -1
Переглянути файл
@@ -1 +1 @@
178bba6e74a51c0911502524f253cf7148854c46883c3f7f96d2c968e70522f5
7d034ee1a4b99615642d5bf033802f8e4662216d45b209c4c7a24eb8f1338f48
+1 -1
Переглянути файл
@@ -1 +1 @@
786e1abf853d615bf0eab7315280b3884e4c2ff6362c23a41a917d6af4c050e9
3fdf985273ec14ae623fa84602a9220cfbfb2e0e587ab192fc2bcb8d990ce9e3
+1 -1
Переглянути файл
@@ -1 +1 @@
77a825aa6adc3aa39ee390204e1fd35a12425d0a38552f116c74497dac446046
8434e9271e27a6778bb3d5922e8925f3fd9f1d35377e5dddf5b5eb5416bd09bb
+1 -1
Переглянути файл
@@ -1 +1 @@
352246ecdba1e3d43127c7b808a3b1cdf48cf0b4ae7d85d532ffaae734158e15
9fa7468ce385ff33c1f3b99c84711e0d11a84b10e8e4f95b358fcd2ccc96e255
+1 -1
Переглянути файл
@@ -1 +1 @@
da9abe9bd086f7808cc1520a592f47c843f26ecc0a5291110915467f57816dc4
5220a5bfb6ec0467a72e63e21d690e70b7d46b4f2eaff4116a8a79220a5eca8f
+1 -1
Переглянути файл
@@ -1 +1 @@
322b82aa432e072f8ae1d4345d321d227dbcb9376bd113c166b816254e7ddf13
a962127d1c6e37e85b81973a272a5d6b383cc2884b41bb2d82e8640ef5f8f943
+1 -1
Переглянути файл
@@ -1 +1 @@
e1ff50682e4aa18ca6bb96547cdd7b2815ad700e6ecaa3aede6d9f20205d4cdb
92ad3e43e7f343004dcf26a51e282e97ed694cc9bd7325ff75aa5b18f1a2eeb6
+1 -1
Переглянути файл
@@ -1 +1 @@
d3757cea9bcc8e33521c50c66b396d8ece2a90d830c2e57e651ebeb018536c62
2200ed0d44dbafb70ad864cb9569b0b2c37cf9eec1582b05efa903a9e8ec89ee
+1 -1
Переглянути файл
@@ -1 +1 @@
409e7017849fc68bd3241bfa5357366259e1eb634fb71ef69d4b857bec0aa821
644612ee4228010f141042ea0eab5431b8386370f863a70b63cd3315f69d963a
+1 -1
Переглянути файл
@@ -1 +1 @@
0b217ad8f0c8f802c1d670422d9621d07553985b9852f3efb724b17688cfa3b9
2af5d46516bfc1d38ad1f24d6cf3c57e2d6db6b0d3225748f55c4f13110430fb
+1 -1
Переглянути файл
@@ -1 +1 @@
8cc7d2ce4e21838f8f1b0f5bd56aea61257fe288f6b7189343ccf849a78de665
0ee0773cefd61b8144d0550718e1988a1e60438bee826c3867350e28886a56f7
+1 -1
Переглянути файл
@@ -1 +1 @@
19b8af5e283a0a6ae866538096d2fa95e51020a9fd423768224c2ae4cfcefa27
941cb9008aaab11464b193c37b91e2476d771ec526247713f291c6642caf5995
+1 -1
Переглянути файл
@@ -1 +1 @@
ccaa7d24825c05409dbcfe1491276b229ee6d712f2ba18556413a87d851c475c
06d70aae3152c88d1299a9b33f151b0baa4a77c3ca7145215c6f6e0aa40727b2
+1 -1
Переглянути файл
@@ -1 +1 @@
b0ae383f86a8059e0bc723ca1cd21dfa76a0faa68975a1b827b44ebe1ffad2f1
86eb87758e4f7c0242a18f12a113c31d418da64d7198041120f19401a5707bfb
+1 -1
Переглянути файл
@@ -1 +1 @@
38eadb34cc096538f2b529beb07d10860323356c554dd8171ccc7ca25ebfec8e
4442bb686fa18e8e8a52fd1cd8683b8767ec7908ffc1454dff476d9cb1711be9
+1 -1
Переглянути файл
@@ -1 +1 @@
1c5c9a19b4dc05219b3c144b21cad6e05a98fe5c01da7c67383cc39223b6e4d8
dd51f1b8634ff6305ba1a69c8457bd586996200a2b18e4a08d0cfa2fb60abaf6
+1 -1
Переглянути файл
@@ -1 +1 @@
d76fe0c659ef337ae7bb9c75ecfa5a9bcdff2eb92d487ca0df2aefa77bd21daf
4319f2655ee1e240b33f4b96c23fff59c61aa62d6ccc628715e5ff9fe38c2717
+1 -1
Переглянути файл
@@ -1 +1 @@
f671d361a8de5eead5c4ed801bfeacafb7b0aa82abefddbe2436c4d679a56d37
50c4fd7e08a4187afae0e00c775a61578b82bbad056807ad063ee47e79e2cef1
+1 -1
Переглянути файл
@@ -1 +1 @@
5cbb5a91f8676fbc0178535f58213eca341c52e210264ffe3da9eb2a47ef02af
220666302d814e6d8bde346954205c94c82320d5584d46f01672fd7d32400bf3
+1 -1
Переглянути файл
@@ -1 +1 @@
79d5d589c64b66fab58f6fc2cd2a10e91ad23e0dc34b356f6d6d51d7fdcca8b0
4ee484afaa1a1f71a9e544582d90db3260307fc89b8f514aaaff883df2761ba6
+1 -1
Переглянути файл
@@ -1 +1 @@
4eb1b77f62effb313bf67c1dfe34b8e0718bf5afaf84c8252d664b9a9888d040
3fba59ce802d88a2a1c026480a2cb8ce4d9539eb7b88f5a18bf6232f7adef147
+1 -1
Переглянути файл
@@ -1 +1 @@
a36c3f0d92237f226d47325dc4e33312f9179e0e05673154fc07d61f6e68f86e
73433da25d5304d0a3cb83d750d02feb5e270ee7e9f680c4ee9d923afa9aa066
+1 -1
Переглянути файл
@@ -1 +1 @@
2b48734dcf4a8cdf0db0ec80628754a836a0efb2f11dac9fd0fcf80572a23dfe
12df43f99eac93f4e1a070635780ad653932cf69a14595175d8ba6d4f0a4445c
+1 -1
Переглянути файл
@@ -1 +1 @@
fc1cb738668cee77a4d2a7b48d5543a29d568a8d2231921f5257de6a835be307
427b63c11188689262101cde971af0a92e54bd6c88a4e3cc8fdfa1a7c8c95fce
+1 -1
Переглянути файл
@@ -1 +1 @@
f609a501e4e752055d9c8f0ff20d1397b0085587f1435af2928e47fe8507f6ca
07ae58fe39746b779b1e466d7bbbb666ba550f427c7bf8de97d7ede647c00bc0
+1 -1
Переглянути файл
@@ -1 +1 @@
dcacc16856c9b9f11245e4b8c686b1ef6532a0f4090cdf531dafb76f0663a00a
f9912644c28512e37299834123cd4c94f6ed11f29bd38ddbc1c92df168447494
+1 -1
Переглянути файл
@@ -1 +1 @@
ca252d45f83c5e5b9378d6acec40319db2d6acc636d13bf7e79a5339869f7f09
ea0eec8c07d6469d3ab63c3bb08c85b01208be1757edffe5eabcb7be79ccf537
+1 -1
Переглянути файл
@@ -1 +1 @@
f54f4b5ac28e44b8d288104a6290557743e68d2b50af4583dc51a01aca7e7777
1ce55fabaa5ea1ddf770c8a1ad7f7b60a843c82c453d42289088c4b2fec61d84
+1 -1
Переглянути файл
@@ -1 +1 @@
cc98a2e2e74b14a84d3272b41211679a15d06abd4dd664bd87da5ece439e0c00
3356b4ec918c668c4c249f84afb9bafcd06c073ba86235b6ceea7ef6220cdaf5
+1 -1
Переглянути файл
@@ -230,7 +230,7 @@ pub async fn target_path(root: &Path, config: &RunConfig) -> IdeResult<String> {
}
let mut command = std::process::Command::new(&config.command);
command.args(args).current_dir(root);
ide_core::process::host_env(&mut command);
ide_core::process::prepare(&mut command);
if !config.extras.include_system_env {
command.env_clear();
} else {
+5
Переглянути файл
@@ -124,6 +124,11 @@ fn package_info(mut command: Command, dir: &Path, flags: &[String]) -> IdeResult
}
}
command.arg(".").current_dir(dir).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(ide_core::process::CREATE_NO_WINDOW);
}
let mut child = command.spawn()?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
+25 -12
Переглянути файл
@@ -84,7 +84,7 @@ pub fn project_libraries_stream(
cancel: &CancellationToken,
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
type Detect = fn(&Path, &Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
let roots = library_project_roots(root, cancel);
let settings = module_settings(root, settings);
@@ -99,7 +99,7 @@ pub fn project_libraries_stream(
if cancel.is_cancelled() {
break;
}
let batch = d(dir, settings, cancel);
let batch = d(dir, root, settings, cancel);
if !cancel.is_cancelled() && !batch.is_empty() {
on_groups(batch.clone());
groups.extend(batch);
@@ -384,7 +384,7 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
// ------------------------------------------------------------------ python
fn python_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
let mut files = vec![python.clone()];
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
@@ -436,7 +436,7 @@ pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
// ------------------------------------------------------------------ ruby
fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn ruby_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, RUBY_MANIFESTS) else { return Vec::new() };
if !root.join("Gemfile").is_file() && !root.join(".ruby-version").is_file() {
return Vec::new();
@@ -454,7 +454,7 @@ fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Lib
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
// Java modules without a build manifest carry `.classpath` / `.project` /
// `.idea` instead; a configured JDK or declared source roots mark one too.
let files = match manifests(root, JAVA_MANIFESTS) {
@@ -731,7 +731,7 @@ pub(crate) fn gradle_jar(home: &Path, d: &BuildDependency) -> Option<PathBuf> {
// ------------------------------------------------------------------ node
fn node_groups(root: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn node_groups(root: &Path, _project: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
if !root.join("package.json").is_file() {
return Vec::new();
}
@@ -907,7 +907,7 @@ pub(crate) fn parse_cargo_metadata(json: &str) -> Option<Vec<(String, PathBuf)>>
// ------------------------------------------------------------------ go
fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn go_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(mut files) = manifests(root, GO_MANIFESTS) else { return Vec::new() };
if !root.join("go.mod").is_file() && !root.join("go.work").is_file() {
return Vec::new();
@@ -958,7 +958,7 @@ fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Libra
} else if let Some(text) =
query_in_cancellable(&go, &["list", "-m", "-e", "-json", "all"], root, &env, GRAPH_TIMEOUT, cancel)
{
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text))));
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text, project))));
}
out
})
@@ -978,8 +978,19 @@ fn vendor_roots(vendor: &Path, text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
/// `(path@version, dir)` of the downloaded non-main modules in `go list -m -json` output.
pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
/// True when `path` is source the user owns: inside `project` and not a `vendor` copy.
fn is_project_source(project: &Path, path: &Path) -> bool {
let project = project.canonicalize().unwrap_or_else(|_| project.to_path_buf());
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let Ok(relative) = path.strip_prefix(&project) else { return false };
!relative.components().any(|component| component.as_os_str() == "vendor")
}
/// `(path@version, dir)` of the modules that are libraries: everything whose source is
/// outside the opened project. Source inside it is the user's own code — the target of a
/// `replace`, say — and stays editable; a `vendor` copy is the exception, checked in and
/// kept read-only.
pub(crate) fn parse_go_modules(text: &str, project: &Path) -> Vec<(String, PathBuf)> {
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Module {
@@ -993,6 +1004,8 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
.into_iter::<Module>()
.map_while(Result::ok)
.filter(|m| !m.main)
// A module whose source sits in the project is the user's own code, not a library.
.filter(|m| m.dir.as_deref().is_none_or(|dir| !is_project_source(project, dir)))
.filter_map(|m| {
let name = match &m.version {
Some(v) => format!("{}@{v}", m.path),
@@ -1005,7 +1018,7 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
// ------------------------------------------------------------------ zig
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn zig_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
@@ -1574,7 +1587,7 @@ mod zig_tests {
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut settings = Settings::default();
settings.languages.zig.zig = "tools".into();
let groups = zig_groups(root, &settings, &CancellationToken::new());
let groups = zig_groups(root, root, &settings, &CancellationToken::new());
let summary: Vec<(&str, &str, Vec<&str>)> = groups
.iter()
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
+30 -1
Переглянути файл
@@ -1875,7 +1875,7 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}
{"Path":"example.com/missing","Version":"v1.0.0","Error":{"Err":"module lookup disabled"}}"#;
assert_eq!(
crate::libraries::parse_go_modules(out),
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
@@ -1883,6 +1883,35 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn go_modules_skip_module_sources_inside_the_project() {
let out = r#"{"Path":"example.com/app","Main":true,"Dir":"/p/app"}
{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}
{"Path":"example.com/vendored","Version":"v0.0.0","Dir":"/p/vendor/vendored"}
{"Path":"example.com/outside","Version":"v1.0.0","Dir":"/other/outside"}
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}"#;
assert_eq!(
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/p/vendor/vendored")),
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/other/outside")),
(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
),
]
);
// Opened from a root that does not contain it: the same folder is a library again.
assert!(
crate::libraries::parse_go_modules(
r#"{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}"#,
std::path::Path::new("/p/app")
)
.iter()
.any(|(name, _)| name == "example.com/[email protected]")
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
+1
Переглянути файл
@@ -22,6 +22,7 @@ parking_lot.workspace = true
zip.workspace = true
flate2.workspace = true
tar.workspace = true
rayon.workspace = true
[dev-dependencies]
tempfile.workspace = true
+48 -41
Переглянути файл
@@ -10,6 +10,7 @@ mod rules;
mod watch;
use ide_core::{IdeError, IdeResult};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::cmp::Ordering;
@@ -133,51 +134,57 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
let excludes = ExcludeMatcher::new(excludes);
let mut entries: Vec<(bool, FileEntry)> = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = match entry {
Ok(e) => e,
let paths: Vec<PathBuf> = fs::read_dir(dir)?
.filter_map(|entry| match entry {
Ok(e) => Some(e.path()),
Err(e) => {
tracing::debug!("read_dir {}: {e}", dir.display());
continue;
None
}
};
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let Ok(lmeta) = fs::symlink_metadata(&path) else { continue };
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
(EntryKind::Symlink, m, Some(target))
})
.collect();
// One stat per entry dominates a large folder (and every stat is a round trip on a network
// share): stat in parallel; small folders stay on this thread.
let mut entries: Vec<(bool, FileEntry)> = paths
.into_par_iter()
.with_min_len(256)
.filter_map(|path| {
let name = path.file_name()?.to_string_lossy().into_owned();
let lmeta = fs::symlink_metadata(&path).ok()?;
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
(EntryKind::Symlink, m, Some(target))
}
Err(_) => (EntryKind::Symlink, lmeta, None),
}
Err(_) => (EntryKind::Symlink, lmeta, None),
}
} else if lmeta.is_dir() {
(EntryKind::Dir, lmeta, None)
} else {
(EntryKind::File, lmeta, None)
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
entries.push((
is_dir,
FileEntry {
hidden: name.starts_with('.'),
size: if is_dir { 0 } else { meta.len() },
mtime_ms: mtime_ms(&meta),
name,
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
));
}
entries.sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
} else if lmeta.is_dir() {
(EntryKind::Dir, lmeta, None)
} else {
(EntryKind::File, lmeta, None)
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
Some((
is_dir,
FileEntry {
hidden: name.starts_with('.'),
size: if is_dir { 0 } else { meta.len() },
mtime_ms: mtime_ms(&meta),
name,
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
))
})
.collect();
entries.par_sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
Ok(entries.into_iter().map(|(_, e)| e).collect())
}
+1 -1
Переглянути файл
@@ -672,7 +672,7 @@ impl Documents {
fn set_dirty(&self, doc: DocId, st: &mut DocState, dirty: bool) {
if st.dirty != dirty {
st.dirty = dirty;
self.sink.emit(IdeEvent::DocDirty { doc, dirty });
self.sink.emit(IdeEvent::DocDirty { doc, dirty, version: st.doc.version() });
}
}
+113
Переглянути файл
@@ -228,6 +228,109 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
fn assert_failed_save_preserves_edit(f: &Fixture, doc: DocId, text: &str, before: usize) {
let snapshot = f.docs.snapshot(doc).unwrap();
assert!(snapshot.dirty, "failed save marked the document clean");
assert_eq!(snapshot.text, text, "failed save changed the unsaved buffer");
assert!(!dirty_events(&f.events.lock()[before..]).contains(&false), "failed save emitted a clean-state event");
}
#[test]
fn unencodable_save_preserves_the_dirty_buffer_and_disk_bytes() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"caf\xe9").unwrap();
let doc = f.docs.open(&path).unwrap().id;
assert_eq!(f.docs.set_encoding(doc, "windows-1252", true).unwrap().encoding, "windows-1252");
let reloaded = f.docs.snapshot(doc).unwrap();
assert_eq!(reloaded.text, "café");
f.docs.edit(doc, reloaded.version, change(4, 4, "漢")).unwrap();
let original = fs::read(&path).unwrap();
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("Windows-1252 cannot encode the edit");
assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}");
assert_failed_save_preserves_edit(&f, doc, "café漢", before);
assert_eq!(fs::read(&path).unwrap(), original, "failed encoding changed disk bytes");
}
#[cfg(unix)]
#[test]
fn permission_denied_save_preserves_the_edit_and_can_be_retried() {
use std::os::unix::fs::PermissionsExt;
struct RestorePermissions<'a>(&'a Path, fs::Permissions);
impl Drop for RestorePermissions<'_> {
fn drop(&mut self) {
let result = fs::set_permissions(self.0, self.1.clone());
if !std::thread::panicking() {
result.expect("restore fixture permissions");
}
}
}
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
{
let _dir_permissions = RestorePermissions(&f.root, fs::metadata(&f.root).unwrap().permissions());
let _file_permissions = RestorePermissions(&path, fs::metadata(&path).unwrap().permissions());
// Deny both sibling temp-file creation and the fallback write to the existing file.
fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap();
fs::set_permissions(&f.root, fs::Permissions::from_mode(0o555)).unwrap();
let sibling = fs::OpenOptions::new().write(true).create_new(true).open(f.root.join("probe"));
let in_place = fs::OpenOptions::new().write(true).open(&path);
for (probe, access) in [(sibling, "create a sibling file"), (in_place, "open the target for writing")] {
match probe {
Ok(_) => {
eprintln!("skipping permission-denied save: test process can {access} despite permission bits");
return;
}
Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{access}: {err}"),
}
}
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("neither atomic nor in-place save should be writable");
assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err}");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert_eq!(fs::read(&path).unwrap(), b"original", "failed write changed disk bytes");
}
let before = f.events.lock().len();
f.docs.save(doc).expect("retry after restoring file and directory permissions");
assert_eq!(fs::read(&path).unwrap(), b"edited");
assert!(!f.docs.snapshot(doc).unwrap().dirty, "successful retry left the document dirty");
assert_eq!(dirty_events(&f.events.lock()[before..]), vec![false]);
}
#[test]
fn save_to_a_path_replaced_by_a_directory_preserves_the_dirty_buffer() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
assert!(f.docs.snapshot(doc).unwrap().dirty);
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
let before = f.events.lock().len();
f.docs.save(doc).expect_err("save must not replace a directory with a file");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert!(fs::symlink_metadata(&path).unwrap().is_dir(), "save removed the replacement directory");
assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "save left artifacts inside the replacement directory");
assert_eq!(fs::read_dir(&f.root).unwrap().count(), 1, "save left artifacts beside the replacement directory");
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
@@ -249,6 +352,16 @@ fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
let transitions: Vec<_> = f
.events
.lock()
.iter()
.filter_map(|event| match event {
IdeEvent::DocDirty { doc, dirty, version } if *doc == info.id => Some((*version, *dirty)),
_ => None,
})
.collect();
assert_eq!(transitions, [(1, true), (1, false), (2, true), (2, false)]);
}
#[test]
+1 -1
Переглянути файл
@@ -29,7 +29,7 @@ Conventions:
| ---------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
| oxfmt | `pnpm format` (CI: `pnpm format:check`) | `.oxfmtrc.json`: print width 120, double quotes, semicolons, trailing commas everywhere |
| oxlint | `pnpm lint` | `.oxlintrc.json`: TypeScript and React plugins |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `perf/`, `scripts/`, `smoke/` |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `e2e/`, `evals/`, `perf/`, `scripts/`, `smoke/` |
| knip | `pnpm knip` | `knip.ts`: unused files, exports and dependencies |
`pnpm knip` fails on an export nobody imports, a file nobody reaches or a dependency nobody uses. Delete dead code rather than suppressing it; exports used only inside their own file are allowed.
+2 -1
Переглянути файл
@@ -27,6 +27,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
| Auggie | `auggie --acp` | `auggie login` |
| Kiro | `kiro-cli acp` | `kiro-cli login` |
| Mistral Vibe | `vibe-acp` | `vibe` |
| Hermes Agent | `hermes acp` | `hermes model` |
**Claude Code** and **Codex** are driven through their own protocols (Claude Code's stream-json mode and `codex app-server`). Their ACP adapters (`claude-acp`, `codex-acp`) are no longer listed; tasks that already use them keep working, and an [agent file](#add-a-custom-agent) for either id lists it again. If an agent needs you to sign in, the task tells you which command to run.
@@ -136,7 +137,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
## Add a custom agent
+1 -1
Переглянути файл
@@ -123,7 +123,7 @@ These commands are in the **Run** menu and on the Debug tool window toolbar.
While the program is suspended:
- The **Variables** view shows the variables of the selected frame. Right-click a value for **Set Value…** (`F2`), **Copy Value**, **Copy Name**, **Jump to Source** (`F4`) and **Add to Watches**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**, or all of them with **Remove All Watches**.
- Hovering a variable in the editor shows its value. `⌥`-click (`Alt`-click) or **Quick Evaluate Expression** (`⌘⌥F8` / `Ctrl+Alt+F8`) evaluates the expression under the mouse or the selection.
- Values of local variables are shown inline after the lines that use them.
- **Evaluate Expression…** (`⌥F8` / `Alt+F8`) opens a dialog that evaluates any expression in the selected frame, keeps a history, and can add the expression to watches.
+2
Переглянути файл
@@ -136,6 +136,8 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
As in IntelliJ IDEA, there is no per-file save: files are saved when you switch to another application or to the built-in terminal, and **File › Save All** (`⌘S` / `Ctrl+S`) saves everything at once. **Settings › Appearance & Behavior › System Settings**, section **Autosave**, can also save after the IDE has been idle for a while.
If you keep typing during a save, edits not included in that write stay marked as unsaved.
Changes made outside the IDE are picked up when you switch back to its window. **Reload from Disk** (`⌥⌘Y` / `Ctrl+Alt+Y`) reloads the current file now.
## Related
+4 -2
Переглянути файл
@@ -111,7 +111,7 @@ The toolbar has **Stop Request**, **Reload History** and **Clear History**. The
- HTTP/1.1 and HTTP/2. gzip, deflate and brotli responses are decoded.
- TLS certificates are verified against the system trust store.
- Redirects are followed.
- Redirects are followed (up to 50): a 303 continues as GET without the body, other redirects keep the method and body, and the hops are shown in the response.
- Cookies are not kept between requests.
- Connections time out after 30 seconds; there is no overall request timeout.
- The proxy comes from **Settings › Appearance & Behavior › System Settings › HTTP Proxy**.
@@ -135,7 +135,9 @@ In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint**
The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent.
This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes.
To see which Feign interfaces declare a request to a Spring endpoint, open the endpoint’s gutter menu and choose **Find Feign Clients**. You can also invoke the action from the editor menu or Find Action with the caret in the controller method. A single service match opens directly. When several clients match, the chooser shows each interface method and its source path. Clients whose service cannot be established appear below known matches as **Possible match**, even when only one is found. A client known to target another service is excluded.
Navigation reads local source and module configuration, including unsaved editor changes. Custom source sets, composed or aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns, and runtime service discovery are outside its scope.
## Not supported
+2
Переглянути файл
@@ -155,6 +155,8 @@ When a project loads and unloads:
**Open now** lists the loaded projects, each with what it is doing (answering a request, kept open by a run, or how long it has been idle and when it unloads) and an **Unload** button. Unloading does not wait for **Apply**. The project loads again on the next tool call that names it, if the setting still serves it.
While any project is loaded, the **Background Projects** item in the status bar (a layers icon and the count) opens the same list. Each row has the **Open in New Window** and **Unload** icon buttons, and below the list are **Unload All** and **MCP Server Settings…**.
What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools.
A background project has no window, so some tools differ:
+1 -1
Переглянути файл
@@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st
Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**.
- File paths and stack trace frames in the output are links.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ The same page also has:
- **Different tool window background**: set tool windows apart from the editor.
- **Background Image**: an image shown through the project window, with its **Opacity**, **Fill** (scale, original size or tile) and **Anchor**.
- **Accessibility**: **Use contrast scrollbars** and **Adjust colors for red-green vision deficiency** (for protanopia and deuteranopia).
- **Compact mode** under **UI Options**.
- **Compact mode** under **UI Options**, also in **View › Appearance**. As in IntelliJ IDEA, it uses shorter tree and list rows, a smaller main toolbar, tool window stripes and status bar, 16px toolbar and stripe icons, and 1px smaller text in the toolbar, status bar, editor tabs and tool window headers.
## Editor color scheme
+1
Переглянути файл
@@ -206,6 +206,7 @@ Limits: interactive rebase doesn't support ranges with merge commits, and **Undo
- **Shelve Changes…** lets you pick files and a name; the changes are then reverted.
- **Unshelve…** applies a shelf (or one file of it) with a three-way merge, into a changelist you choose.
- **Shelve Silently** (`⇧⌘H` / `Ctrl+Shift+H`, also on the Changes toolbar) shelves the selected changes, or the active changelist, without the dialog: one shelf per changelist, named after it. **Unshelve Silently** (`⌥⌘U` / `Ctrl+Alt+U` in the Shelf) applies the selected shelf or file into the changelist with the shelf's name, else the active one.
- The **Shelf** tab shows shelves with diff, compare with local, patch export, rename and delete.
Turn on **Combine stashes and shelves in one tab** in the Git settings to show both in one tab.
+4
Переглянути файл
@@ -318,5 +318,9 @@ let out = host::run_command(&Command::new("forge").arg("build").env("FOUNDRY_PRO
- Calls are cancelled with the task or call and killed at timeout; run anything slow
inside `host::begin_task`. Dropping a `Child` kills it, and disabling or reclaiming the
plugin ends its children.
- A `Child`'s `poll` and `wait` return what it printed since the last read. `status` comes
with the chunk that holds the last of its output, so read until it is set. Output nobody
reads keeps only its last 1 MiB per stream: for the whole output of a command that ends,
use `run_command`.
- In **Settings › Plugins** the user can choose the executable of a `process:` grant
globally or per project; the plugin keeps calling its declared program name.
+6 -6
Переглянути файл
@@ -25,12 +25,12 @@ description: "Rust 与 TypeScript 的格式化、lint 和死代码检查,以
## TypeScript 与 React
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、分号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `e2e/`、`evals/`、`perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
`pnpm knip` 发现没人 import 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。
+2 -1
Переглянути файл
@@ -27,6 +27,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
| Auggie | `auggie --acp` | `auggie login` |
| Kiro | `kiro-cli acp` | `kiro-cli login` |
| Mistral Vibe | `vibe-acp` | `vibe` |
| Hermes Agent | `hermes acp` | `hermes model` |
**Claude Code** 和 **Codex** 通过它们自己的协议驱动(Claude Code 的 stream-json 模式和 `codex app-server`)。它们的 ACP 适配器(`claude-acp`、`codex-acp`)不再列出;已经在用它们的任务照常运行,为这两个 id 写一个 [agent 文件](#添加自定义-agent)也会重新列出。agent 需要登录时,任务中会提示该运行哪条命令。
@@ -136,7 +137,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
## 添加自定义 agent
+1 -1
Переглянути файл
@@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
程序挂起时:
- **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。
- 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。
- 局部变量的值会内联显示在使用它们的行尾。
- **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。
+2
Переглянути файл
@@ -136,6 +136,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。
如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。
在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。
## 相关页面
+4 -2
Переглянути файл
@@ -111,7 +111,7 @@ OpenIDEA 会从请求文件所在目录开始,逐级向上查找到项目根
- 支持 HTTP/1.1 和 HTTP/2,自动解码 gzip、deflate 和 brotli。
- TLS 证书按系统信任库校验。
- 自动跟随重定向。
- 自动跟随重定向(最多 50 次):303 之后以不带请求体的 GET 继续,其余重定向保留方法与请求体,并在响应中显示跳转链。
- 请求之间不保留 Cookie。
- 连接超时为 30 秒,没有整体请求超时。
- 代理使用 **设置 › 外观与行为 › 系统设置 › HTTP 代理** 中的配置。
@@ -135,7 +135,9 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping`
内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。
这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。
要查看哪些 Feign 接口声明了对 Spring 端点的请求,请打开端点的装订线菜单并选择**查找 Feign 客户端**。光标位于控制器方法中时,也可以从编辑器菜单或查找操作中执行。只有一个服务匹配时会直接打开该声明。多个结果会列出各接口方法及其源码路径。无法确认目标服务的客户端排在已知匹配之后,并标为**可能匹配**,即便只有一个候选也会显示选择器。明确指向其他服务的客户端会被排除。
导航读取本地源码和模块配置,包括未保存的修改。暂不支持自定义源码目录、组合或别名注解、继承映射、动态映射路径、`@RequestLine`、Ant/正则路径模式和运行时服务发现。
## 暂不支持
+2
Переглянути файл
@@ -154,6 +154,8 @@ stdio 配置大致如下(路径以你机器上的为准):
**当前已打开** 列出已加载的项目,每个项目显示它正在做什么(正在处理请求、因某个运行保持打开,或已空闲多久以及何时卸载),并带有 **卸载** 按钮。卸载不必等到 **应用**。如果设置仍然提供该项目,下一次指向它的工具调用会再次加载它。
只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。
后台项目没有窗口,所以有些工具不同:
+1 -1
Переглянути файл
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
- 输出里的文件路径和堆栈帧都可以点击跳转。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主
- **不同的工具窗口背景**:让工具窗口与编辑器区分开。
- **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。
- **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。
- **UI 选项** 下的 **紧凑模式**。
- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。
## 编辑器配色方案
+1
Переглянути файл
@@ -204,6 +204,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
- **搁置更改…**:选择文件并命名,之后这些更改会被还原。
- **取消搁置…**:以三方合并的方式把搁置(或其中某个文件)应用到你选择的更改列表。
- **静默搁置**(`⇧⌘H` / `Ctrl+Shift+H`,也在更改工具栏上)不弹对话框,直接搁置选中的更改(未选中时为活动更改列表):每个更改列表一个搁置,以列表名命名。**静默取消搁置**(在搁置中按 `⌥⌘U` / `Ctrl+Alt+U`)把选中的搁置或文件应用到与搁置同名的更改列表,没有则应用到活动更改列表。
- **搁置** 标签页列出所有搁置,支持查看差异、与本地比较、导出补丁、重命名和删除。
在 Git 设置中打开 **在同一个标签页中合并显示贮藏和搁置**,两者会显示在同一个标签页里。
+2
Переглянути файл
@@ -272,4 +272,6 @@ let out = host::run_command(&Command::new("forge").arg("build").env("FOUNDRY_PRO
- 环境变量只能追加:名称已存在于准备好的环境中(包括登录 shell 的 `PATH`)会报错。最多 64 项。
- 调用会随任务或调用一起取消,超时即终止;耗时的工作请放进 `host::begin_task`。丢弃 `Child` 会终止进程,
禁用或回收插件会结束它启动的所有子进程。
- `Child` 的 `poll` 和 `wait` 返回上次读取之后的输出;`status` 随包含最后一段输出的那次结果返回,读到它为止。
没有读取的输出每个流只保留最后 1 MiB;要拿到会结束的命令的完整输出,请用 `run_command`。
- 用户可以在 **设置 › 插件** 中为 `process:` 授权全局或按项目选择可执行文件;插件仍使用其声明的程序名调用。
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ const firstTask: AgentTask = {
const secondTask: AgentTask = { ...firstTask, id: "focus-second", title: "Second focus task" };
const draft = "draft keep this unsent";
const reboundShortcut = "Control+Meta+Shift+J";
const subagent: AgentEntry = {
const subagent: Extract<AgentEntry, { type: "subagent" }> = {
type: "subagent",
id: "focus-child",
title: "Inspect focus behavior",
+4 -3
Переглянути файл
@@ -149,7 +149,7 @@ test("opens slash-prefixed Windows Markdown links with preview content and hover
for (const [label, path, heading] of [
["Specification", spec, "Windows specification"],
["Work skill", skill, "Work specification skill"],
]) {
] as const) {
const link = reply.getByRole("link", { name: label, exact: true });
await link.hover();
await expect(link).toHaveAttribute("title", path);
@@ -947,8 +947,9 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
const expandableToolChevron = toolRows[0]!
.querySelector<SVGElement>("[class*='_toolChevron_']")!
.getBoundingClientRect();
const completedReadIcon = [...toolRows[1]!.querySelectorAll("svg")].at(-1)!.getBoundingClientRect();
const runningReadIcon = toolRows[2]!.querySelector("svg")!.getBoundingClientRect();
const kindIcon = (row: HTMLElement) => row.querySelector<SVGElement>("[class*='_toolKindIcon_']")!;
const completedReadIcon = kindIcon(toolRows[1]!).getBoundingClientRect();
const runningReadIcon = kindIcon(toolRows[2]!).getBoundingClientRect();
return {
summaryChevronCenter: summaryChevron.left + summaryChevron.width / 2,
guideLeft: processBody.left,
+7 -7
Переглянути файл
@@ -1,5 +1,7 @@
import { expect, test } from "./fixtures";
import type { AgentQuestion, AgentTask } from "../src/bindings";
import type * as AgentStore from "../src/features/agents/store";
import type * as Ipc from "../src/platform/ipc";
const task: AgentTask = {
id: "questions",
@@ -49,14 +51,12 @@ for (const status of ["running", "ready"] as const) {
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
await page.evaluate(
async ({ task, status, key }) => {
// Keep the workbench imports in the browser's Vite realm.
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
(await import(ipcPath)).commands.agentAnswerQuestion = async (
id: string,
question: string,
answer: string | null,
) => {
const store: typeof AgentStore = await import(storePath);
const { commands }: typeof Ipc = await import(ipcPath);
commands.agentAnswerQuestion = async (id, question, answer) => {
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
const entries = store.useAgents.getState().entries.get(id)!;
store.useAgents.setState({
@@ -111,7 +111,7 @@ for (const status of ["running", "ready"] as const) {
if (status === "running") {
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
const { useAgents }: typeof AgentStore = await import(storePath);
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
}, task.id);
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
+7 -4
Переглянути файл
@@ -1,3 +1,4 @@
import type * as ProjectStore from "../src/platform/project";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
@@ -114,9 +115,11 @@ test("restricting an attached folder leaves the current project untouched", asyn
test("restricted attachments can be trusted individually from the banner", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const m = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ m);
// Load the running workbench's store in the browser.
const projectPath = "/src/platform/project.ts";
const { useProject }: typeof ProjectStore = await import(/* @vite-ignore */ projectPath);
const primary = useProject.getState().project;
if (!primary) throw new Error("Expected the sample project to be open");
let current = {
...primary,
trusted: false,
@@ -126,11 +129,11 @@ test("restricted attachments can be trusted individually from the banner", async
const trusted = new Set([primary.root]);
window.__ipc.handlers.project_trust_status = ({ path }) => ({
root: path,
trusted: trusted.has(path),
trusted: typeof path === "string" && trusted.has(path),
decided: true,
});
window.__ipc.handlers.project_trust_set = ({ path, trusted: allow }) => {
if (allow) trusted.add(path);
if (allow && typeof path === "string") trusted.add(path);
current = { ...current, trusted: current.workspace.projects.every((path) => trusted.has(path)) };
};
window.__ipc.handlers.project_current = () => current;
+61
Переглянути файл
@@ -0,0 +1,61 @@
import { expect, test } from "./fixtures";
test("line bookmarks keep their code or description readable in the dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 880, height: 640 });
const name = "QuarterlySettlementReconciliationCoordinator.ts";
const path = `/dev/acme-api/${name}`;
const code = "reconcileCheckoutOrders();";
const description = "Review settlement totals";
await page.evaluate(
async ({ path, code }) => {
const backendModule = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
docBackend().files.set(path, [...Array(27).fill("// Settlement rules"), code, "verifyTotals();", ""].join("\n"));
const services = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ services);
await editorService().openFile(path);
},
{ path, code },
);
await expect(page.locator(".cm-content")).toContainText(code);
await page.evaluate(
async ({ path, description }) => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("navigate.toggleBookmark", { path, line: 27 });
await executeAction("navigate.toggleBookmark", { path, line: 29 });
const bookmarkModule = "/src/features/search/bookmarks/store.ts";
const { assignMnemonic, updateBookmarks } = await import(/* @vite-ignore */ bookmarkModule);
updateBookmarks((items: unknown[]) => assignMnemonic(items, path, 28, "verifyTotals();", "4", description));
await executeAction("toolwindow.bookmarks");
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
setToolWindowSize("left", 240);
},
{ path, description },
);
const tree = page.getByRole("tree", { name: "Bookmarks" });
await expect(tree.getByText(name, { exact: true })).toBeVisible();
const snippet = tree.getByText(code, { exact: true });
await expect.poll(() => snippet.evaluate((el) => el.clientWidth)).toBeGreaterThanOrEqual(105);
await expect(tree.getByText("28:", { exact: true })).toBeVisible();
await expect(tree.getByText("29:", { exact: true })).toBeVisible();
await expect(tree.getByText(description, { exact: true })).toBeVisible();
await expect(tree.getByText("(empty line)", { exact: true })).toBeVisible();
expect(await tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
const row = tree.getByRole("treeitem").filter({ hasText: code });
await row.click();
await page.keyboard.press("Enter");
await expect
.poll(() =>
page.evaluate(async () => {
const module = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ module);
const cursor = editorService().activeCursor();
return { path: cursor?.path, line: cursor?.line };
}),
)
.toEqual({ path, line: 27 });
});
+71
Переглянути файл
@@ -0,0 +1,71 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => {
const branch = "feature/settlement-reconciliation-and-international-ledger-reporting";
const current = "feature/review-quarterly-settlement-audit";
const incomingSubject = "Keep regional settlement references stable during the report export";
const outgoingSubject = "Preserve the audit trail for settlement retries";
await page.setViewportSize({ width: 1120, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ branch, current, incomingSubject, outgoingSubject }) => {
const root = "/dev/acme-api";
const branchInfo = {
head: current,
headCommit: "b".repeat(40),
upstream: null,
ahead: 0,
behind: 0,
operation: null,
};
const entry = (letter: string, summary: string) => ({
id: letter.repeat(40),
shortId: letter.repeat(8),
parents: ["a".repeat(40)],
refs: [],
summary,
message: summary + "\n\nUpdate the audit report context.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
});
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, ...branchInfo }];
h.vcs_branch_info = () => branchInfo;
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { range: string }).range === `HEAD..${branch}`
? [entry("c", incomingSubject)]
: [entry("b", outgoingSubject)];
h.window_open_comparison = () => null;
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo });
const path = "/src/features/vcs/CompareBranches.tsx";
(await import(/* @vite-ignore */ path)).showCompareBranches(branch);
},
{ branch, current, incomingSubject, outgoingSubject },
);
const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) });
await expect(dialog.getByRole("listbox")).toHaveCount(2);
const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` });
const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` });
await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible();
await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible();
const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const start = (await divider.boundingBox())!.y;
await divider.focus();
await page.keyboard.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1);
await page.setViewportSize({ width: 440, height: 660 });
const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) });
await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(incoming.getByRole("option")).toBeVisible();
await expect(outgoing.getByRole("option")).toBeVisible();
await dialog.getByRole("button", { name: "Show Diff", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "window_open_comparison"))
.toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]);
});
+40 -2
Переглянути файл
@@ -6,6 +6,9 @@ import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const NESTED_REF = "teams/payments/reporting/month-end/exports/regions/europe/accounting/invoice-export";
const TRACKING_REF = "origin/releases/payments/month-end/reconciliation/invoice-export";
const BRANCH_FIXTURE = { root: ROOT, ref: NESTED_REF, upstream: TRACKING_REF };
async function openBranches(page: Page) {
await page.evaluate(async () => {
@@ -22,7 +25,7 @@ async function openBranches(page: Page) {
test.beforeEach(async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (root) => {
await page.evaluate(async ({ root, ref, upstream }) => {
const h = window.__ipc.handlers;
const branch = (name: string, current = false) => ({
name,
@@ -47,6 +50,7 @@ test.beforeEach(async ({ workbench: page }) => {
h.vcs_tags = () => [];
h.vcs_branches = () => [
branch("main", true),
{ ...branch(ref), upstream, ahead: 2, behind: 3 },
...Array.from({ length: 40 }, (_, i) => branch(`task-${i}-a-long-branch-name-that-gets-cut-off`)),
];
const vcsModule = "/src/features/vcs/store.ts";
@@ -54,7 +58,41 @@ test.beforeEach(async ({ workbench: page }) => {
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
await loadBranches();
}, ROOT);
}, BRANCH_FIXTURE);
});
test("narrow Git Branches keeps a deeply nested branch and its controls readable", async ({ workbench: page }) => {
await page.evaluate(() => {
localStorage.setItem("openidea.vcs.branchesPopup.size", JSON.stringify({ w: 280, h: 420 }));
});
const popup = await openBranches(page);
const search = popup.getByRole("textbox", { name: "Search branches and actions" });
await search.fill("invoice-export");
const row = popup.getByRole("option", { name: /invoice-export/ });
await expect(row).toBeVisible();
const name = row.locator("[class*=branchName]");
const tracking = row.getByText(TRACKING_REF, { exact: true });
const chevron = row.locator("svg").last();
const folder = popup.getByRole("option", { name: "accounting", exact: true });
const rowBox = (await row.boundingBox())!;
const nameBox = (await name.boundingBox())!;
const trackingBox = (await tracking.boundingBox())!;
const chevronBox = (await chevron.boundingBox())!;
const indent = (option: typeof row) =>
option.locator("[data-row-key]").evaluate((el) => parseFloat(getComputedStyle(el).paddingInlineStart));
expect(await indent(row)).toBeGreaterThan(await indent(folder));
expect(chevronBox.x + chevronBox.width).toBeLessThanOrEqual(rowBox.x + rowBox.width);
expect(nameBox.width).toBeGreaterThan(42);
expect(trackingBox.width).toBeGreaterThan(12);
expect(trackingBox.width).toBeLessThan(rowBox.width * 0.4);
await expect(name).toHaveCSS("font-size", "13px");
await expect(tracking).toHaveCSS("font-size", "13px");
await expect(row.getByRole("img", { name: "3 incoming commits" })).toBeVisible();
await expect(row.getByRole("img", { name: "2 outgoing commits" })).toBeVisible();
await expect(row.locator("[data-row-key]")).toHaveAttribute("title", NESTED_REF);
await expect(tracking).toHaveAttribute("title", TRACKING_REF);
await chevron.click();
await expect(page.getByRole("menu", { name: `Branch ${NESTED_REF}` })).toBeVisible();
});
test("Git Branches resizes by its corner and right edge and reopens at that size", async ({ workbench: page }) => {
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { expect, test } from "./fixtures";
test("keeps breakpoint details editable when the dialog gets narrow", async ({ workbench: page }) => {
await page.setViewportSize({ width: 500, height: 480 });
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const storeModule = "/src/features/debugger/breakpoints/store.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
const { addBreakpoint } = await import(/* @vite-ignore */ storeModule);
addBreakpoint("/dev/acme-api/CheckInternationalSettlementBeforeDispatch.java", 7, {
condition: "amount > 100",
});
addBreakpoint("/dev/acme-api/Receipt.java", 4);
await executeAction("debug.viewBreakpoints");
});
const dialog = page.getByRole("dialog", { name: "Breakpoints" });
const list = dialog.getByRole("listbox", { name: "All breakpoints" });
const condition = dialog.locator('input[aria-label="Condition"]');
await expect(condition).toHaveValue("amount > 100");
await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240);
await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 });
await condition.fill("amount > 250");
await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}");
const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ });
await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
await list.getByRole("option", { name: /Receipt\.java:5/ }).click();
await expect(condition).toHaveValue("");
await first.click();
await expect(condition).toHaveValue("amount > 250");
await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}");
await page.setViewportSize({ width: 1080, height: 760 });
const divider = dialog.locator('[data-separator][aria-orientation="vertical"]');
await expect(divider).toBeInViewport();
const oldWidth = (await list.boundingBox())!.width;
const handle = (await divider.boundingBox())!;
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + 60, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(async () => (await list.boundingBox())?.width ?? 0).toBeGreaterThan(oldWidth + 20);
await expect(condition).toHaveValue("amount > 250");
const request = dialog.getByRole("textbox", { name: "Part of a request URL" });
await request.scrollIntoViewIfNeeded();
await expect(request).toBeInViewport({ ratio: 1 });
await dialog.getByRole("button", { name: "Done", exact: true }).click();
await expect(dialog).toBeHidden();
});
+99
Переглянути файл
@@ -0,0 +1,99 @@
import type { Page } from "@playwright/test";
import type { BuildModel, BuildTool } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const model: BuildModel = {
maven: {
projects: [
{
pom: "pom.xml",
dir: "",
groupId: "com.example",
artifactId: "orders",
version: "1.0.0",
packaging: "jar",
displayName: "Orders service",
parent: null,
modules: [],
aggregated: false,
plugins: [],
dependencies: [],
profiles: [],
javaVersion: 21,
command: "mvn",
options: [],
env: {},
},
],
profiles: [],
syncedAt: 1,
stale: false,
syncError: null,
},
gradle: [
{
dir: "",
command: "gradle",
env: {},
javaVersion: 21,
syncedAt: 1,
stale: false,
syncError: null,
projects: [{ path: ":", name: "orders", dir: "", buildFile: "build.gradle", tasks: [] }],
},
],
};
async function showTool(page: Page, tool: BuildTool) {
await stubDesktop(page);
await page.evaluate(
async ({ tool, model }) => {
window.__ipc.handlers.build_model = () => model;
window.__ipc.handlers.run_configs = () => [];
const buildStore = "/src/features/build-tools/store.ts";
await (await import(/* @vite-ignore */ buildStore)).loadModel();
const layout = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layout);
showToolWindow(tool, true);
setToolWindowSize("right", 190);
},
{ tool, model },
);
}
async function setWidth(page: Page, width: number) {
await page.evaluate(async (px) => {
const layout = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ layout)).setToolWindowSize("right", px);
}, width);
}
for (const tool of ["maven", "gradle"] as const) {
const name = tool === "maven" ? "Maven" : "Gradle";
test(`${name} keeps its toolbar actions reachable as the pane resizes`, async ({ workbench: page }) => {
await showTool(page, tool);
const toolbar = page.getByRole("toolbar", { name: `${name} actions` });
const more = toolbar.getByRole("button", { name: "More Actions", exact: true });
const menu = page.getByRole("menu", { name: "More Actions", exact: true });
const skipTests = "Toggle 'Skip Tests' Mode";
await expect(toolbar.getByRole("button", { name: `Reload All ${name} Projects` })).toBeVisible();
await expect(toolbar.getByRole("button", { name: new RegExp(`Execute ${name}`) })).toBeVisible();
await expect(page.getByRole("tree", { name: `${name} projects` })).toBeVisible();
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await more.click();
await expect(menu.getByRole("menuitem", { name: "Analyze Dependencies…" })).toBeVisible();
await expect(menu.getByRole("menuitem", { name: "Expand All" })).toBeVisible();
await menu.getByRole("menuitemcheckbox", { name: skipTests, checked: false }).click();
await expect(menu).toBeHidden();
await more.click();
await expect(menu.getByRole("menuitemcheckbox", { name: skipTests, checked: true })).toBeVisible();
await setWidth(page, 360);
await expect(menu).toBeHidden();
await expect(more).toBeHidden();
await expect(toolbar.getByRole("button", { name: skipTests, pressed: true })).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Collapse All" })).toBeVisible();
await setWidth(page, 190);
await expect(more).toBeVisible();
await expect(menu).toBeHidden();
});
}
+75
Переглянути файл
@@ -0,0 +1,75 @@
import type { MethodSignature } from "../src/bindings";
import { expect, stubDesktop, test } from "./fixtures";
const signature: MethodSignature = {
methodIdentifier: "invoice",
modifier: "",
returnType: "Invoice",
methodName: "prepareInvoiceForInternationalSettlement",
parameters: [
["Order", "order"],
["String", "billingCurrency"],
["BigDecimal", "amountBeforeDiscount"],
["Map<String, BigDecimal>", "taxRatesByJurisdiction"],
["List<Adjustment>", "settlementAdjustments"],
["RoundingMode", "roundingMode"],
["LocalDate", "scheduledSettlementDate"],
["boolean", "includeTaxBreakdown"],
].map(([type, name], originalIndex) => ({ type: type!, name: name!, originalIndex, defaultValue: "" })),
exceptions: [],
};
test("keeps parameter rows and a long signature preview usable in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 490, height: 520 });
await page.evaluate(async () => {
const workbench = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ workbench);
await editorService().openFile("/dev/acme-api/InvoiceService.java");
});
const editor = page.locator(".cm-editor .cm-content");
await expect(editor).toBeVisible();
await stubDesktop(page);
const fontSize = await editor.evaluate(async (content, signature) => {
window.__ipc.handlers.lsp_signature_info = () => signature;
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const prefsModule = "/src/editor/core/cm/prefs.ts";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
const base = Number.parseFloat(getComputedStyle(content).fontSize);
const view = EditorView.findFromDOM(content as HTMLElement)!;
stepFontZoom(view, 4);
view.focus();
return `${base + 4}px`;
}, signature);
await expect(editor).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+F6");
const dialog = page.getByRole("dialog", { name: "Change Signature" });
const table = dialog.getByRole("table", { name: "Parameters" });
const names = table.getByRole("textbox", { name: "Name", exact: true });
await expect(names.first()).toBeInViewport({ ratio: 1 });
const defaults = table.getByRole("columnheader", { name: "Default value", exact: true });
await expect(defaults).toHaveCount(0);
const preview = dialog.locator("pre");
await expect(preview).toBeInViewport({ ratio: 1 });
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(names.first()).toHaveCSS("font-size", fontSize);
expect(
await preview.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1),
).toBe(true);
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport({ ratio: 1 });
await dialog.getByRole("button", { name: "Add", exact: true }).click();
await expect(defaults).toBeInViewport({ ratio: 1 });
const addedType = table.getByRole("textbox", { name: "Type", exact: true }).last();
await expect(addedType).toBeInViewport({ ratio: 1 });
await addedType.fill("boolean");
await names.last().fill("attachReceipt");
await table.getByRole("textbox", { name: "Default value", exact: true }).last().fill("false");
await dialog.getByRole("button", { name: "Move Up", exact: true }).click();
await expect(names.nth(7)).toHaveValue("attachReceipt");
await expect(preview).toContainText("boolean attachReceipt");
await expect(dialog.getByRole("button", { name: "Preview", exact: true })).toBeEnabled();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
Loaded 100 of 517 files, more files were not shown because too many files have changed in this diff. Show more