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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 1b3d6328d1 fix(agent): show an agent's form fields in its schema's order
serde_json's Value keeps object keys sorted, so elicitation/create forms
listed their fields alphabetically. JSON-RPC handlers can now read the
request as received (Handler::on_request_raw), and the form takes its field
order from requestedSchema.properties there. The ACP dialect wrapper
forwards the raw request.
2026-11-16 01:47:26 +08:00
l0ng-ai 89eacbe640 fix(agent): offer the effort levels a session reports for ACP models discovery didn't read (#3582)
ACP discovery opens one session and knows only that session's model's
effort levels. Once discovery succeeded, session reports no longer reached
the New Task catalog, so other models of the agent showed no effort choice.
A session on another listed model now records that model's levels in the
project's catalog (never the discovered model's), and a later discovery
keeps them while the model is still listed.
2026-11-16 01:23:42 +08:00
Mr0Bread c67b336a8a feat(agent): answer ACP form elicitation (#3580)
The ACP client advertises elicitation.form and answers elicitation/create: the request's restricted JSON Schema becomes form fields (text, number, integer, boolean, single and multiple choice, with titles, descriptions, defaults, required and bounds), shown in the question card above the composer. Submit replies accept with typed values, Decline replies decline, Cancel or Escape replies cancel; the conversation records the answers. Nested objects and URL mode are refused with INVALID_PARAMS. Bypassing approvals never answers a form.

Part of #3536

Co-authored-by: Mr0Bread <[email protected]>
2026-11-16 01:11:16 +08:00
Akbar Husain 90cc707d00 feat(zig): Settings page and detection for the Zig toolchain (#3578)
Adds Settings › Languages & Frameworks › Zig for languages.zig.zig (used by the Zig External Libraries), on the shared SDK row: Auto = zig on PATH, Detect again, Browse. ide-sdk gains SdkKind::Zig, detecting PATH installs (shims skipped), Homebrew, zvm and mise / asdf installs; the stored path is the directory holding zig, with the version from zig version.

Co-authored-by: akbar1214 <[email protected]>
2026-11-16 01:05:20 +08:00
Mr0Bread 779080781b fix(agent): keep each ACP model's own effort levels (#3577)
ACP discovery opens one session and reads its thought_level option, which describes that session's model only, but recorded it under every model value. Agents whose models offer different effort lists (e.g. OMP's Copilot gpt-4o: off/auto) showed levels the agent rejects. Discovery now records the levels for the session's model only.

Part of #3536

Co-authored-by: Mr0Bread <[email protected]>
2026-11-16 01:00:29 +08:00
Bbu Gulli Annтаctro15547 ccf87e2476 fix(macos): support macOS 12 again (#3576)
Lowers the minimum macOS version to 12.0 and the WebKit floor to Safari 15.4: Vite targets safari15.4, check-webkit enforces the 15.4 floor and rejects Array toSorted/toReversed/toSpliced, showPicker and Intl.supportedValuesOf in startup chunks, the boot outdated check tests structuredClone, the Database view drops toReversed, and the install docs list macOS 12. Container-query layouts degrade on macOS 12.

Fixes #3413

Co-authored-by: ctro15547 <[email protected]>
2026-11-16 00:58:42 +08:00
l0ng-ai 76f0b3fc63 feat(project-view): Open in Right Split (⇧Enter) (#3579)
The Project view opened a file in the current pane whatever the modifier and had no way to open one in a split. Open in Right Split opens the selected files in the pane to the right: ⇧Enter in the IntelliJ keymaps, ⌘Enter / Ctrl+Enter in the VS Code ones, and in the context menu before Open In (External Libraries too). On a folder ⇧Enter keeps expanding it.

Closes #3549
2026-11-16 00:55:52 +08:00
l0ng-ai a5c14a4c21 fix(notebook): Vim u and Ctrl-R undo and redo in notebook cells (#3575)
Notebook cells keep no CodeMirror history (edits share the notebook's backend history), so Vim's u / Ctrl-R did nothing there. An editor can provide externalHistory; notebook cells provide the session's, and the Vim engine sends undo / redo to it.
2026-11-16 00:11:43 +08:00
Akbar Husain cf444a31f7 perf(index): allocation-free hump scoring and byte-scan name boosts (#3573)
hump_bonus walks the candidate's chars once with a cursor into the sorted, deduplicated match indices instead of collecting a Vec<char> per ranked survivor, and name_boost finds the extension dot with a byte scan. Results are unchanged; find_symbols/OCo goes from 3.71 ms to 3.36 ms in the index bench.

Co-authored-by: akbar1214 <[email protected]>
2026-11-16 00:05:57 +08:00
Mr0Bread c3763fb806 feat(agent): steer agents that advertise _session/steering (#3568)
Messages typed while a task is running join the running turn for agents that advertise the _session/steering extension (_meta.steering.supported in the initialize response, as OMP does), not only those advertising _meta.openidea.steer. An outcome other than injected (promptRequired, failed) queues the message for the next turn.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-16 00:01:30 +08:00
Mr0Bread 9a518e734b refactor(styles): put gap on the spacing scale (#3562)
Extends the 4px-grid spacing scale with --space-0-5 (2px), --space-1 (4px) and --space-1-5 (6px) and replaces the literal 2/4/6/8/12/16px gap, row-gap and column-gap values with the tokens; computed values are unchanged. src/styles/spacingScale.test.ts flags an on-scale literal gap.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:59:47 +08:00
Mr0Bread 2913c12a19 chore(styles): remove CSS module classes no component reads (#3560)
35 CSS-module classes in 10 modules were defined but never read (no styles.x use, no composes, no dynamic access in their importers): leftovers of removed UI such as the settings code-preview block, the GitHub tool window's layout helpers and SDK tree rows.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:58:00 +08:00
Mr0Bread 3044518b88 fix(styles): restore CSS classes components still reference (#3559)
Components read CSS-module classes no module defined, which are undefined at runtime. The archived-task banner in agent sessions (.banner, .bannerText, .bannerSpacer, dropped in #2083) and the Create Patch directory row (.cloneDirRow, .cloneDirInput, dropped in #866) are restored; references to classes that never existed are removed. src/styles/cssModules.test.ts lists any styles.x the imported module lacks.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:56:20 +08:00
Vadim LazukтаInf1mum 778472854e fix(markdown): keep the Preview only scroll position when switching tabs back (#3569)
Tab switches unmount the preview, and its saved offset was applied once at remount, before images and diagrams had drawn. A restore that clamped to the short document is applied again on each settle until it fits or the reader scrolls; the clamped write no longer replaces the saved offset. The preview opts out of scroll anchoring, which in WebView2 kept a later block in view while images above it loaded.

Fixes #3537

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:54:36 +08:00
l0ng-ai 1679d61a6a fix(services): list the SSH configurations in the Docker connection dialog (#3570)
SshConfigSelect reads the settings window's staged ssh.configs unless given a list, and that list is empty outside the settings window, so the Docker connection dialog offered only None. The dialog now passes the live list; the None choice gets its Chinese text.

Closes #3535
2026-11-15 23:51:21 +08:00
l0ng-ai 937008a6fe fix(lsp): highlight a library class the Kotlin server shows as Java as Java (#3565)
A virtual .class document has no language by its name, so it took its server's first language: the Kotlin language server's Java stubs of jar classes were highlighted as Kotlin and their Java keywords stayed uncoloured. A .class stub whose package or import line ends with ';' is now Java (virtual_doc::is_java_class_stub).
2026-11-15 23:40:00 +08:00
l0ng-ai dc3d2050cb fix(editor): colour this and super as keywords in Java, JavaScript, TypeScript and C++ (#3564)
The Lezer grammars tag `this` as `self`, which the colour scheme paints with Python's self-parameter colour, and @lezer/javascript tags `super` as an atom. JAVA_TAGS (also used by JSP), JS_TAGS and a new C++ entry restyle them as keywords. Python's `self` is unchanged.
2026-11-15 23:37:06 +08:00
Mr0Bread 732baf8f1e fix(styles): use defined tokens where CSS read --bg-subtle, --bg-toolbar and --fg-primary (#3550)
Three custom properties were read without a fallback and declared nowhere, so they resolved to their initial values: no background on the Working Status and Command Permissions rows, none on the console Find button (its icon sat over console text), and an inherited hover colour. They now use --bg-hover, --bg-elev and --fg-strong; a dead var(--bg) fallback in Run.module.css is dropped. A test lists any var(--x) without a fallback whose --x is declared nowhere.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 23:31:12 +08:00
Mansur Akhmadiтаmansur-akhmadi 9b6e5a5a62 feat(vcs): copy a file's link on its Git remote from Copy Path/Reference… (#3553)
Copy Path/Reference… gains a <hosting> Link item (GitHub Link, GitLab Link, Bitbucket Link) that copies the page Open In › <hosting> opens; in the editor the link covers the selected lines (#L2-L3 / #L2-3 / #lines-2:3). A copyPath menu id lets features add items to the chooser, so editor/core and project-tree stay free of Git code.

Closes #3552

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 23:29:54 +08:00
l0ng-ai 8c2c701517 feat(keymap): list Cut, Copy, Paste, Undo, Redo and Select All in Settings › Keymap (#3563)
The Edit actions are hidden from Search Everywhere, and the Keymap page skipped hidden actions with no preset shortcut, so they could not get a second key (Ctrl+Shift+C / V / X for Vim users). A keymap flag on an action keeps it listed; the settings window's action list (describeActions) carries it too.
2026-11-15 23:25:59 +08:00
l0ng-ai aeb689c632 test(app): the command-line diff opens with Swap Sides (#3557)
#3540 made the command-line diff swappable; the launch tests in windows.test.ts still expected the diff data without the flag.
2026-11-15 23:17:53 +08:00
l0ng-ai 80c25be389 fix(keymap): list the data editor actions in the VS Code preset (#3556)
The VS Code preset must name every IntelliJ action id; #3551 added the db.* data editor actions to the IntelliJ presets only, failing keymap.test.ts on main.
2026-11-15 23:16:27 +08:00
Sameh Elhawaryтаsamehelhawary acea7e6235 feat(php): Phoxite as a selectable PHP language server (#3541)
languages/php.toml gains a phoxite entry (phoxite-lsp over stdio), a fallback listed after phpactor; Intelephense stays the default and users pick Phoxite under Language Servers. ide-tools installs it from the samehelhawary/phoxite GitHub releases (a binary per platform with a .sha256 beside it). A server entry can now name the servers it replaces: those stay away while it serves the file (Phoxite replaces laravel-lsp, which it covers), including when the replacing fallback takes over after a server gives up.

Co-authored-by: samehelhawary <[email protected]>
2026-11-15 23:14:32 +08:00
l0ng-ai 25197b3215 fix(vcs): show a committed directory symlink's target in revision diffs (#3554)
Revision content was decoded with the working file's encoding, read whenever the path existed. For a symlink to a folder that path is a directory, so loading failed and the Git Log diff showed '<path> is a directory'. The working file is now consulted only when it is a regular file; otherwise the encoding is detected from the revision's blob.

Closes #3528
2026-11-15 23:11:50 +08:00
Vadim LazukтаInf1mum 55786a7030 fix(vcs): the Git Log rename label names the original directory (#3546)
The changed-file label trimmed a rename's old path to its base name, so a move between directories looked like a rename in place. A shared renameFrom() now says 'renamed from <name>' within one directory and 'moved from <old path relative to the new directory>' otherwise, as IDEA does; Git Log and the GitHub create / pull request change trees use it.

Closes #3529

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:09:13 +08:00
Vadim LazukтаInf1mum b7adbbb17c fix(project): mark symlinks with a link arrow in the tree (#3547)
Directory and file symlinks used the same icons as real folders and files. The Project view now overlays IDEA's link arrow (expui nodes/symlink) on every entry the listing reports as a symlink; the model already carried the flag, so no extra stat calls.

Closes #3527

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:06:39 +08:00
l0ng-ai d1290c76ea feat(database): data editor row and toolbar commands as actions (#3551)
Reload Page, First / Previous / Next / Last Page, Add Row, Export Data, Delete Rows, Restore Rows, Edit Cell and the cell copy commands were menu items or toolbar buttons only. They are now db.* actions supplied by the table editor and the console result grid through their focus handle, so they appear in Find Action and take Keymap shortcuts; menus and buttons run the same actions. DataGrip's defaults bind Reload Page, Previous / Next Page and Add Row, and Delete Rows on Windows and Linux.

Closes #3506
2026-11-15 23:03:35 +08:00
l0ng-ai 0febd3e170 fix(editor): Sort Lines orders by character code (#3548)
Sort Lines used a locale-aware collator, which interleaves upper- and lowercase letters. It now compares UTF-16 code units, the order IDEA's Sort Lines uses (String.compareTo) and LC_ALL=C sort gives.

Closes #3516
2026-11-15 22:47:11 +08:00
Akbar Husain acee0d5edb feat(libraries): show the Zig standard library and build.zig.zon packages in External Libraries (#3526)
A zig detector joins the External Libraries pipeline: the standard library from zig env (struct-literal and JSON output), and the fetched build.zig.zon dependencies from the global package cache, as p/<hash> folders (Zig <= 0.14) or p/<hash>.tar.gz blobs (Zig >= 0.15) browsed read-only through the archive VFS, which now reads gzip'd tars. Nothing is downloaded; path dependencies stay in the project tree. New setting languages.zig.zig (directory of zig, empty = PATH).

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 22:45:18 +08:00
Akbar Husain a02a594010 perf(text): byte-parallel scans in ide-text, ide-syntax and ide-language (#3539)
Document open/diff and UTF-16 position mapping decoded whole files char by char. common_ends compares bytes and backs off to char boundaries, utf16_len classifies bytes with an ASCII fast path, LF-only text skips line-ending normalisation, and memchr_newlines uses memchr. Outputs are unchanged; text/open_1mb -60%, diff_two_edits_1mb -38%.

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 22:38:51 +08:00
PONK 6bb4a6375a docs: add Turkish README translation (#3519)
Adds README.tr.md and a Türkçe link in the README language switcher.

Co-authored-by: lprvy <[email protected]>
2026-11-15 22:37:30 +08:00
Mr0Bread f15c2c2b5e perf(startup): load DiffEditor, the Run console and the file-revision chooser on demand (#3544)
DiffWindow, the Services detail pane and Compare with Revision imported these statically, which kept their chunks in the startup set despite lazy imports elsewhere. They now load on demand; initial JS drops by about 34 KB gzip.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:26 +08:00
Mr0Bread a83a1a54e5 fix(agents): refresh stale agent versions after CLI updates (#3538)
The New Task page reused a probe cached for the whole session, so an updated CLI kept showing its old version. The selected agent is probed again (initialize only, no session) when the page is shown or the window regains focus, without overlapping probes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:21 +08:00
Mr0Bread 0d499f3af6 fix(agents): render Nerd Font icons in agent task titles (#3523)
No font in the UI stack had private-use icons, so OMP task titles showed a missing-glyph box. The UI stack now ends with --font-icons, the first installed Nerd Font (proportional faces first), resolved once when the window is idle. The terminal's Nerd Font list moved to platform/fonts unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:17 +08:00
zhzhsxтаzhzhsx e06c890ca4 fix(editor): show completion documentation beside the list (#3522)
The completion documentation was drawn inside the lookup popup, which clipped it or let it cover the options. positionInfo now places it beside the list on the side with more room, top edges aligned, with capped width and height.

Co-authored-by: zhzhsx <[email protected]>
2026-11-15 22:35:12 +08:00
Muuтаmuutot 6295cc2237 fix(vcs): keep inline blame on its line when soft wraps are on (#3518)
The line-end blame was an in-flow nowrap inline-block, so with soft wrap a label that did not fit was folded onto a new visual row and stretched the line. It is now a zero-width anchor with an absolutely positioned label, like code-vision hints and plugin line-end messages; the inner box is the hover and click target.

Co-authored-by: muutot <[email protected]>
2026-11-15 22:35:07 +08:00
Mamaev Igor 8349938481 fix(vim): enable Vim in notebook cells (#3515)
Notebook cell editors did not include the embedded editor contributions, so Vim (an embedded contribution) never attached to them. CellEditor now adds embeddedEditorExtensions like the other embedded editors.

Co-authored-by: pxc1984 <[email protected]>
2026-11-15 22:35:03 +08:00
Alexanderтаformiat cb2c4345d1 fix(vcs): a branch whose remote branch is gone tracks nothing (#3533)
upstream_of returned the configured upstream name even when its tracking ref had been deleted and pruned, so Git Branches still showed origin/<name>, Update stayed enabled and incoming commits were polled against a missing ref. It now reports an upstream only while the tracking ref exists; branches() and branch_info() share it.

Closes #3530

Co-authored-by: formiat <[email protected]>
2026-11-15 22:25:02 +08:00
l0ng-ai 22f409ae76 feat(diff): external diff tool and Show Diff for Lines (#3543)
- Settings › Tools › External Diff Tools: a program and its parameters
  (%1 the left file, %2 the right file, %3 the title). Diff viewers then
  offer Show Diff in External Tool (toolbar button and action). Saved
  files are passed as they are (saved first); revisions and texts go to
  temporary files named after the file. The program is always read from
  the global settings, never a project's, and runs on this machine.
- Show Diff for Lines (vcs.showDiffForLines): with the caret on changed
  lines in the editor, opens the file's diff at that line.
2026-11-15 22:18:58 +08:00
l0ng-ai b2dc59eb0f feat(diff): blank diff window, Swap Sides, and Search In Changes (#3540)
- Open Blank Diff Window: a new diff tab with two empty, editable sides;
  the editor's selection fills the left one. Text typed into either side
  survives viewer changes (mode, highlighting, Swap Sides).
- Swap Sides: a toolbar button and action for diffs whose sides the user
  picked (Compare With…, Compare Files, Compare with Clipboard, the
  command-line diff and blank diffs). Diffs of revisions keep their order.
- Search In Changes: a find bar filter in diffs that limits matches to the
  changed ranges of the searched side. It is per diff and applies to
  finding only; the replace bar searches the whole side.
2026-11-15 21:59:59 +08:00
Mr0Bread f5641f9c6f feat(agents): say what the agent is doing in the working status, with opt-in playful words (#3459)
The row under a working conversation showed a constant Working…. It now follows the turn's latest entry: Thinking…, Writing…, Reading…, Editing…, Running a command…, Running a subagent… and so on, with Working… for the rest.

Settings › Agents › Working Status adds playful words per activity, off by default. When on, they rotate from the start or after a configurable quiet time (0–600 s). Each word stays 8 s, or at least 3 s once the activity changes. Screen readers keep hearing the plain status. Users can replace or clear each activity's words.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 21:55:09 +08:00
l0ng-ai dcd4f150bd fix(kotlin): stop notifying about every Kotlin compiler error in Maven projects (#3521)
The Kotlin-to-Java bridge popped an error notification for each new failure message, so mid-edit Kotlin with autosave produced a balloon per save for errors its editor already shows. Compiler errors in project sources now only update the Problems entry on pom.xml; a build that fails without one (Maven, a goal that didn't run, the bridge bundle or JDT snapshot) still notifies once per message.
2026-11-15 19:26:00 +08:00
l0ng-ai 8caeb1305f fix(editor): indent Kotlin, Scala, Dart and Groovy brackets opened after a string (#3520)
The string-interpolation wrapper let the stock clike tokenizer consume an empty string on a new stream at column 0 whenever a literal opened; clike read that as a new line and reset the line's indentation to 0, so a bracket opened later on the same line indented its contents from column 0. Enter and paste with Reformat on Paste put the following lines at the wrong column. The empty string is now tokenized at the literal's own column, which fixes all dialects served by the wrapper (Kotlin, Scala, Dart, Groovy; C# shares the code path).
2026-11-15 19:21:48 +08:00
l0ng-ai 7ec0a4fed2 feat(diff): Esc closes a diff tab; switch panes with ⌃⇧⇥; move a diff window back to a tab (#3517)
Close Diff Editor: Esc in a diff editor tab closes it once the find bar, a selection, completion or a popup don't take it; panels, dialogs and diff windows keep their own Esc. Select Opposite Diff Pane (⌃⇧⇥ in the IntelliJ keymaps) moves focus to the other side of a side-by-side diff and wins over the Switcher while a diff is focused. A diff window's Show Diff in Editor Tab saves its edits, opens the diff as a tab in its project window and closes the window.
2026-11-15 18:42:16 +08:00
l0ng-ai 733b6cff1d feat(run): pin Run and Debug tabs; a new run replaces one finished, unpinned tab (#3514)
Run and Debug tabs can be pinned (context menu, Pin Active Tab, or the pin in place of the close button). A new run or debug session takes the place of one finished, unpinned tab: the same configuration's, else the selected one, else the first; Run used to add a tab per configuration, so finished tabs piled up. Rerun on a pinned tab restarts it in place and keeps it pinned. Settings > Run/Debug gets "Make configurations pinned by default".

Siblings: Run, Debug, Find and Usages tabs share one context menu (Close Tab, Close All Tabs, Close Other Tabs, Pin/Unpin Tab); Find and Usages show a pinned tab with the pin in place of its close button.
2026-11-15 18:29:15 +08:00
l0ng-ai b0860ed1e2 fix(debugger): a new debug session replaces one finished tab, not all of them (#3512)
Starting a session dropped every finished Debug tab, so ended sessions of other configurations disappeared with it. The new session now takes the place of a single finished tab: the same-named one, else the selected one, else the first; other finished tabs stay. A prepared start replaces it when its build begins and doesn't replace another when the adapter starts.
2026-11-15 18:01:31 +08:00
l0ng-ai 48a13cb8fa fix(terminal): paste paths of files dragged from the Project view (#3511)
The terminal took file paths only from OS drops (Finder / Explorer). A
file or folder dragged from the Project view onto the terminal did nothing.
The terminal is now a drop target for Project view drags too and pastes the
paths at the prompt, shell-quoted, without executing; it also works in a
remote window, where the paths are the remote project's.

Fixes #3503
2026-11-15 17:28:05 +08:00
l0ng-ai c9488df786 fix(appearance): red-green vision setting also adjusts editor colours (#3510)
Adjust colors for red-green vision deficiency only recoloured VCS file
status, change markers and success, so in a file without changes it had no
visible effect. With the bundled dark and light schemes it now also uses the
schemes' red-green variants for syntax (keywords, strings, numbers, fields,
functions, annotations, TODO), errors (orange instead of red), warnings,
identifier-under-caret and search highlights, breakpoint lines and coverage.
Other colour themes and plugin themes keep their own editor colours.

Fixes #3500
2026-11-15 17:28:01 +08:00
l0ng-ai 4427ec2c07 fix(ui): restore hover backgrounds on the main menu and Review Mode buttons (#3509)
The main menu button (Windows and Linux title bar) and the Review Mode comment navigation buttons are plain buttons, so #2990's IconButton hover did not reach them. They paint --bg-toolbar-hover again; the main menu button keeps it while its menu is open. Gutter run markers, diff arrows and the database banner close button keep their icon-only hover.
2026-11-15 17:26:02 +08:00
Mr0Bread cf71a61cdf fix(ui): restore toolbar icon hover feedback (#2990)
Toolbar and tool window icon buttons (IconButton) paint --bg-toolbar-hover across their hit target again, so hovering shows the clickable area. Disabled buttons stay transparent; pressed, selected, focus ring and icon colours are unchanged. The hover colours match the toolbar tokens already used for the pressed state in Islands Light and Dark.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 17:23:13 +08:00
l0ng-ai f9af0e7bff fix(editor): offer to make a read-only file writable when editing it (#3508)
A file with the read-only attribute set (often kept when copying files in
Explorer) opened read-only, and typing into it did nothing beyond the
banner. Typing, pasting or dropping into such a file now asks to make it
writable (the same question as Toggle Read-only Attribute) and clears the
attribute on confirm. Binary, too-large and library documents still refuse
edits without asking.

Fixes #3479
2026-11-15 17:15:50 +08:00
Akbar Husain 6449b68bb0 feat(debug): debug Zig under CodeLLDB (#3392)
Zig programs now debug under CodeLLDB with sourceLanguages: [] so expressions aren't evaluated as Rust; the context menu of a closed .zig file reads its content; rerunning failed tests of a zig build test step derives a standalone zig test from the module root detect/zig.rs records per step (zig build forwards no args to the test binary). Adds the zig-app fixture's failing test step and run/debug smoke cases. The Language smoke CI job for zig is left for a separate change.

Part of #3260

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 17:13:12 +08:00
Mr0Bread 5d2d814610 fix(trust): list Restricted Mode commands by name; snapshot every command's trust class (#3394)
Restricted Mode allowed commands by 19 name prefixes, so any new command matching a prefix was allowed without review. It now lists each allowed command by exact name; a new command is denied until it is listed. src-tauri/tests/commands.snap records every command's trust class, remote placement, bindings presence and sync/async mode, regenerated by the export_bindings test and checked for drift in CI next to src/bindings.ts. The unused bytes_ prefix is gone; doc_open_untitled, doc_save_as and doc_python_facts, added on main since, stay allowed by name.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 17:11:59 +08:00
l0ng-ai 3f18a8a274 fix(project-view): paste a clipboard image as img.png (#3507)
Pasting into the Project view only handled files, so a screenshot on the
clipboard did nothing. With no files to paste, Paste now saves the clipboard
image in the target folder as img.png (img_1.png, img_2.png ... when taken)
and selects it; Paste is enabled while the clipboard holds an image.

The image is read natively: public.png, or public.tiff converted, on macOS;
the registered PNG format, or CF_DIB (24/32-bit) encoded as PNG, on Windows;
GTK on Linux as before.

Fixes #3486
2026-11-15 17:10:11 +08:00
l0ng-ai f8a8ecb662 fix(tools): name a tool relative to its Windows wrapper so a non-ASCII user directory works (#3376)
Windows tool wrappers held the tool's absolute path as UTF-8, which cmd.exe reads in the console code page, so a non-ASCII user directory broke every language server and debugger. Wrappers now name paths inside the tool directory via %~dp0 (plain ASCII), and installed wrappers are rewritten at startup with the existing relocate_shims; GEM_HOME lines are covered too.

Fixes #3338
2026-11-15 17:06:56 +08:00
Deng Liuтаdengliu e2b1a2d732 fix(markdown): scale Mermaid diagrams, SVGs and images with preview font zoom (#3481)
Editor font zoom scaled the Markdown preview's text but left Mermaid diagrams, embedded SVGs and raster images at 1x: Mermaid writes a pixel max-width on its svg and images were only capped at 100%. The preview now publishes --markdown-zoom-scale and records each diagram's and image's intrinsic width (SVG viewBox/width/height, data-URL SVG headers, naturalWidth), sizing them as min(base, 100%) * scale so they follow zoom in/out/reset while staying clamped to the pane at 1x. Agent chat diagrams keep scale 1; Mermaid full-screen and PNG export share the same size helper.

Co-authored-by: dengliu <[email protected]>
2026-11-15 16:57:09 +08:00
Akbar Husain db5a306450 fix(vcs): handle checking out a branch held by another worktree (#3484)
Checking out a branch that another worktree has checked out fell through to the generic failure path with git's raw stderr. Checkout now returns CheckedOutInWorktree before touching the repository (no Smart Checkout stash), and the Worktree Conflict dialog offers Checkout Anyway (--ignore-other-worktrees), Open Existing Worktree, or Cancel. Git's pre-2.42 wording is recognised too, and overwriting such a branch via New Branch names the worktree instead of quoting git.

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 16:54:55 +08:00
Deng Liuтаdengliu bad9429e79 fix(agents): skip unselectable chrome and closed <details> in Find highlights (#3485)
Find in Conversation matched text in user-select:none chrome (summaries, roles, times), which WebKit paints over the next selectable row, and painted matches inside closed <details> that still report client rects. Those subtrees are left out of the matches, and matches in closed <details> count but are only highlighted once stepped into (which opens them).

Co-authored-by: dengliu <[email protected]>
2026-11-15 16:48:37 +08:00
Deng Liuтаdengliu c942374f8a fix(agents): apply Fit conversation to the window width live without restarting (#3483)
Off-screen conversation rows kept their old intrinsic heights when the column switched between 900px and full width (the stream's width doesn't change), so they are re-measured when the setting changes; Agents › Chat display preferences are client settings, so remote windows no longer overwrite them with the server's.

Co-authored-by: dengliu <[email protected]>
2026-11-15 16:48:07 +08:00
Mansur Akhmadiтаmansur-akhmadi 611b27b974 feat(run): Run with Fuzzing for Go fuzz targets (#3497)
A Go Fuzz function's gutter menu and the editor's More Run/Debug get GoLand's "Run '<name>' with Fuzzing": its go test configuration with -fuzz (anchored pattern, saved -run/-bench/-fuzz dropped) as a separate temporary configuration; refused for ./... or several packages, which go test -fuzz rejects.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:47:16 +08:00
Mansur Akhmadiтаmansur-akhmadi 71f948cc9f feat(run): Previous / Next Failed Test in the test results toolbar (#3502)
The test tree registers an occurrence navigator for the Run tool window (failed leaves), so ⌘⌥↑ / ⌘⌥↓ step through failures and open their source; toolbar buttons run the same actions and, as IDEA's FailedTestsNavigator, stop at the first / last failure. Merged with main's Expand All / Collapse All (toolbar: expand, collapse, previous, next).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:46:15 +08:00
Mansur Akhmadiтаmansur-akhmadi 79a750362a feat(run): Expand All / Collapse All in the test results toolbar (#3499)
Expand All opens every suite (filtered ones too); Collapse All leaves the top-level suites, as IDEA's test tree does. Bound to ⌘= / ⌘- (IntelliJ) while the test tree has focus, numpad keys in the Eclipse presets.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:44:26 +08:00
Mansur Akhmadiтаmansur-akhmadi f1c0d098ad feat(vcs): Group By › Repository toggle in the Commit tool window (#3490)
With several repositories, View Options › Group By has a Repository toggle (on by default, persisted) shared by the Commit tool window, Local Changes and the Commit dialog; directory nodes now carry their absolute path so repositories outside the project folder group correctly.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:42:47 +08:00
Mansur Akhmadiтаmansur-akhmadi d9c1a9ff22 feat(vcs): view and drop stashes in the Unstash dialog (#3495)
Show Changes opens Changes Between for stash@{n}^..stash@{n} in the dialog's repository; Drop Stash drops the selected stash after confirmation and reloads the list.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:42:26 +08:00
Mansur Akhmadiтаmansur-akhmadi e86011fc87 feat(vcs): choose the repository in the Stash dialog when the project has several (#3493)
With several repositories the Stash dialog shows the repository combo, starts on the given repository and shows that repository's branch; Stash Selected Files keeps stashing each file in its own repository.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:42:19 +08:00
Mansur Akhmadiтаmansur-akhmadi f80dd0aa49 feat(vcs): choose the repository in the Tag dialog when the project has several (#3488)
With several repositories the Tag dialog shows the repository combo (as Pull, Merge and Rebase do); tags are checked and created in the picked repository, ignoring late answers for the previous pick.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-15 16:42:12 +08:00
zhzhsxтаzhzhsx 832c397e0b fix(editor): hide the hover documentation while typing (#3491)
The hover tooltip stayed open and moved with the text while typing, covering the completion lookup. It now closes when the document or the selection changes, as Quick Documentation on hover does in IDEA.

Co-authored-by: zhzhsx <[email protected]>
2026-11-15 16:40:27 +08:00
l0ng-ai 0f91aac0d4 fix(completion): leave items their server inserts to the server (#3505)
kotlin-lsp items carry an empty text and a command that inserts them through a workspace edit. We added call parentheses to method items anyway (refreshName()(), an override's body followed by ()) and left the caret in front of the server's text. Items with an empty text get no parentheses, and the caret moves past the server's edit when it lands at the caret.
2026-11-15 16:38:37 +08:00
l0ng-ai d4b2ade24d fix(toolwindows): a window that loses its last tab takes its stripe button with it (#3504)
Hierarchy, Run and Debug hid when their last tab closed but kept their stripe button; Find and Find Usages stayed open and empty. Like IDEA (hide on empty content; Hierarchy unavailable without content), they now hide and drop their button until new content opens them again. Terminal keeps its button.
2026-11-15 16:35:49 +08:00
451 змінених файлів з 12067 додано та 1903 видалено

No files matched your search

+3 -3
Переглянути файл
@@ -98,10 +98,10 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast
# nextest ran export_bindings, which rewrites src/bindings.ts.
- name: Bindings are up to date
# nextest ran export_bindings, which rewrites src/bindings.ts and the command snapshot.
- name: Bindings and command snapshot are up to date
if: runner.os == 'Linux'
run: git diff --exit-code src/bindings.ts
run: git diff --exit-code src/bindings.ts src-tauri/tests/commands.snap
# The remote development server ships as a static Linux binary (release-build.yml):
# keep that build working.
+1
Переглянути файл
@@ -42,6 +42,7 @@ Visual style: dark, low-contrast greys, one cool accent
shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
- User-visible text goes through the text catalog: add every new string to both
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
Other locales may lack entries; their UI shows the English text until a translator adds it.
Створено
+6
Переглянути файл
@@ -4232,6 +4232,7 @@ dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"png 0.18.1",
]
[[package]]
@@ -4577,6 +4578,7 @@ dependencies = [
"ide-core",
"ide-extension",
"ide-text",
"memchr",
"parking_lot",
"regex-lite",
"serde",
@@ -4797,6 +4799,7 @@ name = "ide-sdk"
version = "0.1.45"
dependencies = [
"dunce",
"flate2",
"ide-core",
"ide-language",
"ide-run",
@@ -4806,6 +4809,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"tar",
"tempfile",
"toml 0.9.12+spec-1.1.0",
"tracing",
@@ -4962,6 +4966,7 @@ dependencies = [
"chardetng",
"dunce",
"encoding_rs",
"flate2",
"gix",
"globset",
"ide-core",
@@ -4972,6 +4977,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"tar",
"tempfile",
"tracing",
"trash",
+2
Переглянути файл
@@ -90,6 +90,8 @@ dunce = "1"
dirs = "6"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
tar = "0.4"
# search, index, language
grep-searcher = "0.1"
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@
</p>
<p align="center">
English · <a href="README.zh-CN.md">简体中文</a>
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
</p>
<p align="center">
+79
Переглянути файл
@@ -0,0 +1,79 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
</picture>
</p>
<p align="center">
Bildiğin IDE, Rust ile yeniden yazıldı.
</p>
<p align="center">
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>İndir</b></a>
&nbsp;·&nbsp;
<a href="https://openidea.sh">Belgeler</a>
&nbsp;·&nbsp;
<a href="#performans-karşılaştırması">Performans</a>
&nbsp;·&nbsp;
<a href="#eklentiler">Eklentiler</a>
&nbsp;·&nbsp;
<a href="#topluluk">Topluluk</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA, IntelliJ IDEA'nın çalışma biçimini (kısayol tuşlarını, araç pencerelerini,
her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir uygulamaya taşır.
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
önbellekler hazırken açma, 5 çalıştırmanın ortancası:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| ---------------------------------- | --------------------- | ---------------------- |
| Projeyle pencerenin açılması | **0,9 sn** | 3,1 sn |
| Hazır (CPU sakinleşti) | **1,1 sn** | 13,2 sn |
| Bellek (USS, tüm işlemler) | **169 MB** | 2011 MB |
| Hazır olana kadar CPU süresi | **2,4 sn** | 47,9 sn |
| Boştayken CPU | Bir çekirdeğin **%4**'ü | Bir çekirdeğin %7'si |
| Kapanma | **0,3 sn** | 5,9 sn |
`main` dalından derlenmiş bir OpenIDEA sürümü ve varsayılan ayar ve eklentilerle IDEA;
Windows 11, 32 çekirdekli AMD, 62 GB RAM.
IDEA, Python'u daha derinlemesine analiz eder; yani "hazır" iki tarafta aynı işi ifade etmez.
İkisi de dışarıdan, aynı yöntemle ölçüldü: kendi makinende ve projelerinde denemek için
[`perf/compare`](perf/compare) klasörüne bak.
## Eklentiler
Eklentiler; eylemler, kod tamamlama, hızlı düzeltmeler, araç pencereleri, özel editörler,
temalar, dosya simgeleri ve diller ekler. Korumalı (sandbox) WebAssembly bileşenleri olarak çalışırlar;
temalar, simge temaları ve diller için hiç kod yazmak gerekmez.
Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya da
`openidea-plugin new` ile kendininkini başlat. Ayrıntılar için [OpenIDEA eklentisi yazmak](https://openidea.sh/en/plugins) sayfasına ve
[resmi eklentilere](plugins/official) bak. Eklenti API'si hâlâ önizleme aşamasında.
## Topluluk
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
## Lisans
[Apache 2.0](LICENSE). Pakete dahil üçüncü taraf varlıklar [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md) dosyasında listelenir.
<sub>JetBrains ile bağlantılı değildir. IntelliJ IDEA, JetBrains s.r.o.'nun ticari markasıdır.</sub>
+8 -10
Переглянути файл
@@ -10,12 +10,14 @@ use crate::provider::ProviderSpec;
use crate::{Shared, client_info};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(3) } else { Duration::from_secs(120) };
/// Opens `session/new`, reads `configOptions`, and records per-model `thought_level` choices.
/// Opens `session/new`, reads `configOptions`, and records the `thought_level` choices of the
/// session's model: they describe that model only, and other models may offer different ones.
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<Discovered, String> {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
match run_once(shared, spec, prefer_stored).await {
@@ -62,21 +64,17 @@ async fn run_once(shared: &Arc<Shared>, spec: &ProviderSpec, strip_ambient: bool
.map_err(|e| e.to_string())?;
let mut options = config::options_of(&new);
config::add_client_options(&launch.id, &mut options);
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let effort = levels_for_model_from_slice(&options);
let levels: Vec<(String, Vec<AgentConfigOption>)> = match (model_option, effort) {
(Some(model), Some(effort)) if !model.values.is_empty() => {
model.values.iter().map(|v| (v.value.clone(), effort.clone())).collect()
}
(Some(model), Some(effort)) => model.current.clone().map(|m| vec![(m, effort)]).unwrap_or_default(),
_ => Vec::new(),
let model = options.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone());
let levels = match (model, levels_for_model_from_slice(&options)) {
(Some(model), Some(effort)) => BTreeMap::from([(model, effort)]),
_ => BTreeMap::new(),
};
let commands = updates
.commands
.lock()
.clone()
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
Ok::<_, String>(Discovered { config: options, commands, levels: levels.into_iter().collect() })
Ok::<_, String>(Discovered { config: options, commands, levels })
};
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
peer.kill();
+9
Переглянути файл
@@ -58,6 +58,8 @@ fn client_capabilities() -> Value {
"terminal": false,
// Subagents as sessions of their own (ACP subagents RFD; v2 baseline).
"subagents": {},
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
"elicitation": { "form": {} },
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
// only when the client advertises this flag (undocumented Cursor ACP extension).
"_meta": { "parameterizedModelPicker": true },
@@ -320,6 +322,13 @@ impl Handler for Dialect {
}
self.inner.on_request(method, params)
}
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
if self.v2() && method == "session/request_permission" {
return self.on_request_with_data(method, params);
}
self.inner.on_request_raw(method, params, raw)
}
}
/// A v2 permission request with the v1 `toolCall` (its subject's, titled with the request's title).
+5 -1
Переглянути файл
@@ -97,10 +97,13 @@ fn the_negotiating_request_carries_both_versions() {
p["clientCapabilities"]["_meta"]["parameterizedModelPicker"], true,
"Cursor and similar agents need parameterized model options (e.g. fast on/off)"
);
// Forms only: URL mode would open pages the agent names.
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
let mut expected = sent;
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
assert_eq!(expected, p["clientCapabilities"]);
}
@@ -168,7 +171,8 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
assert!(cursor.thought_levels.contains_key("m1") && cursor.thought_levels.contains_key("m2"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+53 -1
Переглянути файл
@@ -56,6 +56,16 @@ pub(crate) struct CatalogData {
pub refreshed_at_ms: Option<f64>,
}
impl CatalogData {
fn model_option(&self) -> Option<&AgentConfigOption> {
self.config.iter().find(|o| o.category.as_deref() == Some("model"))
}
fn lists(&self, model: &str) -> bool {
self.model_option().is_some_and(|o| o.values.iter().any(|v| v.value == model))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SavedCatalog {
@@ -329,11 +339,17 @@ impl AgentCatalogs {
Ok(found) => {
let mut cache = shared.known.lock();
let known = cache.entry(key.2.clone()).or_default();
let catalog = CatalogData {
let mut catalog = CatalogData {
config: found.config,
thought_levels: found.levels,
refreshed_at_ms: Some(self.epoch_ms()),
};
// Efforts sessions reported for models discovery doesn't read stay while listed.
for (model, levels) in entry.catalog.take().map(|old| old.thought_levels).unwrap_or_default() {
if catalog.lists(&model) && !catalog.thought_levels.contains_key(&model) {
catalog.thought_levels.insert(model, levels);
}
}
known.config = catalog.config.clone();
known.thought_levels = catalog.thought_levels.clone();
if let Some(commands) = found.commands {
@@ -366,6 +382,42 @@ impl AgentCatalogs {
}
}
/// Records the efforts a session reported for a listed `model` other than the one discovery
/// read: ACP discovery opens one session, so it knows only that model's efforts.
pub(crate) fn learn_levels(&self, shared: &Shared, provider: &str, model: &str, levels: Vec<AgentConfigOption>) {
let lacks = |catalog: &CatalogData| {
catalog.lists(model)
&& catalog.model_option().and_then(|o| o.current.as_deref()) != Some(model)
&& catalog.thought_levels.get(model) != Some(&levels)
};
let key = Self::key(shared, provider);
let mut state = self.state.lock();
let mut learned = false;
if let Some(catalog) = state.entries.get_mut(&key).and_then(|e| e.catalog.as_mut()).filter(|c| lacks(c)) {
catalog.thought_levels.insert(model.to_owned(), levels.clone());
learned = true;
}
let mut cache = shared.known.lock();
if let Some(saved) = cache
.get_mut(provider)
.and_then(|known| known.catalogs.get_mut(&shared.root_key()))
.filter(|saved| lacks(&saved.catalog))
{
saved.catalog.thought_levels.insert(model.to_owned(), levels);
learned = true;
}
if !learned {
return;
}
shared.persist_known(&cache);
drop(cache);
let snapshot = state.entries.get(&key).map(|entry| self.snapshot(shared, provider, entry));
drop(state);
if let Some(snapshot) = snapshot {
self.broadcast(shared, &snapshot);
}
}
fn subscribers(&self, shared: &Shared) -> Vec<Arc<Shared>> {
self.state
.lock()
+38 -1
Переглянути файл
@@ -199,7 +199,8 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
let fresh = completed(&mut events).await;
assert_eq!(model_values(&fresh), ["retained", "new"]);
assert_eq!(fresh.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["new", "retained"]);
// The session's efforts describe its own model, not "new".
assert_eq!(fresh.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["retained"]);
assert_eq!(fresh.thought_levels["retained"][0].values[0].value, "medium");
assert!(fresh.refreshed_at_ms.is_some() && fresh.retry_at_ms.is_some());
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
@@ -220,6 +221,42 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
}
#[tokio::test]
async fn a_session_adds_the_efforts_of_a_model_discovery_did_not_read() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let mut harness = Harness::new();
let catalogs = Arc::new(AgentCatalogs::default());
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false).unwrap();
harness.next().await.reply.send(Ok(response(&["first", "second"], &["low", "high"]))).unwrap();
completed(&mut events).await;
// A session on "second" reports its own efforts; one on a model the catalog lacks, or on
// "first" with other efforts, changes nothing.
let second = config::options_of(&response(&["second"], &["off", "auto"]));
manager.shared.remember(PROVIDER, Some(&second), None, Some("second"));
manager.shared.remember(PROVIDER, Some(&config::options_of(&response(&["gone"], &["x"]))), None, Some("gone"));
manager.shared.remember(PROVIDER, Some(&config::options_of(&response(&["first"], &["max"]))), None, Some("first"));
let efforts = |catalog: &AgentModelCatalog, model: &str| -> Vec<String> {
catalog.thought_levels[model][0].values.iter().map(|v| v.value.clone()).collect()
};
let catalog = manager.refresh_models(PROVIDER, false).unwrap();
assert_eq!(catalog.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["first", "second"]);
assert_eq!(efforts(&catalog, "first"), ["low", "high"]);
assert_eq!(efforts(&catalog, "second"), ["off", "auto"]);
let restored = make_manager(tmp.path(), Arc::default(), &harness).refresh_models(PROVIDER, false).unwrap();
assert_eq!(efforts(&restored, "second"), ["off", "auto"], "persisted with the project's catalog");
// Discovery again reads "first" only; "second" keeps what its session reported.
advance(&catalogs, 60);
while events.try_recv().is_ok() {}
manager.refresh_models(PROVIDER, true).unwrap();
harness.next().await.reply.send(Ok(response(&["first", "second"], &["medium"]))).unwrap();
let fresh = completed(&mut events).await;
assert_eq!(efforts(&fresh, "first"), ["medium"]);
assert_eq!(efforts(&fresh, "second"), ["off", "auto"]);
}
#[tokio::test]
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
let tmp = tempfile::tempdir().unwrap();
+305
Переглянути файл
@@ -0,0 +1,305 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::{Map, Value, json};
/// The reply that declines the form; a JSON object of field name to values accepts it, and
/// anything else cancels it.
const DECLINE: &str = "decline";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
return Err("only form elicitation is supported".to_owned());
}
let schema = params.get("requestedSchema").ok_or("requestedSchema is missing")?;
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let properties = schema.get("properties").and_then(Value::as_object).ok_or("requestedSchema has no properties")?;
let fields = properties
.iter()
.map(|(name, property)| field(name, property, required.contains(&name.as_str())))
.collect::<Result<_, _>>()?;
Ok(AgentForm { fields })
}
/// Orders the fields as the request's schema lists them: `Value` keeps object keys sorted, and
/// the agent's order is the one its form reads in.
pub(crate) fn in_schema_order(form: &mut AgentForm, raw: &[u8]) {
#[derive(Deserialize)]
struct Request {
params: Params,
}
#[derive(Deserialize)]
struct Params {
#[serde(rename = "requestedSchema")]
schema: Schema,
}
#[derive(Deserialize)]
struct Schema {
properties: Keys,
}
struct Keys(Vec<String>);
impl<'de> Deserialize<'de> for Keys {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Visit;
impl<'de> Visitor<'de> for Visit {
type Value = Keys;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("an object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Keys, A::Error> {
let mut keys = Vec::new();
while let Some((key, IgnoredAny)) = map.next_entry::<String, IgnoredAny>()? {
keys.push(key);
}
Ok(Keys(keys))
}
}
deserializer.deserialize_map(Visit)
}
}
let Ok(request) = serde_json::from_slice::<Request>(raw) else { return };
let order = request.params.schema.properties.0;
form.fields.sort_by_key(|field| order.iter().position(|name| *name == field.name).unwrap_or(usize::MAX));
}
fn field(name: &str, property: &Value, required: bool) -> Result<AgentFormField, String> {
let text = |key: &str| property.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_owned();
let number = |key: &str| property.get(key).and_then(Value::as_f64);
let unsupported = || format!("field {name} has an unsupported schema");
let (kind, options, min, max) = match property.get("type").and_then(Value::as_str) {
Some("string") => match choices(property) {
Some(options) => (AgentFormFieldKind::Choice, options, None, None),
None => (AgentFormFieldKind::Text, Vec::new(), number("minLength"), number("maxLength")),
},
Some("number") => (AgentFormFieldKind::Number, Vec::new(), number("minimum"), number("maximum")),
Some("integer") => (AgentFormFieldKind::Integer, Vec::new(), number("minimum"), number("maximum")),
Some("boolean") => (AgentFormFieldKind::Boolean, Vec::new(), None, None),
Some("array") => {
let options = property.get("items").and_then(choices).ok_or_else(unsupported)?;
(AgentFormFieldKind::Choices, options, number("minItems"), number("maxItems"))
}
_ => return Err(unsupported()),
};
let default = match property.get("default") {
Some(Value::Array(values)) => values.iter().filter_map(scalar).collect(),
Some(value) => scalar(value).into_iter().collect(),
None => Vec::new(),
};
let title = text("title");
Ok(AgentFormField {
name: name.to_owned(),
title: if title.is_empty() { name.to_owned() } else { title },
description: text("description"),
required,
kind,
options,
default,
min,
max,
})
}
/// The values of a choice: `enum` (titled by the legacy `enumNames`), or `oneOf` / `anyOf`
/// of `{ const, title }`.
fn choices(schema: &Value) -> Option<Vec<AgentFormOption>> {
let option = |value: &str, label: Option<&str>, description: Option<&str>| AgentFormOption {
value: value.to_owned(),
label: label.filter(|l| !l.trim().is_empty()).unwrap_or(value).to_owned(),
description: description.unwrap_or_default().trim().to_owned(),
};
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
let names = schema.get("enumNames").and_then(Value::as_array);
return Some(
values
.iter()
.enumerate()
.filter_map(|(i, value)| {
Some(option(value.as_str()?, names.and_then(|n| n.get(i)).and_then(Value::as_str), None))
})
.collect(),
);
}
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf"))?.as_array()?;
Some(
listed
.iter()
.filter_map(|o| {
let text = |key: &str| o.get(key).and_then(Value::as_str);
Some(option(text("const")?, text("title"), text("description")))
})
.collect(),
)
}
fn scalar(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(flag) => Some(flag.to_string()),
_ => None,
}
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
}
/// The `elicitation/create` response to the user's `reply`, and what the conversation
/// records as chosen.
pub(crate) fn answer(form: &AgentForm, reply: Option<&str>) -> (Value, String) {
let values = match reply {
Some(DECLINE) => return (json!({ "action": "decline" }), "Decline".to_owned()),
Some(reply) => serde_json::from_str::<Map<String, Value>>(reply).ok(),
None => None,
};
let Some(values) = values else { return (json!({ "action": "cancel" }), "Cancelled".to_owned()) };
let mut content = Map::new();
let mut shown = Vec::new();
for field in &form.fields {
let given: Vec<&str> = match values.get(&field.name) {
Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(),
Some(Value::String(item)) => vec![item.as_str()],
_ => Vec::new(),
};
let given: Vec<&str> = given.into_iter().map(str::trim).filter(|v| !v.is_empty()).collect();
let Some(&first) = given.first() else { continue };
let value = match field.kind {
AgentFormFieldKind::Text | AgentFormFieldKind::Choice => json!(first),
AgentFormFieldKind::Number => match first.parse::<f64>() {
Ok(number) => json!(number),
Err(_) => continue,
},
AgentFormFieldKind::Integer => match first.parse::<i64>() {
Ok(number) => json!(number),
Err(_) => continue,
},
AgentFormFieldKind::Boolean => json!(first == "true"),
AgentFormFieldKind::Choices => json!(given),
};
let label = |value: &str| {
field.options.iter().find(|o| o.value == value).map_or_else(|| value.to_owned(), |o| o.label.clone())
};
let text = match field.kind {
AgentFormFieldKind::Boolean => (if first == "true" { "yes" } else { "no" }).to_owned(),
AgentFormFieldKind::Choices => given.iter().map(|v| label(v)).collect::<Vec<_>>().join(", "),
_ => label(first),
};
shown.push(format!("{}: {text}", field.title));
content.insert(field.name.clone(), value);
}
let chosen = if shown.is_empty() { "Submitted".to_owned() } else { shown.join("; ") };
(json!({ "action": "accept", "content": content }), chosen)
}
#[cfg(test)]
mod tests {
use super::*;
/// The form OMP's `ask` tool sends: a choice with a recommended default, then an
/// optional typed answer beside it.
fn ask() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Which database?",
"requestedSchema": { "type": "object", "properties": {
"q0": { "type": "string", "title": "Which database?", "description": "Storage",
"oneOf": [{ "const": "pg", "title": "Postgres", "description": "Relational" },
{ "const": "sqlite", "title": "SQLite" }],
"default": "pg" },
"q0__other": { "type": "string", "title": "Other (type your own)" }
} }
})
}
#[test]
fn fields_follow_the_schema_order() {
let raw = br#"{ "jsonrpc": "2.0", "id": 3, "method": "elicitation/create", "params": { "mode": "form",
"requestedSchema": { "type": "object", "properties": {
"strategy": { "type": "string" }, "tests": { "type": "boolean" }, "note": { "type": "string" }
} } } }"#;
let params = serde_json::from_slice::<Value>(raw).unwrap()["params"].take();
let mut form = form_of(&params).unwrap();
in_schema_order(&mut form, raw);
assert_eq!(form.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["strategy", "tests", "note"]);
}
#[test]
fn reads_choices_and_text_fields() {
let form = form_of(&ask()).unwrap();
let [choice, other] = form.fields.as_slice() else { panic!("{form:?}") };
assert_eq!((choice.name.as_str(), choice.kind, choice.required), ("q0", AgentFormFieldKind::Choice, false));
assert_eq!(choice.options[0].label, "Postgres");
assert_eq!(choice.options[0].description, "Relational");
assert_eq!(choice.default, ["pg"]);
assert_eq!((other.kind, other.title.as_str()), (AgentFormFieldKind::Text, "Other (type your own)"));
}
#[test]
fn reads_every_restricted_schema_kind() {
let form = form_of(&json!({ "mode": "form", "requestedSchema": {
"type": "object", "required": ["count"],
"properties": {
"count": { "type": "integer", "minimum": 1, "maximum": 5 },
"ratio": { "type": "number" },
"ok": { "type": "boolean", "default": true },
"size": { "type": "string", "enum": ["s", "l"], "enumNames": ["Small", "Large"] },
"tags": { "type": "array", "items": { "anyOf": [{ "const": "a" }, { "const": "b" }] },
"default": ["b"], "maxItems": 2 }
}
} }))
.unwrap();
let field = |name: &str| form.fields.iter().find(|f| f.name == name).unwrap();
use AgentFormFieldKind::*;
let kinds: Vec<_> = ["count", "ratio", "ok", "size", "tags"].map(|name| field(name).kind).into();
assert_eq!(kinds, [Integer, Number, Boolean, Choice, Choices]);
assert!(field("count").required && !field("ratio").required);
assert_eq!((field("count").min, field("count").max), (Some(1.0), Some(5.0)));
assert_eq!(field("ok").default, ["true"]);
assert_eq!(field("size").options[1].label, "Large");
assert_eq!((field("tags").default.as_slice(), field("tags").max), (["b".to_owned()].as_slice(), Some(2.0)));
}
#[test]
fn url_mode_and_unsupported_fields_are_refused() {
assert!(form_of(&json!({ "mode": "url", "url": "https://example.com" })).is_err());
let nested = json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"address": { "type": "object" }
} } });
assert!(form_of(&nested).is_err());
}
#[test]
fn an_answer_is_typed_by_its_field() {
let form = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"count": { "type": "integer" },
"ok": { "type": "boolean" },
"size": { "type": "string", "oneOf": [{ "const": "s", "title": "Small" }] },
"tags": { "type": "array", "items": { "enum": ["a", "b"] } },
"note": { "type": "string" }
} } }))
.unwrap();
let reply = json!({ "count": ["3"], "ok": ["false"], "size": ["s"], "tags": ["a", "b"], "note": [" "] });
let (response, chosen) = answer(&form, Some(&reply.to_string()));
assert_eq!(
response,
json!({ "action": "accept", "content": { "count": 3, "ok": false, "size": "s", "tags": ["a", "b"] } })
);
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
assert_eq!(answer(&form, Some(DECLINE)), (json!({ "action": "decline" }), "Decline".to_owned()));
assert_eq!(answer(&form, None).0, json!({ "action": "cancel" }));
assert_eq!(answer(&form, Some("cancel")).0, json!({ "action": "cancel" }));
}
}
+106 -20
Переглянути файл
@@ -11,6 +11,7 @@ mod acp;
mod catalogs;
mod config;
mod conversation;
mod elicitation;
mod external;
pub mod mcp;
mod model;
@@ -223,6 +224,7 @@ impl Shared {
commands: Option<&[AgentCommand]>,
model: Option<&str>,
) {
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
let mut changed = false;
@@ -244,6 +246,12 @@ impl Shared {
changed = true;
}
}
// Discovery reads one model's efforts; a session on another model reports that model's.
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
let levels: Vec<_> =
config.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
(model, levels)
});
if let Some(commands) = commands.filter(|c| !c.is_empty())
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
{
@@ -254,6 +262,9 @@ impl Shared {
self.persist_known(&cache);
}
drop(cache);
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
if changed {
self.emit(AgentEvent::Providers);
}
@@ -1861,12 +1872,24 @@ impl Task {
let s = self.state.lock();
s.busy && s.task.status == AgentStatus::Running
};
let Some(live) = live.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images)) else {
let Some((live, method)) = live
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
.and_then(|l| steer_method(&l.init).map(|m| (l, m)))
else {
return Err(prompt);
};
let content = self.content(&live, &prompt).await;
let sent: Result<Value, RpcError> =
live.peer.request("_openidea/steer", json!({ "sessionId": live.session, "prompt": content }), None).await;
live.peer.request(method, json!({ "sessionId": live.session, "prompt": content }), None).await;
// `_session/steering` answers with an outcome: only `injected` joined the turn
// (`promptRequired`: no turn is running any more).
let sent = match sent {
Ok(reply) => match reply.get("outcome").and_then(Value::as_str) {
None | Some("injected") => Ok(()),
Some(outcome) => Err(reply.get("reason").and_then(Value::as_str).unwrap_or(outcome).to_owned()),
},
Err(e) => Err(e.to_string()),
};
if let Err(e) = sent {
// The turn ended meanwhile: the message waits for the next one instead.
tracing::debug!("agent task {}: steering failed: {e}", self.id);
@@ -2366,12 +2389,7 @@ impl Task {
// first question says what it wants, as the Claude Code adapter titles its own.
let title =
if by_index { questions.first().map(|question| question.question.clone()).unwrap_or(title) } else { title };
// A subagent's request is answered in the task's conversation, named after the subagent.
let session = params.get("sessionId").and_then(Value::as_str);
let title = match session.and_then(|s| self.state.lock().conversation.label(s)) {
Some(label) => format!("{label}: {title}"),
None => title,
};
let title = self.labelled(params, title);
let options: Vec<AgentPermissionOption> = params
.get("options")
.and_then(Value::as_array)
@@ -2403,6 +2421,7 @@ impl Task {
command: None,
options,
questions: Vec::new(),
form: None,
chosen: Some("Denied: side conversations are read-only".to_owned()),
});
return match reject {
@@ -2429,6 +2448,7 @@ impl Task {
command: shown.clone(),
options,
questions: Vec::new(),
form: None,
chosen: Some(format!("Blocked by policy ({pattern})")),
});
return match reject {
@@ -2449,6 +2469,7 @@ impl Task {
command: shown.clone(),
options,
questions: Vec::new(),
form: None,
chosen: Some(format!("{} (whitelisted)", allow.name)),
});
return json!({ "outcome": { "outcome": "selected", "optionId": allow.id } });
@@ -2464,6 +2485,7 @@ impl Task {
command: shown,
options: options.clone(),
questions,
form: None,
chosen: None,
});
self.permissions.lock().insert(id, tx);
@@ -2490,17 +2512,7 @@ impl Task {
.and_then(|reply| options.iter().find(|option| &option.id == reply))
.map_or_else(|| "Cancelled".to_owned(), |option| option.name.clone()),
};
{
let mut s = self.state.lock();
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
*chosen = Some(name);
}
}
self.mark_dirty([(None, entry)]);
let still_asking = !self.permissions.lock().is_empty();
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
self.set_status(AgentStatus::Running, None);
}
self.settle(entry, name);
// An agent that answers by index reads the answers beside the outcome, keyed by
// question index, with its Submit option chosen; anything less cancels the request.
if by_index {
@@ -2532,6 +2544,57 @@ impl Task {
}
}
/// A request from a subagent is answered in the task's conversation, named after the subagent.
fn labelled(&self, params: &Value, title: String) -> String {
let session = params.get("sessionId").and_then(Value::as_str);
match session.and_then(|s| self.state.lock().conversation.label(s)) {
Some(label) => format!("{label}: {title}"),
None => title,
}
}
/// An agent's form (`elicitation/create`): asked in the conversation like a permission
/// request, and answered with its values, declined or cancelled. Blocks like `ask_permission`.
fn elicit(self: &Arc<Self>, params: &Value, raw: Option<&[u8]>) -> Result<Value, String> {
let mut form = elicitation::form_of(params)?;
if let Some(raw) = raw {
elicitation::in_schema_order(&mut form, raw);
}
let id = self.next_permission.fetch_add(1, Ordering::Relaxed);
let message = params.get("message").and_then(Value::as_str).unwrap_or_default().trim().to_owned();
let (tx, rx) = std::sync::mpsc::channel();
let entry = self.push_entry(AgentEntry::Permission {
id,
title: self.labelled(params, message),
command: None,
options: elicitation::options(),
questions: Vec::new(),
form: Some(form.clone()),
chosen: None,
});
self.permissions.lock().insert(id, tx);
self.set_status(AgentStatus::NeedsInput, None);
let reply = rx.recv().ok().flatten();
let (response, chosen) = elicitation::answer(&form, reply.as_deref());
self.settle(entry, chosen);
Ok(response)
}
/// Records the answer to the request at `entry`; the turn runs on once nothing else waits.
fn settle(self: &Arc<Self>, entry: usize, chosen: String) {
{
let mut s = self.state.lock();
if let Some(AgentEntry::Permission { chosen: answer, .. }) = s.conversation.main.entries.get_mut(entry) {
*answer = Some(chosen);
}
}
self.mark_dirty([(None, entry)]);
let still_asking = !self.permissions.lock().is_empty();
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
self.set_status(AgentStatus::Running, None);
}
}
fn approve_pending(&self) {
let s = self.state.lock();
if self.cancel_pending.load(Ordering::Acquire) || !config::bypass_approvals(&s.task.config) {
@@ -2596,9 +2659,18 @@ impl Handler for Client {
let task = self.task.upgrade().ok_or((codes::INTERNAL_ERROR, "task closed".to_owned()))?;
match method {
"session/request_permission" => Ok(task.ask_permission(&params)),
"elicitation/create" => task.elicit(&params, None).map_err(|e| (codes::INVALID_PARAMS, e)),
_ => Err((codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
}
}
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
if method != "elicitation/create" {
return self.on_request_with_data(method, params);
}
let task = self.task.upgrade().ok_or((codes::INTERNAL_ERROR, "task closed".to_owned(), None))?;
task.elicit(&params, Some(raw)).map_err(|e| (codes::INVALID_PARAMS, e, None))
}
}
/// The prompt trimmed, or `None` when there is nothing to send.
@@ -2865,13 +2937,27 @@ fn shown_background(tasks: &[Value], known: &[AgentBackgroundTask]) -> Vec<Agent
.collect()
}
/// The method that adds a message to the running turn: OpenIDEA's own, or the
/// `_session/steering` extension an agent advertises in the response's top-level `_meta`
/// (OMP).
fn steer_method(init: &acp::Negotiated) -> Option<&'static str> {
let supported = |v: Option<&Value>| v.and_then(Value::as_bool) == Some(true);
if supported(init.meta("/openidea/steer")) {
Some("_openidea/steer")
} else if supported(init.meta.as_ref().and_then(|m| m.pointer("/steering/supported"))) {
Some("_session/steering")
} else {
None
}
}
fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
let meta = |p: &str| init.meta(p).and_then(Value::as_bool) == Some(true);
let capabilities = AgentCapabilities {
images: init.prompt("image"),
fork: init.session("fork"),
rollback: meta("/openidea/rollback"),
steer: meta("/openidea/steer"),
steer: steer_method(init).is_some(),
background_tasks: meta("/openidea/backgroundTasks"),
read_only: false,
};
+57
Переглянути файл
@@ -316,6 +316,59 @@ pub struct AgentQuestionOption {
pub preview: Option<String>,
}
/// A form the agent asks the user to fill in (ACP `elicitation/create`, form mode).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentForm {
pub fields: Vec<AgentFormField>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentFormField {
/// The property name the answer is keyed by.
pub name: String,
pub title: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub required: bool,
pub kind: AgentFormFieldKind,
/// The choices of a `choice` or `choices` field.
#[serde(default)]
pub options: Vec<AgentFormOption>,
/// The initial answer: option values, a text, a number, or `true` / `false`.
#[serde(default)]
pub default: Vec<String>,
/// Bounds: the number of a `number` / `integer`, the length of a `text`, the count of `choices`.
#[serde(default)]
pub min: Option<f64>,
#[serde(default)]
pub max: Option<f64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentFormFieldKind {
Text,
Number,
Integer,
Boolean,
/// One of `options`.
Choice,
/// Any of `options`.
Choices,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentFormOption {
pub value: String,
pub label: String,
#[serde(default)]
pub description: String,
}
/// One item of a task's conversation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
@@ -396,6 +449,10 @@ pub enum AgentEntry {
/// of question to answer instead of an option.
#[serde(default)]
questions: Vec<AgentQuestion>,
/// Set when the agent asks for a form (ACP elicitation); answered with a JSON object of
/// field name to its values, `decline`, or nothing to cancel.
#[serde(default)]
form: Option<AgentForm>,
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
chosen: Option<String>,
},
+119
Переглянути файл
@@ -51,6 +51,9 @@ struct FakeAgent {
/// Config options `session/new` reports after the model one (per-model efforts, say).
extra_options: Mutex<Vec<Value>>,
model_options: Mutex<HashMap<String, Vec<Value>>>,
/// Advertises steering as OMP does (`_meta.steering` at the top of `initialize`)
/// instead of `_meta.openidea.steer`.
session_steering: bool,
}
impl FakeAgent {
@@ -156,6 +159,10 @@ impl Handler for FakeAgent {
if params.pointer("/clientCapabilities/subagents").is_some_and(Value::is_object) {
self.calls.lock().push("subagents".into());
}
if self.session_steering {
return Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true},
"_meta": {"steering": {"supported": true}}}));
}
Ok(
json!({"protocolVersion": 1, "authMethods": self.auth_methods, "agentCapabilities": {"loadSession": !self.no_load,
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true, "backgroundTasks": true}}}}),
@@ -183,6 +190,13 @@ impl Handler for FakeAgent {
self.calls.lock().push(format!("{method} {detail}"));
Ok(json!({}))
}
"_session/steering" => {
let text = params["prompt"][0]["text"].clone();
self.calls.lock().push(format!("{method} {text}"));
// OMP answers whether the message joined the turn rather than failing.
let outcome = if text == "too late" { "promptRequired" } else { "injected" };
Ok(json!({"outcome": outcome, "queue": "steering"}))
}
"session/load" => {
self.say(&session, "replayed history");
Ok(json!({}))
@@ -281,6 +295,23 @@ impl Handler for FakeAgent {
self.say(&session, &format!("escalation chose {chosen}"));
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "form" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"elicitation/create",
json!({"sessionId": session, "mode": "form", "message": "How should I refactor?",
"requestedSchema": {"type": "object", "required": ["strategy"], "properties": {
"strategy": {"type": "string", "title": "Strategy",
"oneOf": [{"const": "safe", "title": "Conservative"},
{"const": "bold", "title": "Aggressive"}]},
"tests": {"type": "boolean", "title": "Run tests"}}}}),
None,
))
.unwrap();
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "ask" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
@@ -1060,6 +1091,42 @@ fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
#[tokio::test(flavor = "multi_thread")]
async fn steers_through_session_steering() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent { session_steering: true, ..FakeAgent::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("wait"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
assert!(mgr.task(&task.id).unwrap().state.lock().task.capabilities.steer);
mgr.prompt(&task.id, text("also this"), true).await.unwrap();
assert!(agent.calls.lock().iter().any(|c| c == "_session/steering \"also this\""));
let entries = mgr.entries(&task.id, None).unwrap();
assert!(matches!(entries.last(), Some(AgentEntry::User { steered: true, .. })));
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
// The agent didn't take it into the turn: the turn stops and it goes next, as without
// steering (the fake agent's next turn asks for permission).
mgr.prompt(&task.id, text("too late"), true).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: false, .. } if text == "too late")));
assert!(!entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: true, .. } if text == "too late")));
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
let tmp = tempfile::tempdir().unwrap();
@@ -1985,6 +2052,58 @@ async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permis
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are_bypassed() {
let accept = json!({"strategy": ["bold"], "tests": ["true"]}).to_string();
for (reply, said, chosen) in [
(
Some(accept.as_str()),
r#"form {"action":"accept","content":{"strategy":"bold","tests":true}}"#,
"Strategy: Aggressive; Run tests: yes",
),
(Some("decline"), r#"form {"action":"decline"}"#, "Decline"),
(None, r#"form {"action":"cancel"}"#, "Cancelled"),
] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("form"),
provider: "cursor".into(),
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, form) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|entry| match entry {
AgentEntry::Permission { id, title, form: Some(form), chosen: None, .. }
if title == "How should I refactor?" =>
{
Some((id, form))
}
_ => None,
})
.unwrap();
assert_eq!(form.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["strategy", "tests"]);
mgr.respond(&task.id, id, reply.map(str::to_owned)).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == chosen)),
"{entries:?}"
);
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
+1
Переглянути файл
@@ -441,6 +441,7 @@ mod tests {
command: None,
options: vec![],
questions: vec![],
form: None,
chosen: None,
});
assert_eq!(t.end_turn(None), vec![2, 3]);
+9 -3
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -9,8 +9,14 @@ license.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", default-features = false, features = ["std"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSBitmapImageRep", "NSImageRep", "NSPasteboard"] }
[target.'cfg(windows)'.dependencies]
png = "0.18"
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
[dev-dependencies]
png = "0.18"
+222 -3
Переглянути файл
@@ -18,6 +18,10 @@
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
//! `PNG` format or `CF_DIB` on Windows. Linux reads it through GTK in the app.
use std::path::PathBuf;
@@ -34,6 +38,19 @@ pub fn text() -> Option<String> {
imp::text()
}
/// The clipboard's image as PNG bytes, None when it holds none. Call on the main
/// thread on macOS.
#[cfg(any(windows, target_os = "macos"))]
pub fn png() -> Option<Vec<u8>> {
imp::png()
}
/// Whether the clipboard holds an image, without reading it. Call on the main
/// thread on macOS and Linux.
pub fn has_image() -> bool {
imp::has_image()
}
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
const HEADER: usize = 20;
@@ -134,9 +151,62 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
out
}
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
#[cfg(any(windows, test))]
const BI_RGB: u32 = 0;
#[cfg(any(windows, test))]
const BI_BITFIELDS: u32 = 3;
/// A packed DIB (`BITMAPINFOHEADER` or a later header, then the pixels) as PNG.
/// Only 24- and 32-bit uncompressed bitmaps, which is what screenshots and
/// copied images are; None for anything else. A 32-bit bitmap whose alpha is
/// all zero (most writers leave it unset) is opaque.
#[cfg(any(windows, test))]
fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
let u32_at = |at: usize| dib.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let header = u32_at(0)? as usize;
let width = u32_at(4)? as i32;
let height = u32_at(8)? as i32;
let bits = u16::from_le_bytes([*dib.get(14)?, *dib.get(15)?]);
let compression = u32_at(16)?;
if header < 40 || width <= 0 || height == 0 || !matches!(bits, 24 | 32) {
return None;
}
if compression != BI_RGB && !(compression == BI_BITFIELDS && bits == 32) {
return None;
}
// A `BITMAPINFOHEADER` keeps the three bitfield masks after it; later
// headers hold them inside. Masks other than BGRA's are not supported.
let masks = if compression == BI_BITFIELDS && header == 40 { 12 } else { 0 };
let colors = u32_at(32)? as usize;
let (width, rows) = (width as usize, height.unsigned_abs() as usize);
let stride = (width * bits as usize).div_ceil(32) * 4;
let start = header + masks + colors * 4;
let pixels = dib.get(start..start.checked_add(stride.checked_mul(rows)?)?)?;
let step = bits as usize / 8;
let mut rgba = Vec::with_capacity(width * rows * 4);
for row in 0..rows {
// A positive height stores the bottom row first.
let source = if height > 0 { rows - 1 - row } else { row };
let line = &pixels[source * stride..source * stride + width * step];
for px in line.chunks_exact(step) {
rgba.extend_from_slice(&[px[2], px[1], px[0], if step == 4 { px[3] } else { 255 }]);
}
}
if step == 4 && rgba.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
rgba.as_chunks_mut::<4>().0.iter_mut().for_each(|px| px[3] = 255);
}
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width as u32, rows as u32);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().ok()?.write_image_data(&rgba).ok()?;
Some(out)
}
#[cfg(windows)]
mod imp {
use super::{HEADER, decode, encode, names_text};
use super::{HEADER, decode, dib_to_png, encode, names_text};
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr;
@@ -164,6 +234,59 @@ mod imp {
fn GetClipboardData(format: u32) -> Handle;
fn SetClipboardData(format: u32, memory: Handle) -> Handle;
fn IsClipboardFormatAvailable(format: u32) -> i32;
fn RegisterClipboardFormatW(name: *const u16) -> u32;
}
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
fn png_format() -> u32 {
let name: Vec<u16> = "PNG\0".encode_utf16().collect();
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
}
pub fn has_image() -> bool {
let png = png_format();
(png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0)
|| unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0
}
/// A copy of the clipboard's `format` block. Call with the clipboard open.
fn read_block(format: u32) -> Option<Vec<u8>> {
// SAFETY: the clipboard keeps the block alive while it is open, and
// `GlobalSize` bounds the bytes read from it.
unsafe {
let memory = GetClipboardData(format);
if memory.is_null() {
return None;
}
let data = GlobalLock(memory);
if data.is_null() {
return None;
}
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory)).to_vec();
GlobalUnlock(memory);
Some(bytes)
}
}
pub fn png() -> Option<Vec<u8>> {
if !open() {
return None;
}
let png = png_format();
let image = if png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0 {
read_block(png)
} else if unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0 {
read_block(CF_DIB).and_then(|dib| dib_to_png(&dib))
} else {
None
};
unsafe { CloseClipboard() };
image
}
#[link(name = "kernel32")]
@@ -327,8 +450,8 @@ mod imp {
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2::{ClassType, MainThreadMarker};
use objc2_app_kit::{
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
NSPasteboardWriting,
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
@@ -380,6 +503,33 @@ mod imp {
})
}
pub fn has_image() -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
let types = NSArray::from_slice(&[unsafe { NSPasteboardTypePNG }, unsafe { NSPasteboardTypeTIFF }]);
NSPasteboard::generalPasteboard().availableTypeFromArray(&types).is_some()
})
}
/// PNG as copied, else TIFF (what macOS screenshots and most apps write) converted.
pub fn png() -> Option<Vec<u8>> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let board = NSPasteboard::generalPasteboard();
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
if let Some(png) = board.dataForType(unsafe { NSPasteboardTypePNG }) {
return Some(png.to_vec());
}
let tiff = board.dataForType(unsafe { NSPasteboardTypeTIFF })?;
let image = NSBitmapImageRep::imageRepWithData(&tiff)?;
// SAFETY: an empty property dictionary is valid for every file type.
let png =
unsafe { image.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new()) }?;
Some(png.to_vec())
})
}
pub fn text() -> Option<String> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -448,6 +598,17 @@ mod imp {
false
}
pub fn has_image() -> bool {
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_is_image_available()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn files() -> std::io::Result<Vec<PathBuf>> {
Ok(Vec::new())
}
@@ -521,4 +682,62 @@ mod tests {
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
}
/// A `BITMAPINFOHEADER` DIB of `width` × `height` (positive: bottom-up).
fn dib(width: i32, height: i32, bits: u16, compression: u32, rows: &[&[u8]]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&40u32.to_le_bytes());
out.extend_from_slice(&width.to_le_bytes());
out.extend_from_slice(&height.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&bits.to_le_bytes());
out.extend_from_slice(&compression.to_le_bytes());
out.extend_from_slice(&[0u8; 20]);
if compression == super::BI_BITFIELDS {
for mask in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff] {
out.extend_from_slice(&mask.to_le_bytes());
}
}
for row in rows {
out.extend_from_slice(row);
}
out
}
fn decode_png(png: &[u8]) -> (u32, u32, Vec<u8>) {
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap();
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut buf).unwrap();
buf.truncate(info.buffer_size());
(info.width, info.height, buf)
}
#[test]
fn a_bottom_up_24_bit_bitmap_becomes_an_upright_opaque_png() {
// Rows are padded to 4 bytes; the first stored row is the bottom one.
let bottom: &[u8] = &[255, 0, 0, 0, 255, 0, 0, 0];
let top: &[u8] = &[0, 0, 255, 255, 255, 255, 0, 0];
let png = super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[bottom, top])).unwrap();
let (w, h, rgba) = decode_png(&png);
assert_eq!((w, h), (2, 2));
assert_eq!(rgba, [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]);
}
#[test]
fn a_32_bit_bitmap_keeps_its_alpha_unless_none_was_written() {
let row: &[u8] = &[10, 20, 30, 0, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_BITFIELDS, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 255, 60, 50, 40, 255]);
let row: &[u8] = &[10, 20, 30, 128, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_RGB, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 128, 60, 50, 40, 0]);
}
#[test]
fn unsupported_or_truncated_bitmaps_are_not_images() {
let row: &[u8] = &[1, 2, 3, 4];
assert!(super::dib_to_png(&dib(4, 1, 8, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&[0; 10]).is_none());
}
}
+25
Переглянути файл
@@ -42,6 +42,8 @@ pub struct Settings {
pub terminal: TerminalSettings,
pub actions_on_save: ActionsOnSaveSettings,
pub external_tools: Vec<ExternalTool>,
/// Tools › Diff & Merge › External Diff Tools.
pub external_diff: ExternalDiffSettings,
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
@@ -88,6 +90,16 @@ 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,
@@ -130,6 +142,9 @@ 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,
@@ -469,6 +484,7 @@ impl Default for Settings {
debugger: DebuggerSettings::default(),
run: RunSettings::default(),
terminal: TerminalSettings::default(),
external_diff: ExternalDiffSettings::default(),
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
@@ -973,6 +989,7 @@ pub struct LanguagesSettings {
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
}
impl Default for LanguagesSettings {
@@ -995,6 +1012,7 @@ impl Default for LanguagesSettings {
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
}
}
}
@@ -1206,6 +1224,13 @@ impl Default for RustSettings {
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ZigSettings {
/// Directory holding the `zig` executable; empty = the one on `PATH`.
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
+2
Переглянути файл
@@ -19,6 +19,7 @@ pub enum Tool {
Maven,
Gradle,
Ruby,
Zig,
}
impl Tool {
@@ -32,6 +33,7 @@ impl Tool {
Tool::Maven => &["maven"],
Tool::Gradle => &["gradle"],
Tool::Ruby => &["ruby"],
Tool::Zig => &["zig"],
}
}
}
+21
Переглянути файл
@@ -175,6 +175,24 @@ impl Default for VcsConfirmationSettings {
}
}
/// Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalDiffSettings {
/// Offer Show Diff in External Tool in diff viewers.
pub enabled: bool,
/// The program to start.
pub path: String,
/// Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title.
pub parameters: String,
}
impl Default for ExternalDiffSettings {
fn default() -> Self {
Self { enabled: false, path: String::new(), parameters: "%1 %2 %3".into() }
}
}
/// Version Control › Shelf.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -327,6 +345,8 @@ pub struct RunSettings {
/// Ask before closing a Run tab whose process is still running.
pub confirm_terminate: bool,
pub show_on_start: bool,
/// New Run/Debug tabs start pinned: a later run doesn't take their place once finished.
pub pin_tabs: bool,
/// Grace period between interrupt and kill when stopping a process.
pub termination_timeout_ms: u32,
}
@@ -338,6 +358,7 @@ impl Default for RunSettings {
confirm_rerun: true,
confirm_terminate: true,
show_on_start: true,
pin_tabs: false,
termination_timeout_ms: 3000,
}
}
+30
Переглянути файл
@@ -325,6 +325,20 @@ pub fn migrate(data: &Path, local: &Path) {
if cfg!(target_os = "windows") && data != local {
migrate_entries(data, local);
}
if cfg!(target_os = "windows") {
relative_tool_shims(&local.join("tools"));
}
}
/// Wrappers written before they named their tool relative to themselves hold its absolute
/// path, which cmd.exe can't find through a non-ASCII user directory (#3338).
fn relative_tool_shims(tools: &Path) {
let Ok(entries) = fs::read_dir(tools) else { return };
for dir in entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
if let Err(error) = relocate_shims(&dir, &dir) {
tracing::warn!(%error, ?dir, "cannot make the tool's wrappers relative");
}
}
}
fn migrate_entries(data: &Path, local: &Path) {
@@ -651,6 +665,22 @@ mod tests {
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
}
#[test]
fn installed_tool_wrappers_become_relative() {
let tmp = tempfile::tempdir().unwrap();
let tools = tmp.path().join("tools");
let tool = tools.join("taplo");
fs::create_dir_all(tool.join("bin")).unwrap();
let shim = tool.join("bin/taplo.cmd");
fs::write(&shim, format!("@echo off\r\n\"{}\\taplo.exe\" %*\r\n", tool.display())).unwrap();
// A wrapper the user re-saved in another encoding is left alone.
fs::create_dir_all(tools.join("other/bin")).unwrap();
fs::write(tools.join("other/bin/x.cmd"), b"@echo off\r\n\"C:\\\xd5\xc5\" %*\r\n").unwrap();
relative_tool_shims(&tools);
assert_eq!(fs::read_to_string(&shim).unwrap(), "@echo off\r\n\"%~dp0..\\taplo.exe\" %*\r\n");
relative_tool_shims(&tmp.path().join("missing"));
}
#[test]
fn wrappers_accept_mixed_separators_without_rewriting_neighbor_paths() {
let text = "@echo off\r\n\"C:\\old\\tools/demo\\payload.exe\" \"C:\\old\\tools/demo-other\\x\" %*\r\n";
+38 -12
Переглянути файл
@@ -251,18 +251,12 @@ impl KotlinBridge {
}
}
other => {
let text = match other {
Ok(Ok(outcome)) => outcome
.messages
.iter()
.filter(|m| m.severity == Severity::Error)
.map(|m| m.text.as_str())
.collect::<Vec<_>>()
.join("\n"),
Ok(Err(error)) => error.message,
Err(error) => error.to_string(),
let (text, notify) = match other {
Ok(Ok(outcome)) => failed_build(&outcome),
Ok(Err(error)) => (error.message, true),
Err(error) => (error.to_string(), true),
};
self.failure(text, &mut diagnostics, &mut last_failure);
self.report(text, notify, &mut diagnostics, &mut last_failure);
remove_directory(directory).await;
}
}
@@ -276,6 +270,12 @@ impl KotlinBridge {
}
fn failure(&self, text: String, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
self.report(text, true, paths, previous);
}
/// Publishes a failed build in Problems (on `pom.xml`) and, when `notify`, as a
/// notification once per distinct message.
fn report(&self, text: String, notify: bool, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
let text = if text.is_empty() { "Kotlin compilation failed".to_owned() } else { text };
let text = format!("{text}\nJava temporarily uses the last successfully compiled Kotlin API.");
self.clear_diagnostics(paths);
@@ -295,7 +295,7 @@ impl KotlinBridge {
deprecated: false,
}],
});
if previous != &text {
if notify && previous != &text {
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Error,
title: "Kotlin editor compilation failed".into(),
@@ -306,6 +306,15 @@ impl KotlinBridge {
}
}
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
fn failed_build(outcome: &Outcome) -> (String, bool) {
let errors: Vec<_> = outcome.messages.iter().filter(|m| m.severity == Severity::Error).collect();
let text = errors.iter().map(|m| m.text.as_str()).collect::<Vec<_>>().join("\n");
(text, !errors.iter().any(|m| m.path.is_some()))
}
fn relevant_change(root: &Path, path: &Path, settings: &ide_core::settings::Settings) -> bool {
let input = path.extension().is_some_and(|e| e == "kt")
|| path.file_name().is_some_and(|n| n == "pom.xml" || n == "mvnw" || n == "mvnw.cmd")
@@ -383,6 +392,23 @@ mod tests {
assert!(!relevant_change(dir.path(), &dir.path().join("module/src/build/pkg"), &Default::default()));
}
#[test]
fn source_errors_stay_out_of_notifications() {
let message = |text: &str, path: Option<&str>| ide_build::compile::BuildMessage {
severity: Severity::Error,
text: text.into(),
path: path.map(|p| PathBuf::from(p).into()),
range: None,
code: None,
};
let outcome = |messages| Outcome { projects: Vec::new(), messages, success: false };
let (text, notify) = failed_build(&outcome(vec![message("No value passed", Some("/p/src/A.kt"))]));
assert_eq!((text.as_str(), notify), ("No value passed", false));
let (text, notify) = failed_build(&outcome(vec![message("Plugin not found", None)]));
assert_eq!((text.as_str(), notify), ("Plugin not found", true));
assert!(failed_build(&outcome(Vec::new())).1);
}
#[test]
fn extensionless_root_file_does_not_trigger() {
let dir = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -1275,7 +1275,9 @@ impl Project {
}
let defaults = self.documents.file_defaults();
let fallback = defaults.fallback_for(path);
if path.exists() {
// The working file only when it is a regular file: a path that is a directory there
// (a committed symlink to a folder, a file replaced by a folder) has only its blob.
if path.is_file() {
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
+144 -30
Переглянути файл
@@ -296,39 +296,144 @@ impl crate::Host {
}
}
/// Commands which only inspect/edit source or operate user-owned application state.
/// New execution commands are denied until deliberately classified here.
/// Commands allowed in Restricted Mode, by exact name: those which only inspect/edit source or
/// operate user-owned application state. A new command is denied until deliberately listed here.
pub fn restricted_command_allowed(cmd: &str) -> bool {
if [
"fs_",
"doc_",
"syntax_",
"search_",
"nav_",
"history_",
"spell_",
"analysis_",
"structural_",
"refactor_",
"bytes_",
"window_",
"window_group_",
"term_",
"settings_",
"project_trust_",
// New Project writes only where the user chose and runs no code of an open project.
"scaffold_",
"ssh_",
"git_credential",
]
.iter()
.any(|p| cmd.starts_with(p))
{
return true;
}
matches!(
cmd,
"app_info"
"fs_compare_directories"
| "fs_copy"
| "fs_copy_merge"
| "fs_create_dir"
| "fs_create_file"
| "fs_create_file_bytes"
| "fs_delete"
| "fs_entry_kind"
| "fs_open_with_system"
// The user's own diff program (global settings) on the diff's two sides.
| "diff_external_tool"
| "fs_probe"
| "fs_read_dir"
| "fs_read_image"
| "fs_read_range"
| "fs_read_text"
| "fs_rename"
| "fs_resolve_reference"
| "fs_set_writable"
| "doc_close"
| "doc_edit"
| "doc_folding"
| "doc_highlights"
| "doc_open"
| "doc_open_untitled"
| "doc_open_virtual"
| "doc_outline"
| "doc_python_facts"
| "doc_save"
| "doc_save_as"
| "doc_save_all"
| "doc_selection_ranges"
| "doc_set_bom"
| "doc_set_encoding"
| "doc_set_line_ending"
| "doc_snapshot"
| "doc_sync_from_disk"
| "doc_ui_mode"
| "syntax_errors"
| "syntax_expression_at"
| "syntax_identifiers"
| "syntax_identifiers_in_files"
| "syntax_locals"
| "syntax_node_at"
| "syntax_structural_ranges"
| "syntax_support"
| "search_start"
| "search_validate"
| "nav_index_definitions"
| "nav_inheritance"
| "nav_resolve_module"
| "history_content"
| "history_list"
| "history_list_dir"
| "history_put_label"
| "history_restore"
| "spell_check"
| "spell_suggest"
| "analysis_locate_duplicates"
| "structural_languages"
| "structural_search"
| "structural_validate"
| "refactor_can_undo_file_move"
| "refactor_file_move_edits"
| "refactor_file_move_text_edits"
| "refactor_move_files"
| "refactor_undo_file_move"
| "window_close_context"
| "window_complete_launch"
| "window_cycle"
| "window_flash_taskbar"
| "window_group_cancel_close"
| "window_group_close"
| "window_group_close_tabs"
| "window_group_current"
| "window_group_detach"
| "window_group_merge"
| "window_group_reorder"
| "window_group_restore"
| "window_group_select"
| "window_is_fullscreen"
| "window_new"
| "window_open_comparison"
| "window_open_deployment"
| "window_open_diff"
| "window_open_file_in_new_window"
| "window_open_files"
| "window_open_project"
| "window_open_projects"
| "window_open_remote"
| "window_open_settings"
| "window_set_titlebar_height"
| "window_start_drag"
| "window_take_launch"
| "window_toggle_fullscreen"
| "window_toggle_zoom"
| "term_available_shells"
| "term_default_shell"
| "term_is_busy"
| "term_kill"
| "term_resize"
| "term_spawn"
| "term_store_image"
| "term_write"
| "settings_export"
| "settings_get"
| "settings_get_global"
| "settings_import"
| "settings_list_jetbrains_ides"
| "settings_read_jetbrains"
| "settings_set"
| "project_trust_add_location"
| "project_trust_list"
| "project_trust_remove_location"
| "project_trust_set"
| "project_trust_status"
// New Project writes only where the user chose and runs no code of an open project.
| "scaffold_catalog"
| "scaffold_create"
| "scaffold_options"
| "scaffold_requirements"
| "ssh_askpass_answer"
| "ssh_connected"
| "ssh_disconnect"
| "ssh_needs_secret"
| "ssh_open_terminal"
| "ssh_password_saved"
| "ssh_set_secret"
| "ssh_test"
| "ssh_trust_host"
| "git_credential_forget"
| "git_credentials"
| "app_info"
| "app_build_info"
| "app_cli_install"
| "app_cli_uninstall"
@@ -342,6 +447,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "clear_caches"
| "clipboard_file_list"
| "clipboard_has_files"
| "clipboard_has_image"
| "clipboard_image"
| "clipboard_set_file_list"
| "clipboard_write_text"
@@ -572,6 +678,14 @@ mod tests {
assert!(super::restricted_command_allowed("clipboard_write_text"));
}
#[test]
fn restricted_mode_denies_new_commands_whatever_their_name() {
for cmd in ["fs_new_command", "term_new_command", "ssh_new_command", "settings_new_command", "git_credential_x"]
{
assert!(!super::restricted_command_allowed(cmd), "{cmd} is allowed without being listed");
}
}
#[test]
fn remote_project_decisions_are_kept_on_this_machine() {
let tmp = tempfile::tempdir().unwrap();
+1
Переглянути файл
@@ -46,6 +46,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"clear_caches",
"clipboard_file_list",
"clipboard_has_files",
"clipboard_has_image",
"clipboard_image",
"clipboard_set_file_list",
"clipboard_write_text",
+46
Переглянути файл
@@ -111,3 +111,49 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
assert_eq!(vcs::vcs_file_at(&host, "main", utf8, None).await.unwrap().as_deref(), Some(old));
host.close_project("main");
}
/// A committed symlink to a folder (#3528): its revision is the link target, even though the
/// working path is a directory.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_directory_symlink_revision_is_its_target() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(root.join("target")).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
std::fs::write(root.join("target/file.txt"), "example\n").unwrap();
std::os::unix::fs::symlink("target", root.join("dir-link")).unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "Add a directory symlink"]);
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let link = root.join("dir-link");
assert!(link.is_dir());
assert_eq!(
vcs::vcs_file_at(&host, "main", link.clone(), Some("HEAD".into())).await.unwrap().as_deref(),
Some("target")
);
assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000"));
host.close_project("main");
}
+19
Переглянути файл
@@ -207,3 +207,22 @@ async fn change_commit_branch_stash_and_merge_a_conflict() {
assert!(f.status().await.is_empty());
assert_eq!(std::fs::read_to_string(&lib_path).unwrap(), resolved);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn checkout_reports_a_branch_held_by_another_worktree() {
let f = Flow::new("rust-app").await;
let linked = f._tmp.path().join("linked");
git(&f.root, &["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None).await.unwrap();
assert_eq!(
outcome,
ide_vcs::CheckoutOutcome::CheckedOutInWorktree {
branch: "topic".into(),
path: dunce::canonicalize(&linked).unwrap()
}
);
// Nothing changed: the project is still on main.
let branches = ops::vcs::vcs_branches(&f.host, WINDOW, None).await.unwrap();
assert!(branches.iter().any(|b| b.name == "main" && b.current), "{branches:?}");
}
+25 -11
Переглянути файл
@@ -78,8 +78,8 @@ impl Needle {
let mut b = 0;
if n.eq_ignore_ascii_case(q) {
b += EXACT;
} else if let Some(dot) = name.find('.')
&& name.as_bytes()[..dot].eq_ignore_ascii_case(q)
} else if let Some(dot) = n.iter().position(|&b| b == b'.')
&& n[..dot].eq_ignore_ascii_case(q)
{
b += EXACT_STEM;
} else if n.len() >= q.len() && n[..q.len()].eq_ignore_ascii_case(q) {
@@ -97,17 +97,31 @@ fn hump_bonus(s: &str, indices: &[u32]) -> u32 {
if indices.is_empty() {
return 0;
}
let chars: Vec<char> = s.chars().collect();
let is_start = |i: usize| {
if i == 0 {
return true;
// One pass over `s`: `indices` is sorted, and whether position `i` is a
// word start only needs the char before it, so no `Vec<char>` is collected.
let is_start = |prev: Option<char>, c: char| match prev {
None => true,
Some(p) => {
!p.is_alphanumeric()
|| (p.is_lowercase() && c.is_uppercase())
|| (!p.is_ascii_digit() && c.is_ascii_digit())
}
let (p, c) = (chars[i - 1], chars[i]);
!p.is_alphanumeric() || (p.is_lowercase() && c.is_uppercase()) || (!p.is_ascii_digit() && c.is_ascii_digit())
};
let humps = indices.iter().filter(|&&i| (i as usize) < chars.len() && is_start(i as usize)).count() as u32;
let first = if is_start(indices[0] as usize) { FIRST_AT_START } else { 0 };
humps * HUMP + first
let (mut humps, mut next, mut first_start) = (0u32, 0usize, false);
let (mut prev, mut at) = (None, 0u32);
for c in s.chars() {
if next < indices.len() && indices[next] == at {
let started = is_start(prev, c);
humps += u32::from(started);
if next == 0 {
first_start = started;
}
next += 1;
}
prev = Some(c);
at += 1;
}
humps * HUMP + u32::from(first_start) * FIRST_AT_START
}
#[derive(Clone, Copy)]
+21 -8
Переглянути файл
@@ -215,12 +215,18 @@ pub trait Handler: Send + Sync + 'static {
/// Respond to a server→client request (e.g. `workspace/configuration`).
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)>;
/// [`on_request`](Self::on_request) for handlers whose errors carry `data`. This is the
/// one the connection calls.
/// [`on_request`](Self::on_request) for handlers whose errors carry `data`.
fn on_request_with_data(&self, method: &str, params: Value) -> Result<Value, (i64, String, Option<Value>)> {
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
}
/// [`on_request_with_data`](Self::on_request_with_data) with the request as received, for
/// handlers that need what `Value` drops, such as the order of an object's keys. This is the
/// one the connection calls.
fn on_request_raw(&self, method: &str, params: Value, _raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
self.on_request_with_data(method, params)
}
/// Called once the response to a `method` request is queued: what it sends follows the response.
fn after_response(&self, _method: &str) {}
@@ -577,8 +583,8 @@ impl Peer {
tracing::error!("jsonrpc notification handler panicked on {method}");
}
}
Incoming::Request(id, method, params) => {
runtime.spawn(handle_request(inner.clone(), handler.clone(), id, method, params));
Incoming::Request(id, method, params, raw) => {
runtime.spawn(handle_request(inner.clone(), handler.clone(), id, method, params, raw));
}
Incoming::Response(tx, result) => {
let _ = tx.send(result);
@@ -761,14 +767,21 @@ fn parse_id(id: &Value) -> Option<i64> {
enum Incoming {
Notification(String, Value),
Request(Value, String, Value),
Request(Value, String, Value, Arc<[u8]>),
Response(oneshot::Sender<Result<Value, RpcError>>, Result<Value, RpcError>),
}
async fn handle_request(inner: Arc<Inner>, handler: Arc<dyn Handler>, id: Value, method: String, params: Value) {
async fn handle_request(
inner: Arc<Inner>,
handler: Arc<dyn Handler>,
id: Value,
method: String,
params: Value,
raw: Arc<[u8]>,
) {
let m = method.clone();
let h = handler.clone();
let result = tokio::task::spawn_blocking(move || h.on_request_with_data(&m, params)).await;
let result = tokio::task::spawn_blocking(move || h.on_request_raw(&m, params, &raw)).await;
let reply = match result {
Ok(Ok(result)) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
Ok(Err((code, message, data))) => {
@@ -808,7 +821,7 @@ fn dispatch(inner: &Arc<Inner>, handler: &dyn Handler, notif_tx: &std::sync::mps
let params = obj.remove("params").unwrap_or(Value::Null);
match id {
Some(id) if !id.is_null() => {
let _ = notif_tx.send(Incoming::Request(id, method, params));
let _ = notif_tx.send(Incoming::Request(id, method, params, Arc::from(body)));
}
_ => {
let _ = notif_tx.send(Incoming::Notification(method, params));
+1
Переглянути файл
@@ -16,6 +16,7 @@ toml.workspace = true
tree-sitter.workspace = true
parking_lot.workspace = true
tracing.workspace = true
memchr = "2"
regex-lite = "0.1"
blake3.workspace = true
tree-sitter-language = "0.1"
+5
Переглянути файл
@@ -170,6 +170,11 @@ pub struct LanguageServerConfig {
/// basedpyright): only used while none of those is installed.
#[serde(default)]
pub fallback: bool,
/// Names of servers listed after this one that it makes redundant (a PHP server
/// with its own Laravel support replaces `laravel-lsp`): they aren't used while
/// this one serves the file.
#[serde(default)]
pub replaces: Vec<String>,
/// What the server is used for (`completion`, `code-action`, `diagnostics`,
/// … `FEATURES` in `ide-lsp/src/caps.rs`); empty means everything. The other
/// capabilities it announces are ignored, so a refactoring-only server next
+4 -1
Переглянути файл
@@ -758,7 +758,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
assert_eq!(lsp.command.as_str(), "laravel-lsp");
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
+7 -2
Переглянути файл
@@ -79,11 +79,16 @@ impl<'a> LineIndex<'a> {
}
fn memchr_newlines(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
bytes.iter().enumerate().filter(|&(_, &b)| b == b'\n').map(|(i, _)| i + 1)
memchr::memchr_iter(b'\n', bytes).map(|i| i + 1)
}
pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
if s.is_ascii() {
return s.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
/// Byte offset of `pos` (line, UTF-16 column) in `text`; None past the last line.
+26 -9
Переглянути файл
@@ -660,15 +660,17 @@ impl LspManager {
/// The servers serving `path`: every regular one, and each `fallback` one
/// only while all servers listed before it have given up (missing, not
/// launchable, or crashed for good). One that requires a root marker serves
/// only files below one, and stands in for no other.
/// only files below one, and stands in for no other. One that a server before
/// it `replaces` is left out while that server serves the file.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
if let Some(servers) = self.arduino_servers(language, path) {
return servers;
}
let mut out = Vec::new();
let mut available_before = false;
let mut replaced: Vec<String> = Vec::new();
for sc in &self.language_servers(language) {
if sc.fallback && available_before {
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
continue;
}
if sc.require_root_marker
@@ -678,6 +680,9 @@ impl LspManager {
}
let server = self.server_for(sc, language, path);
available_before |= !sc.require_root_marker && !server.gave_up();
if !server.gave_up() {
replaced.extend(sc.replaces.iter().cloned());
}
out.push(server);
}
out
@@ -865,7 +870,7 @@ impl LspManager {
ide_core::event::ServerStatus::Missing,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -878,7 +883,7 @@ impl LspManager {
ide_core::event::ServerStatus::Misconfigured,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -891,7 +896,7 @@ impl LspManager {
ide_core::event::ServerStatus::Crashed,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -1039,7 +1044,7 @@ impl LspManager {
}
}
// Gave up (crashed repeatedly, or its build expired): the fallbacks it hid take over.
None => self.attach_fallbacks(),
None => self.fallbacks_take_over().await,
}
}
@@ -3464,7 +3469,10 @@ impl LspManager {
virtual_doc::is_decompiled(&text)
};
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
let detected = self.languages.detect(Path::new(&title), None);
let mut detected = self.languages.detect(Path::new(&title), None);
if let Some(stem) = title.strip_suffix(".class").filter(|_| virtual_doc::is_java_class_stub(&text)) {
detected = self.languages.detect(Path::new(&format!("{stem}.java")), None);
}
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
@@ -3828,8 +3836,16 @@ impl LspManager {
}
}
/// A server enabled again shadows the fallbacks attached in its place: they
/// leave the open documents, and stop once no document uses them.
/// A server gave up: its fallbacks take over the open documents, and the servers
/// they replace leave.
async fn fallbacks_take_over(&self) {
self.attach_fallbacks();
self.detach_shadowed_fallbacks().await;
}
/// A server enabled again shadows the fallbacks attached in its place, and a
/// fallback that took over may replace a server attached earlier: they leave the
/// open documents, and stop once no document uses them.
async fn detach_shadowed_fallbacks(&self) {
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
@@ -3845,6 +3861,7 @@ impl LspManager {
.filter(|a| {
!wanted.iter().any(|w| w.id == a.server.id)
&& (configs.iter().any(|c| c.fallback && c.name == a.server.name)
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
})
.map(|a| a.server.id)
+22
Переглянути файл
@@ -110,6 +110,17 @@ pub fn is_decompiled(text: &str) -> bool {
})
}
/// Whether a `.class` stub is written in Java: its first `package` or `import` line ends with `;`.
/// The Kotlin language server shows Java classes from jars as Java and Kotlin ones as Kotlin, under
/// the same `.class` name.
pub fn is_java_class_stub(text: &str) -> bool {
text.lines()
.take(200)
.map(str::trim)
.find(|line| line.starts_with("package ") || line.starts_with("import "))
.is_some_and(|line| line.ends_with(';'))
}
/// `scheme` of a URI (`jdt` for `jdt://…`).
pub fn scheme(uri: &str) -> &str {
uri.split_once(':').map(|(s, _)| s).unwrap_or("")
@@ -205,6 +216,17 @@ mod tests {
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
#[test]
fn class_stubs_in_java_or_kotlin() {
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";
let kotlin = "// IntelliJ API Decompiler stub source generated from a class file\n// Implementation of methods is not available\n\npackage kotlin.collections\n\npublic fun <T> listOf(): List<T> { /* compiled code */ }\n";
let imports_only = "import java.util.List;\n\npublic class A {}\n";
assert!(is_java_class_stub(java));
assert!(is_java_class_stub(imports_only));
assert!(!is_java_class_stub(kotlin));
assert!(!is_java_class_stub("public class A {}"));
}
#[test]
fn csharp_metadata_titles_and_kinds() {
for (uri, expected) in [
+62
Переглянути файл
@@ -264,6 +264,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -3286,6 +3287,67 @@ async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
h.wait_status("alt", ServerStatus::Ready).await;
}
/// A server that `replaces` another (a PHP server with its own Laravel support and
/// `laravel-lsp`) keeps it away while it serves, and only then.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_server_stays_away_while_its_replacement_serves() {
let servers = [("main", incremental_caps()), ("alt", incremental_caps()), ("framework", incremental_caps())];
let configure = |cfg: &mut LanguageServerConfig| match cfg.name.as_str() {
"alt" => {
cfg.fallback = true;
cfg.replaces = vec!["framework".into()];
}
"framework" => cfg.require_root_marker = true,
_ => {}
};
let h = harness_configured("mock", "mk", &servers, configure);
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
{
let disabled = disabled.clone();
h.mgr.set_servers_hook(Box::new(move |_, defined| {
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
}));
}
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
// The preferred server serves: the framework's server joins it, the alternative stays away.
h.wait_status("main", ServerStatus::Ready).await;
h.wait_status("framework", ServerStatus::Ready).await;
eventually(|| h.launcher.state("framework").docs.lock().contains_key(&uri)).await;
assert!(h.statuses("alt").is_empty());
// The alternative takes over: the server it replaces closes the document and stops.
disabled.lock().push("main".into());
h.mgr.reconfigure().await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
assert!(!h.launcher.state("framework").notified("textDocument/didClose").is_empty());
assert_eq!(h.statuses("framework").last(), Some(&ServerStatus::Stopped));
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
// The preferred server again: the framework's server comes back with it.
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("main", ServerStatus::Ready).await;
eventually(|| h.statuses("framework").last() == Some(&ServerStatus::Ready)).await;
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
// A preferred server that is not installed: the alternative replaces the framework's
// server although that one attached first.
let servers = [("ghost", json!({})), ("alt", incremental_caps()), ("framework", incremental_caps())];
let h = harness_configured("mock", "mk", &servers, configure);
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
h.wait_status("ghost", ServerStatus::Missing).await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
eventually(|| !h.mgr.servers().iter().any(|s| s.name == "framework")).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
+3
Переглянути файл
@@ -419,6 +419,7 @@ async fn missing_binary_is_reported_with_install_hint() {
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -692,6 +693,7 @@ async fn typescript_language_server_end_to_end() {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -745,6 +747,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
+171
Переглянути файл
@@ -12,6 +12,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let Some(src) = read(&dir.join("build.zig")) else { return };
let src = code_only(&src);
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
let roots = test_roots(&src);
for step in steps(&src) {
// `install` is what plain `zig build` runs.
if step == "install" || step == "uninstall" {
@@ -20,6 +21,9 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
c = c.test();
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
c.extras.params.insert("testRoot".into(), root.clone());
}
}
out.push(c);
}
@@ -161,6 +165,137 @@ fn executables(src: &str) -> Vec<Executable> {
out
}
/// The call's argument text: from just after its `(` to the matching `)`.
fn call_body(src: &str, start: usize) -> &str {
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
for (i, c) in src[start..].char_indices() {
if in_string {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
'(' | '{' | '[' => depth += 1,
')' | '}' | ']' => {
depth -= 1;
if depth == 0 {
return &src[start..start + i];
}
}
_ => {}
}
}
src
}
/// The first `.root_source_file = <receiver>.path("…")` in `body`.
fn root_source_file(body: &str) -> Option<String> {
for (i, _) in body.match_indices(".root_source_file") {
let Some(v) = body[i + ".root_source_file".len()..].trim_start().strip_prefix('=') else { continue };
let v = v.trim_start();
if let Some(call) = v.find(".path(")
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
{
return string_at(&v[call + ".path(".len()..]);
}
}
None
}
/// The identifier assigned just before `at`: `const mod = b.addModule(…` → `mod`.
fn assigned_var(src: &str, at: usize) -> Option<&str> {
let before = src[..at].trim_end();
let before = before.strip_suffix('.')?.trim_end();
// Drop the receiver (`b`) that sits between the `=` and the call.
let receiver =
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
let before = before[..receiver].trim_end();
let before = before.strip_suffix('=')?.trim_end();
let start =
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
Some(&before[start..])
}
/// The test root behind each test-named step (`zig build <step>`): the step's `dependOn` runs
/// an `addTest` artifact — a variable (`const tests = b.addTest(…)`) or an inline call — whose
/// module's `root_source_file` this resolves (through `addModule`/`createModule` variables).
/// `zig build` forwards no args to the test binary, so rerunning a single failed test goes
/// through a standalone `zig test <root> --test-filter …` on the step's own test module.
fn test_roots(src: &str) -> Vec<(String, String)> {
let mut modules: Vec<(String, String)> = Vec::new();
for key in ["addModule(", "createModule("] {
for (i, _) in src.match_indices(key) {
let Some(root) = root_source_file(call_body(src, i + key.len())) else { continue };
if let Some(var) = assigned_var(src, i)
&& !modules.iter().any(|(m, _)| *m == var)
{
modules.push((var.to_owned(), root));
}
}
}
let module_root = |body: &str| -> Option<String> {
root_source_file(body).or_else(|| {
let at = body.find(".root_module")?;
let v = body[at + ".root_module".len()..].trim_start().strip_prefix('=')?.trim_start();
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
modules.iter().find(|(m, _)| *m == var).map(|(_, root)| root.clone())
})
};
let mut tests: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices("addTest(") {
let Some(root) = module_root(call_body(src, i + "addTest(".len())) else { continue };
if let Some(var) = assigned_var(src, i)
&& !tests.iter().any(|(v, _)| *v == var)
{
tests.push((var.to_owned(), root));
}
}
let mut steps: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".step(\"") {
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
// The match includes the dot, so the assignment ends one character earlier.
if let Some(var) = assigned_var(src, i + 1) {
steps.push((var.to_owned(), name));
}
}
let mut out: Vec<(String, String)> = Vec::new();
for (i, _) in src.match_indices(".dependOn(&") {
let Some(step) = receiver_var(src, i + 1) else { continue };
let Some((_, name)) = steps.iter().find(|(v, _)| v == step) else { continue };
let after = &src[i + ".dependOn(&".len()..];
let artifact = if let Some(at) = after.find("addRunArtifact(") {
let v = &after[at + "addRunArtifact(".len()..];
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
tests.iter().find(|(v, _)| *v == var).map(|(_, root)| root.clone())
} else if let Some(at) = after.find("addTest(") {
module_root(call_body(after, at + "addTest(".len()))
} else {
None
};
if let Some(root) = artifact
&& name.starts_with("test")
&& !out.iter().any(|(n, _)| n == name)
{
out.push((name.clone(), root));
}
}
out
}
/// The identifier a method is called on just before `at`: `test_step.dependOn(…` → `test_step`.
fn receiver_var(src: &str, at: usize) -> Option<&str> {
let before = src[..at].trim_end();
let before = before.strip_suffix('.')?;
let start =
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
Some(&before[start..])
}
#[cfg(test)]
mod tests {
use super::*;
@@ -190,7 +325,9 @@ pub fn build(b: *std.Build) void {
}) });
_ = tool;
const run_step = b.step("run", "Run the app");
const tests = b.addTest(.{ .root_module = mod });
const test_step = b.step("test", "Run tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
const docs = b.step("docs", "Generate docs // not a comment");
_ = .{ run_step, test_step, docs };
}
@@ -228,5 +365,39 @@ pub fn build(b: *std.Build) void {
assert_eq!(app.extras.before_launch[0].kind, "run");
assert_eq!(app.extras.before_launch[0].target, BUILD_ID);
assert_eq!(app.extras.params.get("source").map(String::as_str), Some("src/main.zig"));
assert_eq!(test.extras.params.get("testRoot").map(String::as_str), Some("src/root.zig"));
}
const TEST_ROOTS: &str = r#"const std = @import("std");
pub fn build(b: *std.Build) void {
const tally = b.addModule("tally", .{ .root_source_file = b.path("src/tally.zig") });
const unit = b.addTest(.{ .root_module = tally });
const test_step = b.step("test", "Run the unit tests");
test_step.dependOn(&b.addRunArtifact(unit).step);
const failing = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/failing.zig"),
}) });
const test_failing_step = b.step("test-failing", "Run the failing tests");
test_failing_step.dependOn(&b.addRunArtifact(failing).step);
const direct = b.addTest(.{ .root_source_file = b.path("src/direct.zig") });
const test_direct_step = b.step("test-direct", "Run the direct tests");
test_direct_step.dependOn(&b.addRunArtifact(direct).step);
const run_step = b.step("run", "Run the app");
run_step.dependOn(&b.addRunArtifact(unit).step);
}
"#;
#[test]
fn test_roots_come_from_the_step_s_own_artifact() {
let src = code_only(TEST_ROOTS);
assert_eq!(
test_roots(&src),
[
("test".to_owned(), "src/tally.zig".to_owned()),
("test-failing".to_owned(), "src/failing.zig".to_owned()),
("test-direct".to_owned(), "src/direct.zig".to_owned()),
]
);
}
}
+4
Переглянути файл
@@ -21,3 +21,7 @@ toml.workspace = true
tracing.workspace = true
url = "2"
zip.workspace = true
[dev-dependencies]
flate2.workspace = true
tar.workspace = true
+7
Переглянути файл
@@ -141,6 +141,12 @@ pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
}
/// The directory of the configured Zig install (holding `zig`), else `None` for `PATH`.
pub(crate) fn zig_bin(root: &Path, s: &Settings) -> Option<PathBuf> {
setting_path(root, &s.languages.zig.zig)
.map(|p| if p.is_file() { p.parent().map(Path::to_path_buf).unwrap_or(p) } else { p })
}
/// Runtime choices for package-manager based IDE tool installs.
#[derive(Default)]
pub struct ToolInstallEnvironment {
@@ -1300,6 +1306,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
}),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
+82
Переглянути файл
@@ -25,6 +25,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Jdk => jdk(),
SdkKind::Maven => maven(),
SdkKind::Ruby => crate::ruby::detect(root),
SdkKind::Zig => zig(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -40,6 +41,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
SdkKind::Jdk => Some(Tool::Java),
SdkKind::Maven => Some(Tool::Maven),
SdkKind::Ruby => Some(Tool::Ruby),
SdkKind::Zig => Some(Tool::Zig),
SdkKind::Php | SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript => None,
}
}
@@ -739,6 +741,86 @@ fn go() -> Vec<Sdk> {
})
}
// ------------------------------------------------------------------ zig
/// The directory holding the `zig` executable of the install rooted at `base`,
/// the way the common distributions lay it out: `zig` at the root (official
/// tarballs, mise / asdf installs), `<base>/bin/zig` (Homebrew) or one
/// directory down (zvm's nested version folders).
fn zig_dir(base: &Path) -> Option<PathBuf> {
if base.join(exe("zig")).is_file() {
return Some(base.to_path_buf());
}
let bin = base.join(bin_dir());
if bin.join(exe("zig")).is_file() {
return Some(bin);
}
subdirs(base).into_iter().find(|d| d.join(exe("zig")).is_file())
}
/// Zig toolchains: PATH, Homebrew, zvm and mise / asdf installs. `path` is the
/// directory holding `zig`, which is what `languages.zig.zig` stores.
fn zig() -> Vec<Sdk> {
let mut roots: Vec<(PathBuf, &'static str)> = Vec::new();
if let Some(bin) = which("zig").filter(|p| !version_managers::is_shim(p))
&& let Some(dir) = bin.parent()
{
roots.push((dir.to_path_buf(), "path"));
}
for p in ["/opt/homebrew/opt/zig", "/usr/local/opt/zig"] {
roots.push((PathBuf::from(p), "system"));
}
if let Some(home) = home_dir() {
for d in subdirs(&home.join(".zvm")) {
roots.push((d, "zvm"));
}
}
for (d, manager) in version_managers::installs(Tool::Zig) {
roots.push((d, manager));
}
let mut dirs: Vec<(PathBuf, &'static str)> =
roots.into_iter().filter_map(|(base, source)| zig_dir(&base).map(|dir| (dir, source))).collect();
let mut seen = HashSet::new();
dirs.retain(|(dir, _)| seen.insert(dir.canonicalize().unwrap_or_else(|_| dir.clone())));
par_map(&dirs, |(dir, source)| {
let version = query(&dir.join(exe("zig")), &["version"], VERSION_TIMEOUT).map(|v| v.trim().to_owned());
Some(Sdk {
path: dir.clone().into(),
name: format!("Zig {}", version.as_deref().unwrap_or_default()).trim().to_owned(),
version,
source: (*source).to_owned(),
home: Some(dir.clone().into()),
extra: None,
})
})
}
#[cfg(test)]
mod zig_tests {
use super::*;
#[test]
fn finds_the_zig_directory_of_each_layout() {
let tmp = tempfile::tempdir().unwrap();
let install = |rel: &str| {
let dir = tmp.path().join(rel);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(exe("zig")), "").unwrap();
dir
};
// Official tarballs and mise / asdf installs: `zig` at the root.
let root = install("0.14.1");
assert_eq!(zig_dir(&root), Some(root));
// Homebrew: <opt>/bin/zig.
let brew = install("brew/bin");
assert_eq!(zig_dir(brew.parent().unwrap()), Some(brew));
// zvm: one directory down.
let zvm = install("zvm/x");
assert_eq!(zig_dir(&tmp.path().join("zvm")), Some(zvm));
assert_eq!(zig_dir(&tmp.path().join("missing")), None);
}
}
// ------------------------------------------------------------------ typescript
/// `node_modules/typescript/lib` of the project (root or a direct workspace member).
+3
Переглянути файл
@@ -26,6 +26,7 @@ pub mod pinned;
pub mod python;
pub mod ruby;
mod vue;
mod zig;
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -51,6 +52,8 @@ pub enum SdkKind {
/// Maven homes.
Maven,
Ruby,
/// Zig toolchain directories.
Zig,
}
/// One installed interpreter / toolchain.
+206 -3
Переглянути файл
@@ -2,7 +2,8 @@
//! Project view): the folders holding the sources of the project's SDKs and
//! dependencies — the Python interpreter's standard library and site-packages,
//! the JDK, `node_modules` packages, Cargo crates and the Rust standard
//! library, GOROOT and the Go module cache.
//! library, GOROOT and the Go module cache, the Zig standard library and the
//! fetched packages of `build.zig.zon`.
//!
//! Ecosystems are detected in the project and its modules. SDK and graph probes
//! are cached until manifests or settings change; Node packages are read on refresh.
@@ -28,7 +29,7 @@ use std::time::{Duration, SystemTime};
pub struct LibraryGroup {
/// Display name, e.g. `Python 3.12 (.venv)`.
pub name: String,
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`.
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`.
pub kind: String,
pub roots: Vec<LibraryRoot>,
}
@@ -56,6 +57,7 @@ const JAVA_MANIFESTS: &[&str] =
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
const RUBY_MANIFESTS: &[&str] = &["Gemfile", "Gemfile.lock", ".ruby-version", ".tool-versions", "mise.toml"];
const ZIG_MANIFESTS: &[&str] = &["build.zig.zon", "build.zig"];
/// A Maven / Gradle dependency of the project, from the build model.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -83,7 +85,7 @@ pub fn project_libraries_stream(
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups];
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);
std::thread::scope(|s| {
@@ -193,6 +195,8 @@ fn library_project_roots(root: &Path, cancel: &CancellationToken) -> Vec<PathBuf
"setup.py",
"requirements.txt",
".python-version",
"build.zig",
"build.zig.zon",
".tool-versions",
"mise.toml",
]
@@ -252,6 +256,7 @@ fn module_settings(root: &Path, settings: &Settings) -> Settings {
&mut l.rust.stdlib,
&mut l.go.goroot,
&mut l.go.gopath,
&mut l.zig.zig,
&mut l.java.jdk,
] {
// `target:<id>` names a run target, not a path.
@@ -998,6 +1003,80 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
// ------------------------------------------------------------------ zig
fn zig_groups(root: &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, || {
let Some(env) = query_in_cancellable(&zig, &["env"], root, &[], QUERY_TIMEOUT, cancel)
.as_deref()
.and_then(crate::zig::parse_zig_env)
else {
return Vec::new();
};
let mut out = Vec::new();
let version =
env.version.clone().or_else(|| query_in_cancellable(&zig, &["version"], root, &[], QUERY_TIMEOUT, cancel));
let name = match version.as_deref().map(str::trim) {
Some(v) if !v.is_empty() => format!("Zig {v}"),
_ => "Zig".into(),
};
out.extend(env.std_sources().and_then(|std| group(name, "zig", library_roots(vec![std]))));
if let Some(cache) = env.global_cache_dir.as_deref() {
let zon = std::fs::read_to_string(root.join("build.zig.zon")).unwrap_or_default();
let deps = crate::zig::zon_dependencies(&zon);
out.extend(group("Zig packages", "zigPackages", zig_package_roots(cache, &deps)));
}
out
})
}
/// The fetched sources of a `build.zig.zon`'s dependencies: `p/<hash>` folders
/// (Zig ≤ 0.14 unpacks them) or the package root inside `p/<hash>.tar.gz` (Zig
/// ≥ 0.15 keeps packages as blobs, browsed through the archive VFS). Path
/// dependencies stay in the project tree; unfetched packages are simply absent —
/// listing libraries never downloads.
fn zig_package_roots(cache: &Path, deps: &[crate::zig::ZonDependency]) -> Vec<LibraryRoot> {
let mut seen = std::collections::HashSet::new();
deps.iter()
.filter_map(|d| {
let hash = d.hash.as_deref()?;
let dir = cache.join("p").join(hash);
if dir.is_dir() {
let zon = std::fs::read_to_string(dir.join("build.zig.zon")).unwrap_or_default();
let name =
match (crate::zig::zon_string_field(&zon, "name"), crate::zig::zon_string_field(&zon, "version")) {
(Some(name), Some(version)) => format!("{name} {version}"),
(Some(name), None) => name,
_ => hash.to_owned(),
};
return Some((name, dir));
}
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
blob.is_file().then_some(hash).map(|hash| {
// The blob's only top-level folder is the package (`<hash>/`); fall back to
// the archive root should that layout ever change.
let entry = if ide_vfs::read_archive_dir(&blob, hash).is_ok() { hash } else { "" };
(package_label(d, hash), ide_vfs::archive_entry_path(&blob, entry))
})
})
.filter(|(_, path)| seen.insert(path.to_string_lossy().into_owned()))
.map(|(name, path)| LibraryRoot { name, path: path.into() })
.collect()
}
/// `probe_pkg 0.1.0` from a Zig ≥ 0.15 package hash (`name-version-<hash>`).
fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
let Some((rest, _)) = hash.rsplit_once('-') else { return dep.name.clone() };
let mut parts: Vec<&str> = rest.split('-').collect();
let version = parts.pop().unwrap_or_default();
match parts.is_empty() || !version.starts_with(|c: char| c.is_ascii_digit()) || !version.contains('.') {
true => dep.name.clone(),
false => format!("{} {version}", parts.join("-")),
}
}
#[cfg(test)]
mod go_cache_tests {
use super::*;
@@ -1387,3 +1466,127 @@ mod idea_project_tests {
assert!(idea_java_project(root));
}
}
#[cfg(test)]
mod zig_tests {
use super::*;
use crate::zig::ZonDependency;
/// Writes a Zig package blob (`p/<hash>.tar.gz`) with a `<hash>/` root folder.
fn write_package_blob(cache: &Path, hash: &str, files: &[(&str, &str)]) {
use flate2::write::GzEncoder;
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
let enc = GzEncoder::new(std::fs::File::create(blob).unwrap(), flate2::Compression::default());
let mut tar = tar::Builder::new(enc);
for (name, text) in files {
let mut header = tar::Header::new_gnu();
header.set_size(text.len() as u64);
header.set_mode(0o644);
header.set_cksum();
tar.append_data(&mut header, name, text.as_bytes()).unwrap();
}
tar.into_inner().unwrap().finish().unwrap();
}
#[test]
fn zig_packages_come_from_the_global_cache_without_fetching() {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path();
let (hash, old) = ("zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8", "1220b7c0");
write_package_blob(cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
let unpacked = cache.join("p").join(old);
std::fs::create_dir_all(&unpacked).unwrap();
std::fs::write(unpacked.join("build.zig.zon"), r#".{ .name = .old_pkg, .version = "0.2.0" }"#).unwrap();
let deps = [
ZonDependency { name: "zap".into(), hash: Some(hash.into()), path: None, lazy: false },
ZonDependency { name: "shared".into(), hash: None, path: Some("../shared".into()), lazy: false },
ZonDependency { name: "gone".into(), hash: Some("gone-1.0.0-BBBBBBBBBB".into()), path: None, lazy: true },
ZonDependency { name: "old".into(), hash: Some(old.into()), path: None, lazy: false },
];
let roots = zig_package_roots(cache, &deps);
let summary: Vec<(String, String)> =
roots.iter().map(|r| (r.name.clone(), r.path.to_string_lossy().into_owned())).collect();
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
assert_eq!(
summary,
[
("zap 0.1.0".into(), format!("{}!/{hash}", blob.display())),
("old_pkg 0.2.0".into(), unpacked.to_string_lossy().into_owned())
]
);
}
#[test]
fn zig_package_labels_parse_from_the_hash() {
let dep = |name: &str| ZonDependency { name: name.into(), hash: None, path: None, lazy: false };
assert_eq!(package_label(&dep("zap"), "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8"), "zap 0.1.0");
assert_eq!(
package_label(&dep("diffz"), "diffz-0.0.1-G2tlISvOAQDORzPTSxDgiKwlHuADKeJMdJrw4kRfLufj"),
"diffz 0.0.1"
);
assert_eq!(
package_label(&dep("zig-anytype"), "zig-anytype-0.1.0-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
"zig-anytype 0.1.0"
);
assert_eq!(package_label(&dep("old"), "1220b7c0"), "old");
}
#[cfg(unix)]
#[test]
fn zig_libraries_list_the_stdlib_and_fetched_packages() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let stdlib = root.join("stdlib");
std::fs::create_dir_all(&stdlib).unwrap();
std::fs::write(root.join("build.zig"), "").unwrap();
let hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
let cache = root.join("zig-cache");
write_package_blob(&cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
std::fs::write(
root.join("build.zig.zon"),
r#".{
.name = .app,
.dependencies = .{
// the package cache holds this one
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8" },
.local = .{ .path = "../shared" },
.gone = .{ .url = "https://example.com/gone.tar.gz", .hash = "gone-1.0.0-BBBBBBBBBB" },
},
}
"#,
)
.unwrap();
let bin = root.join("tools");
std::fs::create_dir(&bin).unwrap();
let zig = bin.join("zig");
std::fs::write(
&zig,
format!(
"#!/bin/sh\ncase \"$1\" in\n env) printf '%s\\n' '.{{\n .zig_exe = \"{}\",\n .std_dir = \"{}\",\n .global_cache_dir = \"{}\",\n .version = \"0.16.0\",\n}}' ;;\n version) echo 0.16.0 ;;\nesac\n",
zig.display(),
stdlib.display(),
cache.display(),
),
)
.unwrap();
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 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()))
.collect();
assert_eq!(
summary,
[("Zig 0.16.0", "zig", vec!["stdlib"]), ("Zig packages", "zigPackages", vec!["zap 0.1.0"])]
);
let packages = groups.iter().find(|g| g.kind == "zigPackages").unwrap();
assert_eq!(
packages.roots[0].path.to_string_lossy(),
format!("{}!/{hash}", cache.join("p").join(format!("{hash}.tar.gz")).display())
);
}
}
+80
Переглянути файл
@@ -35,6 +35,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -1589,6 +1590,85 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
.{
.name = .app,
.version = "0.1.0",
.fingerprint = 0x348e9ddfb4b9e03c,
.dependencies = .{
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-AAA" },
.@"weird name" = .{
.url = "https://example.com/w.tar.gz",
.hash = "weird-2.0.0-BBB",
.lazy = true,
},
.shared = .{ .path = "../shared" },
},
.paths = .{ "build.zig", "src" },
}
"#;
assert_eq!(
crate::zig::zon_dependencies(zon),
[
crate::zig::ZonDependency {
name: "zap".into(),
hash: Some("zap-0.1.0-AAA".into()),
path: None,
lazy: false
},
crate::zig::ZonDependency {
name: "weird name".into(),
hash: Some("weird-2.0.0-BBB".into()),
path: None,
lazy: true
},
crate::zig::ZonDependency {
name: "shared".into(),
hash: None,
path: Some("../shared".into()),
lazy: false
},
]
);
assert!(crate::zig::zon_dependencies(".{ .name = .app, .dependencies = .{} }").is_empty());
assert!(crate::zig::zon_dependencies(".{ .name = .app }").is_empty());
assert!(crate::zig::zon_dependencies("{ broken").is_empty());
assert_eq!(
crate::zig::zon_string_field(".{ .name = .probe_pkg, .version = \"0.1.0\" }", "name").as_deref(),
Some("probe_pkg")
);
}
#[test]
fn zig_env_is_parsed_from_json_and_struct_literals() {
let env = crate::zig::parse_zig_env(
r#"{"zig_exe":"/opt/zig/zig","lib_dir":"/opt/zig/lib","std_dir":"/opt/zig/lib/std","global_cache_dir":"/home/u/.cache/zig","version":"0.14.1"}"#,
)
.unwrap();
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
// Zig ≥ 0.15 prints a struct literal; a relative std_dir resolves against the install dir.
let env = crate::zig::parse_zig_env(
r#".{
.zig_exe = "/opt/zig/zig",
.lib_dir = "/opt/zig/lib",
.std_dir = "lib/std",
.global_cache_dir = "/home/u/.cache/zig",
.version = "0.16.0",
.target = "aarch64-macos",
.env = .{ .ZIG_GLOBAL_CACHE_DIR = null, .HOME = "/home/u" },
}"#,
)
.unwrap();
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
assert_eq!(env.version.as_deref(), Some("0.16.0"));
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
assert!(crate::zig::parse_zig_env("error: nothing").is_none());
}
#[test]
fn jdk_library_is_the_jdk_home() {
let tmp = tempfile::tempdir().unwrap();
+261
Переглянути файл
@@ -0,0 +1,261 @@
//! Reading Zig's own text formats for External Libraries, without running Zig:
//! the package manifest (`build.zig.zon`) and the `zig env` output. Both are
//! Zig struct literals; `zig env` printed JSON before Zig 0.15.
use serde::Deserialize;
use std::path::{Path, PathBuf};
/// One `.dependencies` entry of a `build.zig.zon`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ZonDependency {
pub name: String,
/// Package hash: its sources are fetched into the global cache as `p/<hash>`
/// (Zig ≤ 0.14 unpacks them, Zig ≥ 0.15 keeps `p/<hash>.tar.gz` blobs).
pub hash: Option<String>,
/// A path dependency, part of the project tree rather than the package cache.
pub path: Option<String>,
/// Fetched only when the build actually references it.
pub lazy: bool,
}
/// The `.dependencies` entries of a `build.zig.zon`, in order. Tolerant of
/// partially edited files: whatever does not parse is skipped.
pub(crate) fn zon_dependencies(zon: &str) -> Vec<ZonDependency> {
let src = code_only(zon);
let Some(top) = struct_body(&src) else { return Vec::new() };
let Some((_, value)) = fields(top).into_iter().find(|(name, _)| *name == "dependencies") else {
return Vec::new();
};
let Some(deps) = struct_body(value) else { return Vec::new() };
fields(deps)
.into_iter()
.map(|(name, value)| {
let entry = struct_body(value).map(|body| fields(body)).unwrap_or_default();
ZonDependency {
name: name.to_owned(),
hash: field(&entry, "hash"),
path: field(&entry, "path"),
lazy: entry.iter().any(|(n, v)| *n == "lazy" && v.trim() == "true"),
}
})
.collect()
}
/// A top-level string (or enum-literal, `.name`) field of a Zig struct literal.
pub(crate) fn zon_string_field(text: &str, name: &str) -> Option<String> {
let src = code_only(text);
let top = struct_body(&src)?;
field(&fields(top), name)
}
/// What `zig env` reports that External Libraries needs.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct ZigEnv {
pub zig_exe: Option<PathBuf>,
pub lib_dir: Option<PathBuf>,
pub std_dir: Option<PathBuf>,
pub global_cache_dir: Option<PathBuf>,
pub version: Option<String>,
}
impl ZigEnv {
/// The standard library sources: `std_dir`, else `lib_dir/std`. A relative
/// path resolves against the zig install dir (stage builds print relative paths).
pub(crate) fn std_sources(&self) -> Option<PathBuf> {
let resolve = |p: &Path| match (p.is_relative(), self.zig_exe.as_ref().and_then(|e| e.parent())) {
(true, Some(install)) => install.join(p),
_ => p.to_path_buf(),
};
self.std_dir
.as_deref()
.map(Path::new)
.map(resolve)
.or_else(|| self.lib_dir.as_deref().map(Path::new).map(|dir| resolve(dir).join("std")))
}
}
/// The `zig env` output: JSON (older Zig) or a struct literal (Zig ≥ 0.15).
pub(crate) fn parse_zig_env(out: &str) -> Option<ZigEnv> {
#[derive(Deserialize)]
struct Json {
zig_exe: Option<PathBuf>,
lib_dir: Option<PathBuf>,
std_dir: Option<PathBuf>,
global_cache_dir: Option<PathBuf>,
version: Option<String>,
}
if let Ok(json) = serde_json::from_str::<Json>(out.trim()) {
return Some(ZigEnv {
zig_exe: json.zig_exe,
lib_dir: json.lib_dir,
std_dir: json.std_dir,
global_cache_dir: json.global_cache_dir,
version: json.version,
});
}
let src = code_only(out);
let top = struct_body(&src)?;
let f = fields(top);
Some(ZigEnv {
zig_exe: field(&f, "zig_exe").map(PathBuf::from),
lib_dir: field(&f, "lib_dir").map(PathBuf::from),
std_dir: field(&f, "std_dir").map(PathBuf::from),
global_cache_dir: field(&f, "global_cache_dir").map(PathBuf::from),
version: field(&f, "version"),
})
}
/// The string (or enum-literal, `.foo`) value of a field of a struct body.
fn field<'a>(entry: &[(&'a str, &'a str)], name: &str) -> Option<String> {
let value = entry.iter().find(|(n, _)| *n == name)?.1;
if let Some(string) = string_value(value) {
return Some(string);
}
value
.strip_prefix('.')
.filter(|v| v.chars().next().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'))
.map(str::to_owned)
}
/// The contents of the string literal starting at `value`, `\"` unescaped.
fn string_value(value: &str) -> Option<String> {
let rest = value.trim_start().strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
/// `src` with comments blanked out and string contents kept.
fn code_only(src: &str) -> String {
let mut out = String::with_capacity(src.len());
for line in src.lines() {
let bytes = line.as_bytes();
let mut in_string = false;
let mut escaped = false;
let mut end = line.len();
for (i, &b) in bytes.iter().enumerate() {
if in_string {
match b {
_ if escaped => escaped = false,
b'\\' => escaped = true,
b'"' => in_string = false,
_ => {}
}
} else if b == b'"' {
in_string = true;
} else if b == b'/' && bytes.get(i + 1) == Some(&b'/') {
end = i;
break;
}
}
out.push_str(&line[..end]);
out.push('\n');
}
out
}
/// The inside of the first `{ … }` of `text`, strings respected.
fn struct_body(text: &str) -> Option<&str> {
let bytes = text.as_bytes();
let mut start = 0;
while start < bytes.len() {
match bytes[start] {
b'"' => start = skip_string(text, start),
b'{' => break,
_ => start += 1,
}
}
let mut depth = 0;
let mut i = start;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(text, i),
b'{' => {
depth += 1;
i += 1;
}
b'}' => {
if depth == 1 {
return Some(&text[start + 1..i]);
}
depth -= 1;
i += 1;
}
_ => i += 1,
}
}
None
}
/// The index just past the string literal starting at `i` (an opening `"`).
fn skip_string(text: &str, i: usize) -> usize {
let bytes = text.as_bytes();
let mut i = i + 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return i + 1,
_ => i += 1,
}
}
i
}
/// The `.name = value` fields of a struct literal body, in order: `name` is the
/// identifier (or `@"…"` unquoted), `value` trimmed and may itself be `.{ … }`.
fn fields(body: &str) -> Vec<(&str, &str)> {
let bytes = body.as_bytes();
let mut out = Vec::new();
let mut depth = 0;
let mut field: Option<usize> = None;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(body, i),
b'{' | b'[' | b'(' => {
depth += 1;
i += 1;
}
b'}' | b']' | b')' => {
if depth == 0 {
break;
}
depth -= 1;
i += 1;
}
b',' if depth == 0 => {
if let Some(start) = field.take() {
push_field(&mut out, body, start, i);
}
i += 1;
}
b'.' if depth == 0 && field.is_none() => {
if bytes.get(i + 1).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'@') {
field = Some(i + 1);
}
i += 1;
}
_ => i += 1,
}
}
if let Some(start) = field {
push_field(&mut out, body, start, bytes.len());
}
out
}
fn push_field<'a>(out: &mut Vec<(&'a str, &'a str)>, body: &'a str, start: usize, end: usize) {
let text = &body[start..end];
let Some(eq) = text.find('=') else { return };
let name = text[..eq].trim().trim_start_matches('@').trim_matches('"');
if !name.is_empty() {
out.push((name, text[eq + 1..].trim()));
}
}
+10
Переглянути файл
@@ -61,6 +61,9 @@ fn mise_and_asdf_installs_are_detected_and_pinned_versions_used() {
script(&maven.join("bin/mvn"), "Apache Maven 3.9.6");
write(&maven.join("lib/maven-core-3.9.6.jar"), "");
script(&installs.join("gradle/8.7/bin/gradle"), "Gradle 8.7");
// Zig: asdf keeps the executable at the install root, zvm under ~/.zvm.
script(&asdf.join("installs/zig/0.14.1/zig"), "0.14.1");
script(&tmp.join("home/.zvm/0.13.0/zig"), "0.13.0");
let project = tmp.join("project");
write(
@@ -91,6 +94,13 @@ fn mise_and_asdf_installs_are_detected_and_pinned_versions_used() {
let mvn = find(&mavens, &maven);
assert_eq!((mvn.source.as_str(), mvn.version.as_deref()), ("mise", Some("3.9.6")));
let zigs = detect(SdkKind::Zig, Some(&project));
let zig = find(&zigs, &asdf.join("installs/zig"));
assert_eq!((zig.source.as_str(), zig.version.as_deref()), ("asdf", Some("0.14.1")));
assert_eq!(zig.path, asdf.join("installs/zig/0.14.1"), "the setting stores the directory");
let zvm = find(&zigs, &tmp.join("home/.zvm"));
assert_eq!((zvm.source.as_str(), zvm.version.as_deref()), ("zvm", Some("0.13.0")));
// Nothing configured in Settings: the pinned versions apply.
let s = Settings::default();
let jdk = ide_sdk::apply::project_jdk(&project, &s).expect("pinned JDK");
+6 -1
Переглянути файл
@@ -56,7 +56,12 @@ impl<'a> Lines<'a> {
}
pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
if s.is_ascii() {
return s.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
fn utf16_to_byte(s: &str, offset: usize) -> usize {
+30 -9
Переглянути файл
@@ -39,6 +39,10 @@ impl LineEnding {
/// The dominant line ending of `text`; ties and text without any line
/// break resolve to [`LineEnding::Lf`].
pub fn detect(text: &str) -> Self {
// Without `\r` both other counts are zero and `Lf` wins outright.
if !text.contains('\r') {
return Self::Lf;
}
let (mut lf, mut crlf, mut cr) = (0usize, 0usize, 0usize);
let bytes = text.as_bytes();
let mut i = 0;
@@ -72,13 +76,20 @@ const DIFF_BUDGET: Duration = Duration::from_millis(50);
type LineRange = std::ops::Range<usize>;
/// Byte lengths of the common prefix and suffix; they never overlap.
/// Byte lengths of the common prefix and suffix; they never overlap. Compared
/// byte-wise (equal bytes imply equal chars) so the scan vectorizes, with the
/// ends backed off to char boundaries.
fn common_ends(a: &str, b: &str) -> (usize, usize) {
let shared = |a: &mut dyn Iterator<Item = char>, b: &mut dyn Iterator<Item = char>| -> usize {
a.zip(b).take_while(|(x, y)| x == y).map(|(x, _)| x.len_utf8()).sum()
};
let prefix = shared(&mut a.chars(), &mut b.chars());
let suffix = shared(&mut a[prefix..].chars().rev(), &mut b[prefix..].chars().rev());
let (ab, bb) = (a.as_bytes(), b.as_bytes());
let mut prefix = ab.iter().zip(bb).take_while(|(x, y)| x == y).count();
while !a.is_char_boundary(prefix) {
prefix -= 1;
}
let limit = ab.len().min(bb.len()) - prefix;
let mut suffix = ab.iter().rev().zip(bb.iter().rev()).take(limit).take_while(|(x, y)| x == y).count();
while suffix > 0 && !a.is_char_boundary(a.len() - suffix) {
suffix -= 1;
}
(prefix, suffix)
}
@@ -94,7 +105,13 @@ fn line_starts(lines: &[&str]) -> Vec<usize> {
}
fn utf16_len(text: &str) -> u32 {
text.chars().map(|c| c.len_utf16() as u32).sum()
let bytes = text.as_bytes();
if bytes.is_ascii() {
return bytes.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
bytes.iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
/// Converts `\r\n` and lone `\r` to `\n`. Borrows when there is nothing to do.
@@ -158,8 +175,12 @@ pub struct Document {
impl Document {
/// Builds a document from text with any line endings; detects and normalizes them.
pub fn new(text: &str) -> Self {
let line_ending = LineEnding::detect(text);
let rope = ropey::Rope::from_str(&normalize_line_endings(text));
// One `\r` scan decides both: LF text needs no normalization pass.
let (line_ending, rope) = if text.contains('\r') {
(LineEnding::detect(text), ropey::Rope::from_str(&normalize_line_endings(text)))
} else {
(LineEnding::Lf, ropey::Rope::from_str(text))
};
Self { rope, version: 0, line_ending }
}
+28 -3
Переглянути файл
@@ -331,8 +331,8 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
#[cfg(not(unix))]
{
let link = bin_dir.join(format!("{command}.cmd"));
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", cmd_path(bin_dir, v))).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
}
@@ -357,11 +357,25 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
{
let link = bin_dir.join(format!("{command}.cmd"));
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", target.display()))?;
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
}
/// `path` as a `.cmd` shim in `bin_dir` names it: relative to the shim (`%~dp0..\…`) when it
/// is in the tool's own directory. cmd.exe reads a batch file in the console's code page, so
/// an absolute path through a non-ASCII user directory, written as UTF-8, isn't found (#3338).
#[cfg_attr(unix, allow(dead_code))]
fn cmd_path(bin_dir: &Path, path: &Path) -> String {
match bin_dir.parent().and_then(|tool| path.strip_prefix(tool).ok()) {
Some(rest) => {
let rest: Vec<_> = rest.components().map(|c| c.as_os_str().to_string_lossy()).collect();
format!("%~dp0..\\{}", rest.join("\\"))
}
None => path.display().to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -743,6 +757,17 @@ mod tests {
assert!(found.ends_with("server/com.microsoft.java.debug.plugin-0.53.2.jar"));
}
#[test]
fn windows_shims_name_the_tool_relative_to_themselves() {
let tool = Path::new("/Users/张三/AppData/Local/ai.l0ng.openidea/tools/taplo");
let bin = tool.join("bin");
assert_eq!(cmd_path(&bin, &tool.join("taplo.exe")), "%~dp0..\\taplo.exe");
assert_eq!(cmd_path(&bin, &tool.join("gems/bin/solargraph")), "%~dp0..\\gems\\bin\\solargraph");
// Outside the tool's directory (a system SDK) stays absolute.
let sdk = Path::new("/usr/local/share/dotnet");
assert_eq!(cmd_path(&bin, sdk), sdk.display().to_string());
}
#[cfg(unix)]
#[test]
fn wrapper_runs_target() {
+22
Переглянути файл
@@ -170,6 +170,28 @@ mod tests {
assert_eq!(select_asset(&["laravel-lsp"], rules, LINUX_X64), None);
}
#[test]
fn phoxite_assets() {
let names = [
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-x86_64-pc-windows-msvc.exe",
// Not for any platform here: the musl build, the checksums, the VS Code packages.
"phoxite-lsp-x86_64-unknown-linux-musl",
"phoxite-lsp-x86_64-unknown-linux-gnu.sha256",
"phoxite-lsp-x86_64-pc-windows-msvc.exe.sha256",
"phoxite-linux-x64-0.2.1.vsix",
];
let rules = crate::registry::find("phoxite").unwrap().asset_rules();
assert_eq!(select_asset(&names, rules, MAC_ARM), Some(names[0]));
assert_eq!(select_asset(&names, rules, MAC_X64), Some(names[1]));
assert_eq!(select_asset(&names, rules, LINUX_ARM), Some(names[2]));
assert_eq!(select_asset(&names, rules, LINUX_X64), Some(names[3]));
assert_eq!(select_asset(&names, rules, WIN), Some(names[4]));
}
#[test]
fn kmp_lsp_assets_include_the_native_jar_indexer() {
let names = [
+32
Переглянути файл
@@ -458,6 +458,38 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/laravel/lsp",
needs: &[],
},
ToolSpec {
name: "phoxite",
display: "Phoxite",
kind: LanguageServer,
commands: &["phoxite-lsp"],
// Plain binaries per platform (`phoxite-lsp-<target triple>[.exe]`), each with a
// `.sha256` beside it.
method: Method::Release {
source: ReleaseSource::GitHub { repo: "samehelhawary/phoxite" },
assets: &[
rule(Mac, Arm64, "phoxite-lsp-aarch64-apple-darwin"),
rule(Mac, X64, "phoxite-lsp-x86_64-apple-darwin"),
rule(Linux, Arm64, "phoxite-lsp-aarch64-unknown-linux-gnu"),
rule(Linux, X64, "phoxite-lsp-x86_64-unknown-linux-gnu"),
rule(Windows, Arm64, "phoxite-lsp-aarch64-pc-windows-msvc.exe"),
rule(Windows, X64, "phoxite-lsp-x86_64-pc-windows-msvc.exe"),
],
locate: &[
"phoxite-lsp",
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-aarch64-pc-windows-msvc",
"phoxite-lsp-x86_64-pc-windows-msvc",
],
},
fallback: None,
version: ver("phoxite-lsp"),
homepage: "https://github.com/samehelhawary/phoxite",
needs: &[],
},
ToolSpec {
name: "gopls",
display: "gopls",
+145
Переглянути файл
@@ -0,0 +1,145 @@
//! Show Diff in External Tool: starts the user's diff program on the two sides of a diff.
use ide_core::{IdeError, IdeResult, settings::ExternalDiffSettings};
use serde::Deserialize;
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// One side of the diff: a file on disk, or text written to a temporary file.
#[derive(Clone, Debug, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalDiffSide {
/// A saved file, passed to the tool as it is.
pub path: Option<PathBuf>,
/// Content without a file of its own (a revision, a text), written to a temporary file.
pub text: Option<String>,
/// The temporary file's name; its extension lets the tool pick a syntax.
pub name: String,
}
/// Splits a parameter line like a shell does for plain words: whitespace separates
/// arguments, double or single quotes keep one together, a backslash escapes the next
/// character inside double quotes and outside quotes.
pub fn split_parameters(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut in_arg = false;
let mut quote: Option<char> = None;
let mut chars = line.chars();
while let Some(c) = chars.next() {
match (quote, c) {
(Some('\''), '\'') | (Some('"'), '"') => quote = None,
(Some('"') | None, '\\') => {
if let Some(next) = chars.next() {
cur.push(next);
}
in_arg = true;
}
(None, '"' | '\'') => {
quote = Some(c);
in_arg = true;
}
(None, c) if c.is_whitespace() => {
if in_arg {
out.push(std::mem::take(&mut cur));
in_arg = false;
}
}
(_, c) => {
cur.push(c);
in_arg = true;
}
}
}
if in_arg {
out.push(cur);
}
out
}
/// The tool's arguments: `%1` the left file, `%2` the right file, `%3` the title.
pub fn expand_parameters(parameters: &str, left: &str, right: &str, title: &str) -> Vec<String> {
split_parameters(parameters)
.into_iter()
.map(|arg| arg.replace("%1", left).replace("%2", right).replace("%3", title))
.collect()
}
fn side_file(side: &ExternalDiffSide, dir: &Path, sub: &str) -> IdeResult<PathBuf> {
if let Some(path) = &side.path {
return Ok(path.clone());
}
let name = Path::new(&side.name).file_name().map(|n| n.to_owned()).unwrap_or_else(|| "content".into());
let folder = dir.join(sub);
std::fs::create_dir_all(&folder)?;
let file = folder.join(name);
std::fs::write(&file, side.text.as_deref().unwrap_or_default())?;
Ok(file)
}
/// Starts the configured tool on `left` ↔ `right` and returns once it runs; the tool
/// lives on after the diff closes, as it would started from a shell.
pub fn launch_external_diff(
settings: &ExternalDiffSettings,
left: &ExternalDiffSide,
right: &ExternalDiffSide,
title: &str,
) -> IdeResult<()> {
let program = settings.path.trim();
if program.is_empty() {
return Err(IdeError::invalid("no external diff tool is set (Settings › Tools › External Diff Tools)"));
}
let needs_temp = left.path.is_none() || right.path.is_none();
// Kept after the call: the tool reads the files after it starts.
let dir = if needs_temp { Some(tempfile::Builder::new().prefix("openidea-diff-").tempdir()?.keep()) } else { None };
let temp = dir.as_deref().unwrap_or_else(|| Path::new(""));
let a = side_file(left, temp, "left")?;
let b = side_file(right, temp, "right")?;
let args = expand_parameters(&settings.parameters, &a.to_string_lossy(), &b.to_string_lossy(), title);
let mut cmd = Command::new(program);
ide_core::process::prepare(&mut cmd);
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
let mut child = cmd
.spawn()
.map_err(|e| IdeError::unavailable(format!("cannot start the external diff tool {program}: {e}")))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_quoted_parameters() {
assert_eq!(split_parameters("%1 %2 %3"), ["%1", "%2", "%3"]);
assert_eq!(split_parameters(r#"--title "%3" -L 'a b' x\ y"#), ["--title", "%3", "-L", "a b", "x y"]);
assert_eq!(split_parameters(r#"--empty "" end"#), ["--empty", "", "end"]);
}
#[test]
fn expands_placeholders_inside_arguments() {
let args = expand_parameters("--left=%1 %2 --title %3", "/t/a b.rs", "/t/b.rs", "a.rs (HEAD ↔ Your version)");
assert_eq!(args, ["--left=/t/a b.rs", "/t/b.rs", "--title", "a.rs (HEAD ↔ Your version)"]);
}
#[test]
fn writes_text_sides_to_named_temporary_files() {
let dir = tempfile::tempdir().unwrap();
let side = ExternalDiffSide { path: None, text: Some("x\n".into()), name: "../Main.java".into() };
let file = side_file(&side, dir.path(), "left").unwrap();
assert_eq!(file, dir.path().join("left/Main.java"));
assert_eq!(std::fs::read_to_string(file).unwrap(), "x\n");
let saved = ExternalDiffSide { path: Some("/p/a.rs".into()), text: None, name: "a.rs".into() };
assert_eq!(side_file(&saved, dir.path(), "right").unwrap(), PathBuf::from("/p/a.rs"));
}
#[test]
fn needs_a_program() {
let side = ExternalDiffSide { path: Some("/p/a".into()), text: None, name: "a".into() };
assert!(launch_external_diff(&ExternalDiffSettings::default(), &side, &side, "t").is_err());
}
}
+11
Переглянути файл
@@ -496,6 +496,9 @@ pub struct CheckoutOptions {
/// Required when checking out a remote branch whose local namesake is ahead of it.
#[serde(default)]
pub diverged: Option<DivergedLocal>,
/// Check the branch out even though another worktree has it checked out.
#[serde(default)]
pub ignore_other_worktrees: bool,
}
/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
@@ -522,6 +525,12 @@ pub enum CheckoutOutcome {
Conflicts {
files: Vec<String>,
},
/// Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
/// changed; the branch can be worked on there.
CheckedOutInWorktree {
branch: String,
path: PathBuf,
},
}
/// HEAD before and after a history rewrite, for its Undo.
@@ -618,6 +627,7 @@ pub mod changelists;
mod cli;
mod compare;
mod diff;
mod external_diff;
mod history;
mod ignore;
mod index_writes;
@@ -644,6 +654,7 @@ pub use cli::{
set_git_command_observer, set_git_executable,
};
pub use diff::build_partial_patch;
pub use external_diff::{ExternalDiffSide, launch_external_diff};
pub use ignore::{IgnoreDestination, add_to_ignore};
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
pub use remotes::Remote;
+10 -16
Переглянути файл
@@ -24,8 +24,8 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
&& let Some((upstream_name, upstream_id)) = upstream_of(&repo, name.as_ref())
{
info.upstream = Some(upstream_name);
if let (Some(local), Some(up)) = (head_commit, upstream_id) {
let (a, b) = ahead_behind(&repo, local, up)?;
if let Some(local) = head_commit {
let (a, b) = ahead_behind(&repo, local, upstream_id)?;
info.ahead = a;
info.behind = b;
}
@@ -51,16 +51,12 @@ pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
Some(op.to_string())
}
/// Short upstream name (`origin/main`) and, if the tracking ref exists, its commit.
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, Option<gix::ObjectId>)> {
/// Short upstream name (`origin/main`) and its commit. A branch whose tracking ref is gone (the
/// remote branch was deleted and pruned) tracks nothing, as in IDEA.
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, gix::ObjectId)> {
let tracking = repo.branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)?.ok()?;
let short = to_string(tracking.as_ref().shorten());
let id = repo
.try_find_reference(tracking.as_ref())
.ok()
.flatten()
.and_then(|mut r| r.peel_to_id().ok().map(|id| id.detach()));
Some((short, id))
let id = repo.try_find_reference(tracking.as_ref()).ok()??.peel_to_id().ok()?.detach();
Some((to_string(tracking.as_ref().shorten()), id))
}
/// Commits in `local` not in `upstream`, and vice versa.
@@ -114,11 +110,9 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
};
if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) {
branch.upstream = Some(up);
if let Some(up_id) = up_id {
let (a, b) = ahead_behind(&repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
}
let (a, b) = ahead_behind(&repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
}
out.push(branch);
}
+42 -2
Переглянути файл
@@ -765,6 +765,18 @@ fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
listed_files(stderr, "untracked working tree files would be")
}
/// The branch git refused to check out or update because another worktree has it, from
/// its error message: a switch says `'<branch>' is already used by worktree at '<path>'`,
/// a forced update says `cannot force update the branch '<branch>' used by worktree at
/// '<path>'`; git before 2.42 says `'<branch>' is already checked out at '<path>'`.
fn branch_of_other_worktree(stderr: &str) -> Option<(String, String)> {
const MARKERS: [&str; 3] =
["' is already used by worktree at '", "' used by worktree at '", "' is already checked out at '"];
let (before, path) = stderr.lines().find_map(|l| MARKERS.iter().find_map(|m| l.split_once(m)))?;
let branch = before.rsplit('\'').next()?.to_string();
Some((branch, path.strip_suffix('\'').unwrap_or(path).to_string()))
}
fn listed_files(stderr: &str, header: &str) -> Option<Vec<String>> {
let mut lines = stderr.lines().skip_while(|l| !l.contains(header));
lines.next()?;
@@ -805,12 +817,18 @@ pub(crate) fn checkout_with(
if options.mode == CheckoutMode::Force {
args.push("--discard-changes".into());
}
if options.ignore_other_worktrees {
args.push("--ignore-other-worktrees".into());
}
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
let out = cli::run_raw(r.root(), &argv, None)?;
if out.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let stderr = String::from_utf8_lossy(&out.stderr);
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
}
if let Some(files) = overwritten_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files });
}
@@ -893,7 +911,14 @@ pub(crate) fn create_branch(
args.extend(["--", name]);
}
args.extend(start);
run(r.root(), &args, None).map(|_| ())
let out = cli::run_raw(r.root(), &args, None)?;
if out.code == Some(0) {
return Ok(());
}
if let Some((branch, path)) = branch_of_other_worktree(&String::from_utf8_lossy(&out.stderr)) {
return Err(IdeError::invalid(format!("branch '{branch}' is already checked out in worktree at '{path}'")));
}
Err(cli::failure(&args, &out.stderr, &out.stdout, out.code))
}
/// Whether `start` is a remote-tracking branch with another name than the new branch
@@ -1479,7 +1504,22 @@ fn decode_diff(bytes: &[u8], encoding: TextEncoding) -> String {
#[cfg(test)]
mod tests {
use super::append_revision;
use super::{append_revision, branch_of_other_worktree};
#[test]
fn the_worktree_holding_a_branch_is_read_from_each_git_wording() {
let held = |b: &str, p: &str| Some((b.to_string(), p.to_string()));
assert_eq!(
branch_of_other_worktree("fatal: 'topic' is already used by worktree at '/w/t'\n"),
held("topic", "/w/t")
);
assert_eq!(
branch_of_other_worktree("fatal: cannot force update the branch 'topic' used by worktree at '/w/t'"),
held("topic", "/w/t")
);
assert_eq!(branch_of_other_worktree("fatal: 'a/b' is already checked out at '/w/t'"), held("a/b", "/w/t"));
assert_eq!(branch_of_other_worktree("fatal: invalid reference: x"), None);
}
#[test]
fn a_revision_is_appended_once_keeping_the_list() {
+6
Переглянути файл
@@ -777,12 +777,18 @@ fn fetch_prunes_deleted_remote_branches() {
let (fx, bare) = Fixture::with_origin();
fx.git(&["push", "-q", "origin", "main:gone"]);
fx.git(&["fetch", "-q"]);
fx.git(&["checkout", "-q", "-b", "feature", "--track", "origin/gone"]);
let repo = fx.repo();
let upstream = || repo.branches().unwrap().into_iter().find(|b| b.name == "feature").and_then(|b| b.upstream);
assert!(repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
assert_eq!(upstream().as_deref(), Some("origin/gone"));
git_in(&bare, &["branch", "-D", "gone"]);
let (cancel, out) = quiet();
repo.fetch(&cancel, &out).unwrap();
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
// The branch that tracked it no longer counts as tracking, as in IDEA.
assert_eq!(upstream(), None);
assert_eq!(repo.branch_info().unwrap().upstream, None);
}
#[test]
+47 -3
Переглянути файл
@@ -1070,7 +1070,7 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
fx.commit_all("other edit");
fx.git(&["checkout", "-q", "main"]);
let repo = fx.repo();
let opts = |mode| CheckoutOptions { mode, diverged: None };
let opts = |mode| CheckoutOptions { mode, ..Default::default() };
// A non-conflicting local edit to a file the switch rewrites.
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
@@ -1110,6 +1110,50 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
}
#[test]
fn checkout_of_a_branch_held_by_another_worktree_reports_it_and_changes_nothing() {
let fx = Fixture::new();
fx.write("f.txt", "1\n");
fx.commit_all("base");
let linked = fx._tmp.path().join("linked");
fx.git(&["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
let repo = fx.repo();
let none = CheckoutOptions::default();
let linked_path = std::fs::canonicalize(&linked).unwrap();
// From the main worktree, the branch the linked worktree has checked out.
let outcome = repo.checkout_with("topic", false, &none).unwrap();
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
// With local changes in the way too: reported before any Smart Checkout stash.
fx.write("f.txt", "changed\n");
let smart = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
let outcome = repo.checkout_with("topic", false, &smart).unwrap();
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
assert_eq!(fx.read("f.txt"), "changed\n", "local changes untouched");
assert!(repo.stashes().unwrap().is_empty());
fx.git(&["reset", "-q", "--hard"]);
// The same refusal from the linked worktree, for the main worktree's branch.
let linked_repo = Repo::discover(&linked).unwrap().unwrap();
linked_repo.set_execution_allowed(true);
let outcome = linked_repo.checkout_with("main", false, &none).unwrap();
let main_path = std::fs::canonicalize(&fx.dir).unwrap();
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "main".into(), path: main_path });
assert_eq!(linked_repo.branch_info().unwrap().head.as_deref(), Some("topic"));
// Overwriting such a branch (New Branch with Checkout) names the worktree, not raw stderr.
let error = repo.create_branch_with_overwrite("topic", Some("main"), true, true).unwrap_err();
assert!(error.message.contains("branch 'topic' is already checked out in worktree"), "{error}");
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
// Checkout Anyway: both worktrees then have the branch.
let anyway = CheckoutOptions { ignore_other_worktrees: true, ..Default::default() };
assert_eq!(repo.checkout_with("topic", false, &anyway).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
}
#[test]
fn checkout_remote_branch_with_existing_local_namesake() {
let (fx, bare) = with_remote();
@@ -1939,7 +1983,7 @@ fn smart_checkout_keeps_staged_changes_staged() {
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
fx.write("s.txt", "staged\n");
fx.git(&["add", "s.txt"]);
let opts = CheckoutOptions { mode: CheckoutMode::Smart, diverged: None };
let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n");
@@ -1960,7 +2004,7 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
fx.write("dir/new.txt", "mine\n");
let repo = fx.repo();
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
let opts = CheckoutOptions { mode, diverged: None };
let opts = CheckoutOptions { mode, ..Default::default() };
let outcome = repo.checkout_with("other", false, &opts).unwrap();
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
+2
Переглянути файл
@@ -20,6 +20,8 @@ trash.workspace = true
tracing.workspace = true
parking_lot.workspace = true
zip.workspace = true
flate2.workspace = true
tar.workspace = true
[dev-dependencies]
tempfile.workspace = true
+163 -44
Переглянути файл
@@ -1,6 +1,7 @@
//! Read-only browsing of zip archives (jar, zip, war…), IDEA's `jar://` file
//! system: `<archive>!` is the archive's root and `<archive>!/<entry>` an entry
//! inside it. Listing and reading go through a small cache of parsed central
//! Read-only browsing of zip archives (jar, zip, war…) and gzip'd tars (Zig
//! keeps its fetched packages as `.tar.gz` blobs), IDEA's `jar://` file system:
//! `<archive>!` is the archive's root and `<archive>!/<entry>` an entry inside
//! it. Listing and reading go through a small cache of parsed central
//! directories, refreshed when the archive changes on disk.
use crate::{EntryKind, FileEntry, mtime_ms, natural_cmp};
@@ -8,7 +9,7 @@ use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::{Read, Seek};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
@@ -22,13 +23,21 @@ pub const ARCHIVE_SEPARATOR: char = '!';
/// Parsed archives kept open.
const CACHE_SIZE: usize = 8;
/// Whether `path` names a file browsed as an archive (by extension).
/// Whether `path` names a file browsed as an archive: a zip extension, or a
/// gzip'd tar (`x.tar.gz`).
pub fn is_archive_file(path: &Path) -> bool {
if is_tar_gz(path) {
return true;
}
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| ARCHIVE_EXTENSIONS.iter().any(|a| a.eq_ignore_ascii_case(e)))
}
fn is_tar_gz(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.to_ascii_lowercase().ends_with(".tar.gz"))
}
/// `(archive, entry)` for `<archive>!` (entry `""`) or `<archive>!/<entry>`;
/// `None` for ordinary paths. The entry is `/`-separated without leading or trailing `/`.
pub fn split_archive_path(path: &Path) -> Option<(PathBuf, String)> {
@@ -84,7 +93,14 @@ struct Archive {
mtime_ms: f64,
/// Entry path (`""` = root) → node.
nodes: HashMap<String, Node>,
zip: Mutex<zip::ZipArchive<File>>,
contents: Contents,
}
/// Where entry contents come from: a random-access zip, or a gzip'd tar that
/// is re-scanned per read (package tarballs are small).
enum Contents {
Zip(Mutex<zip::ZipArchive<File>>),
Tar(Mutex<File>),
}
/// Most recently used first.
@@ -115,43 +131,83 @@ fn parent_of(name: &str) -> (&str, &str) {
impl Archive {
fn open(path: &Path, stamp: (Option<SystemTime>, u64), mtime_ms: f64) -> IdeResult<Self> {
let mut zip = zip::ZipArchive::new(File::open(path)?).map_err(|e| zip_error(path, e))?;
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
for i in 0..zip.len() {
let Ok(file) = zip.by_index_raw(i) else { continue };
let Ok(name) = file.name() else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = (file.is_dir(), file.size());
drop(file);
let mut parent = parent_of(&name).0;
while !nodes.contains_key(parent) {
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
parent = parent_of(parent).0;
}
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
node.dir |= dir;
node.index = Some(i);
node.size = if node.dir { 0 } else { size };
}
let links: Vec<(String, String)> = nodes
.keys()
.filter(|k| !k.is_empty())
.map(|k| {
let (parent, base) = parent_of(k);
(parent.to_owned(), base.to_owned())
})
.collect();
for (parent, base) in links {
if let Some(p) = nodes.get_mut(&parent) {
p.dir = true;
p.children.push(base);
}
}
Ok(Self { stamp, mtime_ms, nodes, zip: Mutex::new(zip) })
let file = File::open(path)?;
let (nodes, contents) = if is_tar_gz(path) {
(tar_nodes(&file)?, Contents::Tar(Mutex::new(file)))
} else {
let mut zip = zip::ZipArchive::new(file).map_err(|e| zip_error(path, e))?;
let nodes = zip_nodes(&mut zip)?;
(nodes, Contents::Zip(Mutex::new(zip)))
};
Ok(Self { stamp, mtime_ms, nodes, contents })
}
}
/// The directory tree of a zip, with each entry's central-directory index.
fn zip_nodes(zip: &mut zip::ZipArchive<File>) -> IdeResult<HashMap<String, Node>> {
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
for i in 0..zip.len() {
let Ok(file) = zip.by_index_raw(i) else { continue };
let Ok(name) = file.name() else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = (file.is_dir(), file.size());
drop(file);
add_entry(&mut nodes, name, i, dir, size);
}
Ok(link_children(nodes))
}
/// The directory tree of a gzip'd tar, with each entry's ordinal position.
/// Entries are re-read by streaming the (decompressed) tar again.
fn tar_nodes(file: &File) -> IdeResult<HashMap<String, Node>> {
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
for (i, entry) in tar.entries()?.enumerate() {
let Ok(entry) = entry else { break };
let Ok(name) = entry.path().map(|p| p.to_string_lossy().into_owned()) else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = match entry.header().entry_type().is_dir() {
true => (true, 0),
false => (false, entry.header().size().unwrap_or_default()),
};
add_entry(&mut nodes, name, i, dir, size);
}
Ok(link_children(nodes))
}
fn add_entry(nodes: &mut HashMap<String, Node>, name: String, index: usize, dir: bool, size: u64) {
let mut parent = parent_of(&name).0;
while !nodes.contains_key(parent) {
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
parent = parent_of(parent).0;
}
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
node.dir |= dir;
node.index = Some(index);
node.size = if node.dir { 0 } else { size };
}
/// Makes every named entry a child of its parent folder node.
fn link_children(mut nodes: HashMap<String, Node>) -> HashMap<String, Node> {
let links: Vec<(String, String)> = nodes
.keys()
.filter(|k| !k.is_empty())
.map(|k| {
let (parent, base) = parent_of(k);
(parent.to_owned(), base.to_owned())
})
.collect();
for (parent, base) in links {
if let Some(p) = nodes.get_mut(&parent) {
p.dir = true;
p.children.push(base);
}
}
nodes
}
/// The parsed archive at `path`, from the cache unless it changed on disk.
fn archive(path: &Path) -> IdeResult<Arc<Archive>> {
let meta = std::fs::metadata(path)?;
@@ -235,10 +291,31 @@ pub fn read_archive_entry(archive_path: &Path, entry: &str) -> IdeResult<(Vec<u8
Some(_) => return Err(IdeError::invalid(format!("{entry} is a directory"))),
None => return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display()))),
};
let mut zip = a.zip.lock();
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
file.read_to_end(&mut bytes)?;
let bytes = match &a.contents {
Contents::Zip(zip) => {
let mut zip = zip.lock();
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
file.read_to_end(&mut bytes)?;
bytes
}
Contents::Tar(file) => {
let mut file = file.lock();
file.seek(std::io::SeekFrom::Start(0))?;
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(&mut *file));
for (i, entry) in tar.entries()?.enumerate() {
if i != index {
continue;
}
let mut entry = entry.map_err(|e| IdeError::invalid(format!("{}: {e}", archive_path.display())))?;
let mut bytes =
Vec::with_capacity(entry.header().size().unwrap_or_default().min(crate::MAX_OPEN_SIZE) as usize);
entry.read_to_end(&mut bytes)?;
return Ok((bytes, a.mtime_ms));
}
return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display())));
}
};
Ok((bytes, a.mtime_ms))
}
@@ -262,6 +339,20 @@ pub(crate) mod tests {
w.finish().unwrap();
}
/// Writes a gzip'd tar with `files`, the layout of the Zig package cache blobs.
pub(crate) fn write_tar_gz(path: &Path, files: &[(&str, &str)]) {
let enc = flate2::write::GzEncoder::new(File::create(path).unwrap(), flate2::Compression::default());
let mut b = tar::Builder::new(enc);
for (name, text) in files {
let mut header = tar::Header::new_gnu();
header.set_size(text.len() as u64);
header.set_mode(0o644);
header.set_cksum();
b.append_data(&mut header, name, text.as_bytes()).unwrap();
}
b.into_inner().unwrap().finish().unwrap();
}
#[test]
fn splits_archive_paths() {
assert_eq!(split_archive_path(Path::new("/a/b.txt")), None);
@@ -317,6 +408,34 @@ pub(crate) mod tests {
assert_eq!(names(""), vec![("only.txt".into(), EntryKind::File)]);
}
#[test]
fn lists_and_reads_gzipped_tars() {
let tmp = tempfile::tempdir().unwrap();
let hash = "probe_pkg-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
let blob = tmp.path().join(format!("{hash}.tar.gz"));
let (zon, lib) = (format!("{hash}/build.zig.zon"), format!("{hash}/src/lib.zig"));
write_tar_gz(&blob, &[(zon.as_str(), ".{ .name = .probe_pkg }"), (lib.as_str(), "pub fn hello() {}\n")]);
let root = |entry: &str| PathBuf::from(format!("{}!/{entry}", blob.display()));
let names = |dir: &str| -> Vec<String> {
crate::read_dir(&root(&format!("{hash}/{dir}")), &[]).unwrap().into_iter().map(|e| e.name).collect()
};
assert_eq!(names(""), vec!["src", "build.zig.zon"]);
assert_eq!(names("src"), vec!["lib.zig"]);
let lib = crate::load_text(&root(&format!("{hash}/src/lib.zig"))).unwrap();
assert_eq!((lib.text.as_str(), lib.binary), ("pub fn hello() {}\n", false));
// A rewritten tar is re-read, and a plain `.gz` stays an ordinary file.
write_tar_gz(&blob, &[("only.zig", "1")]);
let f = File::options().write(true).open(&blob).unwrap();
f.set_modified(SystemTime::now() + std::time::Duration::from_secs(5)).unwrap();
assert_eq!(
crate::read_dir(&root(""), &[]).unwrap().iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
["only.zig"]
);
assert!(!is_archive_file(Path::new("/a/data.gz")));
assert!(is_archive_file(Path::new("/a/pack.TAR.GZ")));
}
#[test]
fn read_dir_and_load_text_go_through_archives() {
let tmp = tempfile::tempdir().unwrap();
+2 -2
Переглянути файл
@@ -197,5 +197,5 @@ You don't write anything special for remote development. In a remote window, `sr
1. Put the logic in the owning crate; convert errors to `IdeError` at its edge; use IPC coordinates.
2. Add the shared implementation to `ide-host::ops::<domain>` if it touches a project; register it with the remote dispatcher if remote windows need it.
3. Add the `#[tauri::command] #[specta::specta]` adapter in `src-tauri/src/commands/<domain>.rs` and list it in `collect_commands!`.
4. If it executes anything, leave it out of the restricted-mode allowlist (it is denied in untrusted projects by default).
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`.
4. Decide its trust class: list it by exact name in `restricted_command_allowed` (also in Restricted Mode) or `projectless_command_allowed` (also with no project open), or leave it out to require a trusted project. There are no name prefixes; if it executes anything, leave it out.
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`. It also rewrites `src-tauri/tests/commands.snap`; check that the new line shows the trust class and placement you meant.
+3 -1
Переглянути файл
@@ -28,6 +28,8 @@ Style components with CSS Modules: `Thing.module.css` next to `Thing.tsx`, impor
Build from the primitives in `src/ui/` before writing your own: `Button`, `BarButton`, `Input`, `Checkbox`, `Select`, `Dialog`, `Popup`, `Menu`, `Tooltip`, `List`, `Tree`, `Tabs`, `Splitter`, `Scrollbar`, `Spinner`, `Kbd`, and `T` for translated text. They already handle focus, keyboard navigation, theming and translation of their labels. Workbench-level pieces (tool windows, status items, overlays) come from [contributions](/en/contribute/architecture/frontend#contributions), not from custom layout.
Toolbar icon actions use `IconButton`: its full hit target uses `--bg-toolbar-hover` on hover, while pressed and selected states use their corresponding toolbar tokens. Keep semantic icon colours and the keyboard focus ring intact.
## Accessibility
- Use real `<button>` and `<input>` elements (or the primitives that render them), never clickable `<div>`s.
@@ -41,7 +43,7 @@ User-visible text is written in English at the call site and goes through the te
## WebKit compatibility
On macOS and Linux the app runs in WebKit, and the supported floor is Safari 16, the engine of macOS 13 (on macOS 11 and 12 a Safari update doesn't update the engine other apps use). `pnpm build` runs `scripts/check-webkit.ts` on the bundle, and `src/platform/webkitCompatibility.test.ts` checks application regexes. Avoid:
On macOS and Linux the app runs in WebKit, and the supported floor is Safari 15.4, the engine of macOS 12 (the app's minimum). `pnpm build` runs `scripts/check-webkit.ts` on the bundle, and `src/platform/webkitCompatibility.test.ts` checks application regexes. Avoid:
- regex lookbehind (`(?<=…)`, `(?<!…)`), which needs Safari 16.4, and the regex `v` flag;
- import attributes;
+1 -1
Переглянути файл
@@ -31,7 +31,7 @@ Opening a project folder can run code that the project controls: language server
- When a project that hasn't been decided opens, the **Trust and Open Project?** dialog offers **Trust Project**, **Preview in Restricted Mode** and **Don't Open**. Decisions and trusted locations are managed on Settings' **Project Trust** page (group **Security**), and **Revoke Trust** is an action.
- Trust is user-owned state (`crates/ide-host/src/trust.rs`). **Project settings never grant trust.**
- Enforcement is in the backend, not the UI: every IPC command passes `Host::authorize_command` in the Tauri invoke handler (`src-tauri/src/lib.rs`) before it runs. In an untrusted project only commands on an explicit allowlist (`restricted_command_allowed`) run: reading and editing files and documents, syntax, search, navigation, local history, spelling, analysis, refactoring, settings and similar.
- The allowlist is a default-deny list: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode.
- The allowlist is a default-deny list of exact names: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode. `src-tauri/tests/commands.snap` lists every command's trust class, so a change shows up in review.
- Below the command layer, language servers don't start (`LspManager` execution switch), and git runs with execution disabled and without the project's `git` executable setting until the project is trusted. Project plugins (`.openidea/plugins/`) load only for trusted projects.
- In a remote window the desktop checks the remote project's trust before forwarding a command, and `openidea-server` authorizes every `invoke` again.
+6 -6
Переглянути файл
@@ -7,12 +7,12 @@ Smoke tests check each language end to end with the real tools the IDE uses: lan
They are not part of `cargo nextest run` or `pnpm test`, because they need the tools installed. CI runs them in the **Language smoke** workflow with pinned versions.
| Suite | What it checks | Languages |
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------- |
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php |
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, php |
| Suite | What it checks | Languages |
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------ |
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php, zig |
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, zig, php |
## Language smoke
+4
Переглянути файл
@@ -56,6 +56,8 @@ Agents are unavailable in a project you have not marked as trusted.
Available models depend on the installed agent and account. If a selected model is removed, choose another before starting. Refreshing does not change running tasks.
The version below the prompt is reported by a fresh agent initialization when this page is shown or the window regains focus. After updating a CLI, return to this page to refresh it. This does not restart running tasks; an already running agent process keeps its original version until it exits.
</Step>
<Step title="Send">
The task opens as an editor tab and starts.
@@ -119,6 +121,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
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.
## Add a custom agent
Any agent that speaks ACP over stdio can be added with an agent file, `agents/<id>.toml` in OpenIDEA's configuration directory:
+2 -1
Переглянути файл
@@ -146,7 +146,8 @@ Closing a selected result activates its left neighbor, or its right neighbor if
**Edit Data** (`F4`) opens a table in an editor tab with server-side paging (100 to 5,000 rows), a `WHERE` filter and an `ORDER BY` field (both with completion). Click a column header to sort; `Shift`-click to add more sort columns.
- Double-click, `Enter` or `F2` edits a cell; `Shift+Enter` opens a larger editor. Pasting tab-separated text fills several cells.
- **Add Row**, **Delete Rows**, **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
- **Add Row** (`⌘N` / `Alt+Insert`), **Delete Rows** (`Ctrl+Y` on Windows and Linux), **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
- **Reload Page** (`⌘R` / `Ctrl+F5`), **Previous Page** and **Next Page** (`⌘⌥↑` / `⌘⌥↓`, `Ctrl+Alt+Up` / `Ctrl+Alt+Down`). These, the copy commands and **Export Data** are actions: find them with **Find Action** and assign shortcuts in **Settings › Keymap**.
- **Submit** (`⌘Enter` / `Ctrl+Enter`) sends all pending changes in one transaction; **Revert** (`⌘⌥Z` / `Ctrl+Alt+Z`) discards them.
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
+2 -2
Переглянути файл
@@ -47,7 +47,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
| **Move Caret to Code Block Start** / **End** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
| **Toggle Insert/Overwrite** | `Insert` | `Insert` |
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines; they have no default shortcut.
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
Brackets and quotes are paired as you type, and typing a quote or bracket over a selection surrounds it. These and other typing aids (smart Home, Tab out of a closing bracket, smart indent on Enter, documentation comment stubs, what Backspace does with indentation, reformat on paste) are under **Settings › Editor › General › Smart Keys**.
@@ -117,7 +117,7 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
| **Go to Next Splitter** | `⌥⇥` | `Alt+Tab` |
| **Go to Previous Splitter** | `⌥⇧⇥` | `Alt+Shift+Tab` |
**Window › Editor Tabs** also offers **Split Down**, **Unsplit**, **Unsplit All**, **Move to Opposite Group**, **Open in Opposite Group** and **Change Splitter Orientation**. You can also drag a tab to an edge of the editor area to split it.
**Window › Editor Tabs** also offers **Split Down**, **Unsplit**, **Unsplit All**, **Move to Opposite Group**, **Open in Opposite Group** and **Change Splitter Orientation**. You can also drag a tab to an edge of the editor area to split it. In the Project view, **Open in Right Split** (`⇧↵` / `Shift+Enter`, also in the context menu) opens the selected file in the split to the right.
## View options
+1 -1
Переглянути файл
@@ -9,7 +9,7 @@ In the file names below, `<version>` is the release version, for example `0.1.40
## macOS
macOS 13 Ventura or later.
macOS 12 Monterey or later.
| Mac | File |
| ------------- | -------------------------------- |
+1
Переглянути файл
@@ -101,6 +101,7 @@ Each entry starts one LSP server. Servers are listed in order; all regular serve
| `settings` | table | Answers the server's `workspace/configuration` requests. Without it, the requested sections are looked up in `initialization-options`. |
| `install-hint` | string | Shown when the server is missing and the IDE cannot install it. |
| `fallback` | bool | An alternative to the servers listed before it; used only while none of them is installed. |
| `replaces` | string array | Names of servers listed after this one that it makes redundant. They are not used while this server serves the file. Use it for an alternative that covers what an added server does. |
| `features` | string array | Use the server only for these features; empty means everything. Values: `completion`, `inline-completion`, `hover`, `signature-help`, `definition`, `declaration`, `type-definition`, `implementation`, `references`, `document-highlight`, `document-symbol`, `workspace-symbol`, `code-action`, `code-lens`, `rename`, `formatting`, `inlay-hint`, `semantic-tokens`, `document-link`, `call-hierarchy`, `type-hierarchy`, `folding-range`, `selection-range`, `diagnostics`. |
| `code-action-kinds` | string array | Keep only these code action kinds, matched by prefix (`refactor` keeps `refactor.extract`); empty keeps all. |
| `connect` | string | `host:port` of a server that speaks LSP over TCP. See [TCP servers](#tcp-servers). |
+1 -1
Переглянути файл
@@ -148,7 +148,7 @@ The table lists every built-in language definition. Server and debugger names in
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
+11 -7
Переглянути файл
@@ -7,11 +7,14 @@ OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.p
## Language servers
| Server | When it runs |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
| Server | When it runs |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `phoxite` | Alternative with its own Laravel and Blade support: used while neither server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
While Phoxite serves a project, `laravel-lsp` is not started: Phoxite answers the Laravel strings itself.
Intelephense checks code against the project's PHP version (see [Language level](#language-level)) and indexes the stubs and include paths you configure.
@@ -25,6 +28,7 @@ When a `.php` file opens and Intelephense is missing, a notification offers **In
| ------------------ | ---------------------------------------------------------------------- |
| Intelephense | npm (`intelephense`) |
| Laravel LSP | GitHub release (`laravel/lsp`) |
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
| phpactor | Not installable from the IDE; install it yourself and put it on `PATH` |
@@ -77,12 +81,12 @@ See [Debugging](/en/guide/debugging).
## Framework support
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration.
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration. With Phoxite as the PHP server, routes, views, config, translations and Eloquent models get completion, navigation and rename from it instead.
- **WordPress** and similar platforms: add their stubs under **Additional stubs** and the platform folder under **Include paths**.
## Limitations
- No Blade or Twig template support; only `.php` files get PHP code insight.
- No Blade or Twig template support with Intelephense; only `.php` files get PHP code insight. Phoxite adds code insight in `.blade.php` files, without Blade highlighting.
- phpactor is not installed by the IDE.
- Run with Coverage is not available for PHPUnit.
- Debugging needs the Xdebug extension in your PHP; the IDE does not install it.
+2 -2
Переглянути файл
@@ -197,5 +197,5 @@ onIdeEvent("projectTrustChanged", (e) => {
1. 逻辑放在所属的 crate 里;在其边界把错误转成 `IdeError`;使用 IPC 坐标。
2. 如果涉及项目,把共享实现加到 `ide-host::ops::<domain>`;远程窗口需要的话,注册到远程 dispatcher。
3. 在 `src-tauri/src/commands/<domain>.rs` 添加 `#[tauri::command] #[specta::specta]` 适配函数,并加入 `collect_commands!`。
4. 如果它会执行任何东西,不要把它加进受限模式白名单(未受信任的项目里默认拒绝)。
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。
4. 决定它的信任级别:在 `restricted_command_allowed`(受限模式下也可运行)或 `projectless_command_allowed`(未打开项目时也可运行)中按完整名称列出它,或者不列出,即需要受信任的项目。没有名称前缀规则;会执行任何东西的命令不要列出。
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。它也会重写 `src-tauri/tests/commands.snap`;检查新增的那一行是否是你想要的信任级别和运行位置。
+3 -1
Переглянути файл
@@ -28,6 +28,8 @@ description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、
先用 `src/ui/` 里的基础组件,再考虑自己写:`Button`、`BarButton`、`Input`、`Checkbox`、`Select`、`Dialog`、`Popup`、`Menu`、`Tooltip`、`List`、`Tree`、`Tabs`、`Splitter`、`Scrollbar`、`Spinner`、`Kbd`,以及用于翻译文本的 `T`。它们已经处理好焦点、键盘导航、主题和标签翻译。工作台级别的部件(工具窗口、状态栏项、浮层)来自 [contribution](/zh/contribute/architecture/frontend),不要自己写布局。
工具栏图标操作使用 `IconButton`:悬停时整个点击区域使用 `--bg-toolbar-hover`,按下和选中状态使用对应的工具栏 token。保留图标的语义颜色和键盘焦点环。
## 无障碍
- 使用真正的 `<button>` 和 `<input>` 元素(或渲染它们的基础组件),不要用可点击的 `<div>`。
@@ -41,7 +43,7 @@ description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、
## WebKit 兼容性
在 macOS 和 Linux 上应用运行于 WebKit,最低支持 Safari 16,即 macOS 13 的引擎(macOS 11、12 上更新 Safari 不会更新其他应用使用的引擎)。`pnpm build` 会对产物运行 `scripts/check-webkit.ts`,`src/platform/webkitCompatibility.test.ts` 会检查应用中的正则。请避免:
在 macOS 和 Linux 上应用运行于 WebKit,最低支持 Safari 15.4,即 macOS 12 的引擎(应用的最低系统版本)。`pnpm build` 会对产物运行 `scripts/check-webkit.ts`,`src/platform/webkitCompatibility.test.ts` 会检查应用中的正则。请避免:
- 正则后行断言(`(?<=…)`、`(?<!…)`,需要 Safari 16.4)和正则 `v` 标志;
- import attributes;
+1 -1
Переглянути файл
@@ -28,7 +28,7 @@ description: "如何报告漏洞,以及贡献者需要维护的安全模型:
- 打开一个尚未做过决定的项目时,会弹出 **信任并打开项目?** 对话框,提供 **信任项目**、**以受限模式预览** 和 **不打开**。已有决定和受信任的位置在设置的 **项目信任** 页面(**安全** 分组)里管理,**撤销信任** 是一个 action。
- 信任是用户自己的状态(`crates/ide-host/src/trust.rs`)。**项目设置永远不能授予信任。**
- 拦截在后端而不是 UI:每个 IPC 命令执行前,都要在 Tauri 的 invoke handler(`src-tauri/src/lib.rs`)里经过 `Host::authorize_command`。未受信任的项目里,只有显式白名单(`restricted_command_allowed`)中的命令能运行:读写文件和文档、语法、搜索、导航、本地历史、拼写、分析、重构、设置等。
- 这份白名单是默认拒绝的:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。
- 这份白名单按完整名称列出,默认拒绝:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。`src-tauri/tests/commands.snap` 列出每个命令的信任级别,改动会出现在审查的 diff 里。
- 在命令层之下,项目受信任之前语言服务器不会启动(`LspManager` 的执行开关),git 以禁止执行的方式运行,也不使用项目里配置的 `git` 可执行文件。项目插件(`.openidea/plugins/`)只在受信任的项目中加载。
- 远程窗口中,桌面端在转发命令前会先确认远程项目是否受信任,`openidea-server` 对每个 `invoke` 还会再校验一次。
+6 -6
Переглянути файл
@@ -7,12 +7,12 @@ description: "在 fixtures 示例项目上,用真实语言服务器跑语言
由于需要安装这些工具,冒烟测试不包含在 `cargo nextest run` 或 `pnpm test` 中。CI 在 **Language smoke** 工作流里用固定版本运行它们。
| 套件 | 检查内容 | 语言 |
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php |
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、php |
| 套件 | 检查内容 | 语言 |
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php、zig |
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、zig、php |
## 语言冒烟测试
+4
Переглянути файл
@@ -56,6 +56,8 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
可用模型取决于已安装的 agent 和账号。如果已选模型被移除,需要先选择其他模型才能开始任务。刷新不会更改正在运行的任务。
提示词下方的版本来自 agent 的初始化响应;显示此页面或窗口重新获得焦点时会重新查询。更新 CLI 后,返回此页面即可刷新版本。这不会重启正在运行的任务;已运行的 agent 进程在退出前仍使用原来的版本。
</Step>
<Step title="发送">
任务会在编辑器标签页中打开并开始运行。
@@ -119,6 +121,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
## 添加自定义 agent
任何通过 stdio 使用 ACP 的 agent,都可以用一个 agent 文件添加:OpenIDEA 配置目录下的 `agents/<id>.toml`。
+2 -1
Переглянути файл
@@ -145,7 +145,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
**编辑数据**(`F4`)在编辑器标签页中打开表,服务器端分页(每页 100 到 5,000 行),并提供 `WHERE` 过滤和 `ORDER BY` 字段(都支持补全)。点击列标题排序,按住 `Shift` 点击可以追加排序列。
- 双击、`Enter` 或 `F2` 编辑单元格;`Shift+Enter` 打开更大的编辑框。粘贴制表符分隔的文本可以一次填写多个单元格。
- **添加行**、**删除行**、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
- **添加行**(`⌘N` / `Alt+Insert`)、**删除行**(Windows 和 Linux 上为 `Ctrl+Y`)、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
- **重新加载页面**(`⌘R` / `Ctrl+F5`)、**上一页** 和 **下一页**(`⌘⌥↑` / `⌘⌥↓`,`Ctrl+Alt+Up` / `Ctrl+Alt+Down`)。这些命令、各种复制命令和 **导出数据** 都是操作:可以在 **查找操作** 中找到,并在 **设置 › 按键映射** 中设置快捷键。
- **提交**(`⌘Enter` / `Ctrl+Enter`)在一个事务中提交所有待定更改;**还原**(`⌘⌥Z` / `Ctrl+Alt+Z`)放弃更改。
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
+2 -2
Переглянути файл
@@ -47,7 +47,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **将光标移至代码块开头** / **末尾** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
| **切换插入/改写** | `Insert` | `Insert` |
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行重新排序,默认没有快捷键。
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
输入时括号和引号会自动成对,选中文本后输入引号或括号会把选区包起来。这些以及其他输入辅助(智能 Home、用 Tab 跳出右括号、回车智能缩进、文档注释骨架、退格键如何处理缩进、粘贴时重新格式化)都在 **设置 › 编辑器 › 常规 › 智能键** 中。
@@ -117,7 +117,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **转到下一个拆分器** | `⌥⇥` | `Alt+Tab` |
| **转到上一个拆分器** | `⌥⇧⇥` | `Alt+Shift+Tab` |
**窗口 › 编辑器标签页** 中还有 **向下拆分**、**取消拆分**、**全部取消拆分**、**移动到另一组**、**在相对组中打开** 和 **更改拆分方向**。也可以把标签页拖到编辑区的某一侧边缘来拆分。
**窗口 › 编辑器标签页** 中还有 **向下拆分**、**取消拆分**、**全部取消拆分**、**移动到另一组**、**在相对组中打开** 和 **更改拆分方向**。也可以把标签页拖到编辑区的某一侧边缘来拆分。在 Project 视图中,**在右侧拆分中打开**(`⇧↵` / `Shift+Enter`,右键菜单中也有)会把选中的文件打开到右侧拆分中。
## 显示选项
+1 -1
Переглянути файл
@@ -9,7 +9,7 @@ description: "在 macOS、Windows 或 Linux 上下载并安装 OpenIDEA,以及
## macOS
需要 macOS 13 Ventura 或更高版本。
需要 macOS 12 Monterey 或更高版本。
| Mac | 文件 |
| ---------- | -------------------------------- |
+1
Переглянути файл
@@ -101,6 +101,7 @@ root-markers = ["angular.json", "node_modules/@angular/core"]
| `settings` | 表 | 用于响应服务器的 `workspace/configuration` 请求。不写时,从 `initialization-options` 中查找请求的配置节。 |
| `install-hint` | 字符串 | 服务器缺失且 IDE 无法安装时显示的提示。 |
| `fallback` | 布尔 | 作为前面服务器的备选,只在它们都未安装时使用。 |
| `replaces` | 字符串数组 | 排在它后面、因它而变得多余的服务器名称。它为文件提供服务时,这些服务器不会被使用。用于能覆盖附加服务器功能的备选服务器。 |
| `features` | 字符串数组 | 只把服务器用于这些功能;为空表示全部。可选值:`completion`、`inline-completion`、`hover`、`signature-help`、`definition`、`declaration`、`type-definition`、`implementation`、`references`、`document-highlight`、`document-symbol`、`workspace-symbol`、`code-action`、`code-lens`、`rename`、`formatting`、`inlay-hint`、`semantic-tokens`、`document-link`、`call-hierarchy`、`type-hierarchy`、`folding-range`、`selection-range`、`diagnostics`。 |
| `code-action-kinds` | 字符串数组 | 只保留这些种类的代码操作,按前缀匹配(`refactor` 包含 `refactor.extract`);为空则全部保留。 |
| `connect` | 字符串 | 通过 TCP 提供 LSP 的服务器地址 `host:port`,见 [TCP 服务器](#tcp-服务器)。 |
+1 -1
Переглянути файл
@@ -143,7 +143,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
+11 -7
Переглянути файл
@@ -7,11 +7,14 @@ OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老
## 语言服务器
| 服务器 | 启用条件 |
| -------------- | --------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
| 服务器 | 启用条件 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `phoxite` | 备选,自带 Laravel 和 Blade 支持:仅在以上两个服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
Phoxite 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由 Phoxite 自己处理。
Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别”),并索引你配置的 stub 和包含路径。
@@ -25,6 +28,7 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
| ------------------ | -------------------------------------------------- |
| Intelephense | npm(`intelephense`) |
| Laravel LSP | GitHub release(`laravel/lsp`) |
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
| phpactor | IDE 不负责安装,请自行安装并放到 `PATH` 上 |
@@ -77,12 +81,12 @@ PHPUnit 运行配置类型包含 **目标**、**配置文件**、**测试过滤
## 框架支持
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。以 Phoxite 作为 PHP 服务器时,路由、视图、配置、翻译和 Eloquent 模型的补全、跳转和重命名改由它提供。
- **WordPress** 等平台:在 **附加存根** 中加入对应 stub,在 **包含路径** 中加入平台代码目录。
## 已知限制
- 不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。
- 使用 Intelephense 时不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。Phoxite 为 `.blade.php` 文件提供代码智能,但没有 Blade 语法高亮。
- IDE 不会安装 phpactor。
- PHPUnit 不支持使用覆盖率运行。
- 调试需要 PHP 已安装 Xdebug 扩展,IDE 不负责安装。
+102 -9
Переглянути файл
@@ -372,20 +372,25 @@ test("keeps chat history readable and selections free of timestamps and status l
expect(narrow.reply).toBeLessThanOrEqual((narrow.width - narrow.padding) * 0.96);
});
test("fits conversation stream, composer, question card and user bubbles to window width when enabled", async ({
test("fits conversation stream, composer, question card and off-screen rows live from Settings without restarting", async ({
page,
}) => {
await page.setViewportSize({ width: 1800, height: 1000 });
await page.setViewportSize({ width: 1800, height: 900 });
await openReply(page, "Initial reply");
await page.evaluate(async (task) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
const filler = Array.from({ length: 8 }, (_, i) => ({
type: "agent" as const,
text: `Earlier paragraph ${i + 1}: ` + "wrapped words across the column ".repeat(35),
}));
store.useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "needsInput" as const }]]),
entries: new Map([
[
task.id,
[
...filler,
{
type: "user",
text: "Long prompt ".repeat(40),
@@ -419,11 +424,15 @@ test("fits conversation stream, composer, question card and user bubbles to wind
const stream = page.locator("[class*='_stream_']:visible");
await expect(page.getByRole("form", { name: "Choose layout" })).toBeVisible();
await expect(stream.locator("[data-measured]").first()).toBeAttached();
const measure = () =>
stream.evaluate((root) => {
const conversation = root.closest<HTMLElement>("[class*='_conversation_']")!;
const column = root.querySelector<HTMLElement>("[class*='_agentMessage_']")!.getBoundingClientRect();
const rows = [...root.querySelectorAll<HTMLElement>("[class*='_conversationRow_']")];
const column = [...root.querySelectorAll<HTMLElement>("[class*='_agentMessage_']")]
.at(-1)!
.getBoundingClientRect();
const bubble = root.querySelector<HTMLElement>("[class*='_user_']")!.getBoundingClientRect();
const composer = conversation.querySelector<HTMLElement>("[class*='_composerArea_']")!.getBoundingClientRect();
const question = conversation.querySelector<HTMLElement>("[class*='_questionCard_']")!.getBoundingClientRect();
@@ -436,6 +445,8 @@ test("fits conversation stream, composer, question card and user bubbles to wind
bubbleWidth: bubble.width,
composerWidth: composer.width,
questionWidth: question.width,
offscreenRowHeight: rows[0]!.getBoundingClientRect().height,
scrollHeight: root.scrollHeight,
};
});
@@ -446,14 +457,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
expect(Math.abs(capped.composerWidth - 924)).toBeLessThan(1);
expect(Math.abs(capped.questionWidth - 900)).toBeLessThan(1);
// Toggle on through Settings › Agents › Chat › Apply and verify live re-layout including off-screen rows.
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(projectPath);
const settings = useProject.getState().settings;
useProject.setState({
settings: { ...settings, agents: { ...settings?.agents, fitWindowWidth: true } } as never,
});
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(actionsPath);
await executeAction("file.settings", "agents.chat");
});
const dialog = page.getByRole("dialog", { name: "Settings" });
const toggle = dialog.getByRole("checkbox", { name: "Fit conversation to the window width" });
await expect(toggle).not.toBeChecked();
await toggle.click();
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(stream.locator("[data-measured]").first()).toBeAttached();
const fitted = await measure();
expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1);
@@ -461,6 +476,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1);
expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1);
expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1);
expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight);
expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight);
// Toggle back off and click OK: dialog closes and conversation returns to the 900px column live.
await toggle.click();
await dialog.getByRole("button", { name: "OK", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(stream.locator("[data-measured]").first()).toBeAttached();
const restored = await measure();
expect(Math.abs(restored.columnWidth - 900)).toBeLessThan(1);
expect(Math.abs(restored.offscreenRowHeight - capped.offscreenRowHeight)).toBeLessThan(1);
});
test("keeps hover actions reachable when the pointer leaves the message body", async ({ page, context }) => {
@@ -668,3 +695,69 @@ test("draws a diagram without reaching the hosts its configuration names", async
);
expect(asked).toEqual(["/after"]);
});
test("Find in Conversation skips user-select:none summaries and closed <details> until stepped into", async ({
page,
}) => {
await openReply(page, "Confirmed—PR is merged.");
await page.evaluate(async (task) => {
const path = "/src/features/agents/store.ts";
const store = await import(path);
store.useAgents.setState({
entries: new Map([
[
task.id,
[
{
type: "thought",
text: "**Confirming Active Watch Shell**\n\nCheck background shell before rebasing.",
},
{
type: "tool",
id: "t1",
title: "stop_bash",
kind: "other",
status: "completed",
locations: [],
output: "<command with id: 60 had already stopped>",
diffs: [],
},
{ type: "agent", text: "Confirmed—PR is merged." },
],
],
]),
});
store.openTaskInEditorLocation(task.id);
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
await runSummary.click();
await expect(stream.getByText("stop_bash")).toBeVisible();
await stream.focus();
await page.keyboard.press("Meta+f");
const findBox = page.getByLabel("Find in Conversation");
await findBox.fill("confirm");
// 2 matches total (1 inside collapsed thought body, 1 in visible reply); unselectable <summary> is excluded.
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
const initialHighlights = await page.evaluate(() => ({
find: [...(CSS.highlights.get("agent-find") ?? [])].map((r) => (r as Range).startContainer.textContent),
current: [...(CSS.highlights.get("agent-find-current") ?? [])].map((r) => (r as Range).startContainer.textContent),
}));
expect(initialHighlights.find).toEqual(["Confirmed—PR is merged."]);
expect(initialHighlights.current).toEqual([]);
// Stepping to match 2/2 opens the collapsed thought <details> and highlights it.
await findBox.press("Enter");
await expect(page.locator("[class*='_findCount_']")).toHaveText("2/2");
await findBox.press("Enter");
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
const expandedHighlights = await page.evaluate(() => ({
thoughtOpen: document.querySelector<HTMLDetailsElement>("details[class*='_thought_']")?.open,
findCount: CSS.highlights.get("agent-find")?.size ?? 0,
currentCount: CSS.highlights.get("agent-find-current")?.size ?? 0,
}));
expect(expandedHighlights).toEqual({ thoughtOpen: true, findCount: 2, currentCount: 1 });
});
+2 -2
Переглянути файл
@@ -83,8 +83,8 @@ for (const placement of ["editor", "toolWindow"] as const) {
},
{ id: task.id, placement },
);
// The working indicator ends the conversation, after its rows.
await expect(stream.getByRole("status").getByText("Working…", { exact: true })).toBeVisible();
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { expect, test } from "./fixtures";
test.beforeEach(async ({ workbench: page }) => {
await page.evaluate(async () => {
// Load the IPC module in Vite's browser realm, not Playwright's Node process.
const ipcPath = "/src/platform/ipc.ts";
const { commands } = await import(ipcPath);
const provider = {
id: "omp",
name: "OMP",
command: "omp acp",
program: "omp",
args: ["acp"],
defaultProgram: null,
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "custom" },
config: [],
thoughtLevels: {},
};
let installed = "18.20.0";
let cached = installed;
window.addEventListener("test:agent-upgraded", () => {
installed = "18.20.2";
});
commands.agentProviders = async () => ({ status: "ok", data: [provider] });
commands.agentProbe = async (id: string, refresh: boolean) => {
if (refresh) cached = installed;
return {
status: "ok",
data: { provider: id, name: "omp", version: cached, protocol: "ACP v1", error: null },
};
};
commands.agentRefreshModels = async () => ({
status: "ok",
data: {
provider: "omp",
config: [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
},
});
});
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
});
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
const message = page.getByRole("textbox", { name: "Message", exact: true });
await message.focus();
await page.keyboard.insertText("Keep this unsent draft");
await page.evaluate(() => {
window.dispatchEvent(new Event("test:agent-upgraded"));
window.dispatchEvent(new Event("focus"));
});
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
await expect(message).toHaveText("Keep this unsent draft");
});
test("refreshes an upgraded agent's version when New Task is reopened", async ({ workbench: page }) => {
await page.getByRole("button", { name: "Close Tab", exact: true }).click();
await page.evaluate(() => window.dispatchEvent(new Event("test:agent-upgraded")));
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
});
+147
Переглянути файл
@@ -98,6 +98,153 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
const editor = await openSample(page);
await page.evaluate(async () => {
// Long enough for the pane to reach its max-width: a short doc leaves it at
// `width: max-content`, so the placement assertions would never exercise the room calculation.
const longDocs =
"Computes the order total including tax, discounts and shipping, rounded to the currency's scale. " +
"The result is cached until the order changes, so callers should not hold on to it across edits; " +
"ask for a fresh value after every update.";
const item = (label: string, detail: string) => ({
label,
labelDetail: "()",
detail,
kind: "method",
documentation: { kind: "markdown", value: `Docs for **${label}**. ${longDocs}` },
sortText: null,
filterText: null,
preselect: false,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_completion = () => ({
isIncomplete: false,
items: [item("total", "BigDecimal"), item("toDto", "OrderDto")],
});
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = structuredClone(useProject.getState().settings ?? {});
const editor = settings.editor ?? {};
settings.editor = {
...editor,
completion: { ...editor.completion, showDocumentation: true, documentationDelay: 0 },
};
useProject.setState({ settings });
});
const popup = page.locator(".cm-tooltip-autocomplete");
const openLookup = async () => {
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.type("order.");
await page.keyboard.press("Control+Space");
await expect(popup.getByText("total", { exact: true })).toBeVisible();
await expect(page.locator(".cm-completionInfo")).toContainText("Docs for");
};
const geometry = () =>
page.evaluate(() => {
const info = document.querySelector(".cm-completionInfo") as HTMLElement;
const list = (document.querySelector(".cm-tooltip-autocomplete") as HTMLElement).getBoundingClientRect();
const rect = info.getBoundingClientRect();
const overlapX = Math.max(0, Math.min(rect.right, list.right) - Math.max(rect.left, list.left));
const overlapY = Math.max(0, Math.min(rect.bottom, list.bottom) - Math.max(rect.top, list.top));
const side = info.classList.contains("cm-completionInfo-left")
? "left"
: info.classList.contains("cm-completionInfo-right")
? "right"
: "none";
return {
overlap: overlapX * overlapY,
visible: !!document.elementFromPoint(rect.left + 4, rect.top + 4)?.closest(".cm-completionInfo"),
inside: rect.left >= 0 && rect.right <= document.documentElement.clientWidth,
side,
};
});
await page.setViewportSize({ width: 760, height: 900 });
await openLookup();
await page.screenshot({ path: info.outputPath("completion-documentation.png"), animations: "disabled" });
const narrow = await geometry();
expect(narrow.overlap).toBe(0);
expect(narrow.visible).toBe(true);
expect(narrow.inside).toBe(true);
expect(narrow.side).toBe("left");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
await page.setViewportSize({ width: 1400, height: 900 });
await openLookup();
const wide = await geometry();
expect(wide.overlap).toBe(0);
expect(wide.visible).toBe(true);
expect(wide.inside).toBe(true);
expect(wide.side).toBe("right");
});
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(() => {
const item = (label: string) => ({
label,
labelDetail: "()",
detail: "Unit",
kind: "method",
documentation: { kind: "markdown", value: `Docs for **${label}**.` },
sortText: null,
filterText: null,
preselect: false,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_completion = () => ({
isIncomplete: false,
items: [item("service"), item("serviceName"), item("setUp")],
});
window.__ipc.handlers.lsp_hover = () => ({
contents: { kind: "markdown", value: "Docs for **service**." },
range: null,
});
});
const geometry = await editor.locator(".cm-content").evaluate(async (content) => {
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const view = EditorView.findFromDOM(content as HTMLElement)!;
const find = view.state.doc.toString().indexOf("find");
if (find < 0 || !view.coordsAtPos(find)) throw new Error('the fixture has no visible "find"');
const word = view.coordsAtPos(find)!;
view.dispatch({ selection: { anchor: find + 5 } });
view.focus();
return { wordX: word.left + 2, wordY: (word.top + word.bottom) / 2 };
});
await page.mouse.move(geometry.wordX, geometry.wordY);
const tooltip = page.locator(".cm-tooltip-hover");
await expect(tooltip).toBeVisible();
await page.keyboard.type("se");
const popup = page.locator(".cm-tooltip-autocomplete");
await expect(popup.getByText("service", { exact: true })).toBeVisible();
await expect(tooltip).toHaveCount(0);
});
for (const key of ["Enter", "Tab"]) {
for (const prefix of ["", "v"]) {
test(`${key} leaves the caret after a field snippet at root.${prefix}`, async ({ workbench: page }, info) => {
+64 -2
Переглянути файл
@@ -174,12 +174,36 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
});
test("Markdown preview highlights ⌘F matches and selected word occurrences", async ({ workbench: page }) => {
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 96" width="320" height="96"><!-- svg-source:excalidraw --><rect width="320" height="96"/></svg>';
const url = `data:image/svg+xml;base64,${btoa(svg)}`;
const routeModule = "/src/platform/tauriCore.ts";
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(url) : null));
});
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("# Order Service\n\nManage **Order** items and `Order` status.\n");
await page.keyboard.insertText(
[
"# Order Service",
"",
"Manage **Order** items and `Order` status.",
"",
"```mermaid",
"flowchart LR",
" A --> B",
"```",
"",
"![Diagram](./arch.excalidraw.svg)",
].join("\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(preview).toContainText("Manage Order items");
@@ -209,6 +233,44 @@ test("Markdown preview highlights ⌘F matches and selected word occurrences", a
})),
)
.toEqual({ current: ["Order"], other: ["Order", "Order"] });
const mermaidSvg = preview.locator(".mermaid-output svg");
const excalidrawImg = preview.locator('img[alt="Diagram"]');
await expect(mermaidSvg).toBeVisible();
await expect(excalidrawImg).toHaveAttribute("src", /^data:image\/svg\+xml/);
const widths = async () => ({
mermaid: (await mermaidSvg.boundingBox())!.width,
excalidraw: (await excalidrawImg.boundingBox())!.width,
});
const base = await widths();
expect(base.mermaid).toBeGreaterThan(50);
expect(base.excalidraw).toBeCloseTo(320, 0);
const runAction = (id: string, times = 1) =>
page.evaluate(
async ({ id, times }) => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
for (let i = 0; i < times; i++) await executeAction(id);
},
{ id, times },
);
await runAction("editor.increaseFontSize", 4);
const zoomedIn = await widths();
expect(zoomedIn.mermaid / base.mermaid).toBeCloseTo(17 / 13, 2);
expect(zoomedIn.excalidraw / base.excalidraw).toBeCloseTo(17 / 13, 2);
await runAction("editor.decreaseFontSize", 6);
const zoomedOut = await widths();
expect(zoomedOut.mermaid / base.mermaid).toBeCloseTo(11 / 13, 2);
expect(zoomedOut.excalidraw / base.excalidraw).toBeCloseTo(11 / 13, 2);
await runAction("editor.resetFontSize");
const reset = await widths();
expect(reset.mermaid).toBeCloseTo(base.mermaid, 1);
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
+91
Переглянути файл
@@ -0,0 +1,91 @@
import { expect, openFromTree, test } from "./fixtures";
for (const theme of ["light", "dark"] as const) {
test(`${theme}: toolbar icon buttons provide hover feedback without changing their layout or icons`, async ({
workbench: page,
}) => {
const gear = page.getByRole("button", { name: "IDE and Project Settings", exact: true });
await gear.click();
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
await page
.getByRole("menuitemcheckbox", { name: `Islands ${theme === "light" ? "Light" : "Dark"}`, exact: true })
.click();
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
const toolbar = page.locator("header").first();
const disabledRun = toolbar.getByRole("button", { name: "Run", exact: true });
await expect(disabledRun).toBeDisabled();
await disabledRun.hover();
await expect(disabledRun).toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
await openFromTree(page, "App.tsx");
await page.locator("[data-run-chooser]").click();
await page.getByRole("option", { name: "Current File", exact: true }).click();
const project = page.getByRole("region", { name: "Project", exact: true });
const buttons = [
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
project.getByRole("button", { name, exact: true }),
),
...[
"Run Current File",
"Debug Current File",
"More Actions",
"Search Everywhere",
"IDE and Project Settings",
].map((name) => toolbar.getByRole("button", { name, exact: true })),
];
for (const button of buttons) {
await page.mouse.move(700, 500);
const bounds = await button.boundingBox();
const iconColors = await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node);
return { fill: style.fill, stroke: style.stroke };
}),
);
await expect(button).toBeEnabled();
// Hover inside the hit target but outside its centred icon.
await button.hover({ position: { x: bounds!.width / 2, y: 1 } });
await expect(button).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
expect(await button.boundingBox()).toEqual(bounds);
if (/^(Run|Debug) Current File$/.test((await button.getAttribute("aria-label")) ?? "")) {
expect(
await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node);
return { fill: style.fill, stroke: style.stroke };
}),
),
).toEqual(iconColors);
}
await button.focus();
await page.keyboard.press("Shift+Tab");
await page.keyboard.press("Tab");
await expect(button).toBeFocused();
await expect(button).toHaveCSS("outline-style", "solid");
await expect(button).toHaveCSS("outline-width", "2px");
}
const expand = project.getByRole("button", { name: "Expand All", exact: true });
await expand.hover();
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
await page.mouse.down();
await expect(expand).not.toHaveCSS("background-color", hover);
await page.mouse.up();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
await project.getByRole("button", { name: "Options", exact: true }).click();
await expect(page.getByRole("menu", { name: "Project options", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "More Actions", exact: true }).click();
await expect(page.getByRole("menuitem", { name: /^Edit Configurations…/ })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "Search Everywhere", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Search Everywhere", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await project.getByRole("button", { name: "Hide", exact: true }).click();
await expect(project).toBeHidden();
});
}
+7
Переглянути файл
@@ -28,4 +28,11 @@ pub fn build(b: *std.Build) void {
const tests = b.addTest(.{ .root_module = tally });
const test_step = b.step("test", "Run the tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
const failing_tests = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/failing.zig"),
.target = target,
}) });
const test_failing_step = b.step("test-failing", "Run the tests that fail on purpose");
test_failing_step.dependOn(&b.addRunArtifact(failing_tests).step);
}
+5
Переглянути файл
@@ -0,0 +1,5 @@
//! Fails on purpose: the `test-failing` step, for checking that a run's failure shows up
//! in the test tree and Rerun Failed Tests re-runs it alone.
test "intentionally fails" {
return error.OpenideaFail;
}
+2 -1
Переглянути файл
@@ -3,7 +3,8 @@ const tally = @import("tally");
pub fn main() !void {
const prices = [_]u32{ 4999, 2499, 5999 };
const sum = tally.total(&prices); // Set a breakpoint here
const sum = tally.total(&prices);
var buf: [16]u8 = undefined;
// Set a breakpoint here (QA: debugger) and inspect `sum`.
std.debug.print("Total: {s}\n", .{try tally.format(&buf, sum)});
}
+11
Переглянути файл
@@ -26,6 +26,17 @@ args = ["language-server"]
root-markers = ["composer.json", ".phpactor.json"]
install-hint = "Install phpactor (https://phpactor.readthedocs.io/en/master/usage/standalone.html)"
# Alternative with its own Laravel and Blade support. https://github.com/samehelhawary/phoxite
[[language-servers]]
name = "phoxite"
fallback = true
command = "phoxite-lsp"
args = []
root-markers = ["composer.json", "artisan", "index.php"]
# It answers the Laravel strings itself.
replaces = ["laravel-lsp"]
install-hint = "Install phoxite-lsp from https://github.com/samehelhawary/phoxite/releases and put it on PATH"
# Laravel projects only: hover, definition and completion inside
# config('…'), route('…') and view('…'). Last: Intelephense keeps PHP hover,
# rename and symbols. https://github.com/laravel/lsp
+6 -12
Переглянути файл
@@ -13,7 +13,7 @@
details: "启动错误详情",
timeout: "启动未在 60 秒内完成。",
outdatedMac:
"这台 Mac 的系统网页引擎过旧:OpenIDEA 的界面运行在 macOS 自带的 WebKit 引擎上,需要 macOS 13 Ventura 或更高版本。在 macOS 11、12 上更新 Safari 不会更新其他应用使用的引擎,需要升级 macOS。",
"这台 Mac 的系统网页引擎过旧:OpenIDEA 的界面运行在 macOS 自带的 WebKit 引擎上,需要 macOS 12 Monterey 或更高版本(引擎为 Safari 15.4 或更新)。更旧的系统缺少应用所需的引擎,需要升级 macOS。",
outdated:
"系统的 WebKitGTK 版本过旧:OpenIDEA 需要较新的 WebKitGTK(webkit2gtk-4.1)。请通过系统的包管理器更新后重新打开 OpenIDEA。",
}
@@ -27,20 +27,14 @@
details: "Startup error details",
timeout: "Startup did not finish within 60 seconds.",
outdatedMac:
"The system web engine on this Mac is too old: OpenIDEA's interface runs on macOS's built-in WebKit and needs macOS 13 Ventura or later. On macOS 11 and 12 a Safari update doesn't update the engine other apps use, so macOS itself needs upgrading.",
"The system web engine on this Mac is too old: OpenIDEA's interface runs on macOS's built-in WebKit and needs macOS 12 Monterey or later (Safari 15.4 or newer). Older macOS releases lack the engine the app needs, so macOS itself needs upgrading.",
outdated:
"The system's WebKitGTK is too old: OpenIDEA needs a recent WebKitGTK (webkit2gtk-4.1). Update it with your package manager, then open OpenIDEA again.",
};
// The bundle targets Safari 16 (vite.config.ts); an older system web engine can't even
// parse it. Container queries came with Safari 16, and WebKit's user agent doesn't name
// its version. Unknown (no CSS.supports) counts as current.
const outdated = () => {
try {
return typeof window.CSS?.supports === "function" && !window.CSS.supports("container-type", "inline-size");
} catch {
return false;
}
};
// The bundle targets Safari 15.4 (vite.config.ts), so an older system web engine can't
// even parse it. structuredClone came with Safari 15.4, and WebKit's user agent doesn't
// name its version.
const outdated = () => typeof structuredClone !== "function";
let failed = false;
let ready = false;
const describe = (reason) => {
+5 -1
Переглянути файл
@@ -10,12 +10,16 @@ it.each([
"Object.groupBy(items, key)",
"Array.fromAsync(items)",
"text.toWellFormed()",
"input.showPicker()",
'Intl.supportedValuesOf("collator")',
"items.toSorted(compare)",
"path.toReversed()",
'new RegExp("[a-z]", "v")',
'RegExp("(?<=a)b")',
"/[a-z]/v",
"/(?<!a)b/",
'import data from "./data.json" with { type: "json" }',
])("rejects %s in the Safari 16 startup graph", (source) => {
])("rejects %s in the Safari 15.4 startup graph", (source) => {
expect(checkSource(source, true).length).toBeGreaterThan(0);
});
+13 -4
Переглянути файл
@@ -3,7 +3,7 @@ import { dirname, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import ts from "typescript";
// Safari 16 is macOS 13's system engine (the app's minimum). Keep this floor in sync with vite.config.ts.
// Safari 15.4 is the bundle's floor, macOS 12's engine (the app's minimum). Keep this floor in sync with vite.config.ts.
// Syntax lowering does not replace newer runtime APIs in dependencies.
const newerStatics = new Set([
"Promise.withResolvers",
@@ -15,7 +15,16 @@ const newerStatics = new Set([
"Uint8Array.fromBase64",
"Uint8Array.fromHex",
]);
const newerMethods = new Set(["isWellFormed", "toWellFormed"]);
const newerMethods = new Set([
"isWellFormed",
"toWellFormed",
// Safari 16 / 16.4 APIs above the floor.
"showPicker",
"supportedValuesOf",
"toSorted",
"toReversed",
"toSpliced",
]);
export function checkSource(source: string, startup: boolean): string[] {
const tree = ts.createSourceFile("bundle.js", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
@@ -84,6 +93,6 @@ export function checkBuild(dir: string): string[] {
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
const errors = checkBuild(resolve("dist"));
if (errors.length) throw new Error(`Safari 16 compatibility check failed:\n${errors.join("\n")}`);
console.log("Safari 16 startup API and bundle syntax checks passed");
if (errors.length) throw new Error(`Safari 15.4 compatibility check failed:\n${errors.join("\n")}`);
console.log("Safari 15.4 startup API and bundle syntax checks passed");
}
+11
Переглянути файл
@@ -164,6 +164,17 @@ const CASES: Record<string, Case> = {
variable: "line",
evaluate: ["print line", / = /],
},
// Zig ships no debugger of its own: CodeLLDB debugs the binary `zig build` produces.
// The breakpoint lands on the last use of `sum`: zig's debuginfo gives a const local a
// location only within its live range, so `prices` (used earlier) is not in the frame.
zig: {
fixture: "zig-app",
tools: ["codelldb"],
adapter: "codelldb",
file: "src/main.zig",
variable: "sum",
evaluate: ["sum", /13497/],
},
php: {
fixture: "php-app",
setup: (root) =>
+13
Переглянути файл
@@ -135,6 +135,19 @@ const CASES: Record<string, Case> = {
file: "ThresholdCustomsTest.php",
},
},
// The failing run uses the fixture's dedicated `test-failing` step (`zig build` forwards
// no args to the test binary, so a failing test can't be switched on through the config).
zig: {
fixture: "zig-app",
run: { config: "zig:run", prints: "Total: $134.97" },
tests: {
config: "zig:test-failing",
failing: (c) => c,
passed: 0,
failed: "intentionally fails",
file: "src/failing.zig",
},
},
};
let server: Server | null = null;
+17 -9
Переглянути файл
@@ -76,15 +76,26 @@ pub async fn clipboard_set_file_list(app: AppHandle, paths: Vec<PathBuf>) -> Ide
with_clipboard(app, move || Ok(ide_clipboard::set_files(&paths))).await
}
/// The clipboard's image as a PNG data URL, for a paste whose event carried no
/// files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
/// None when the clipboard holds no image, and always on other platforms.
/// Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
/// enabled state.
#[tauri::command]
#[specta::specta]
pub fn clipboard_has_image() -> bool {
// Synchronous Tauri commands run on the main thread, as macOS and GTK require.
ide_clipboard::has_image()
}
/// The clipboard's image as a PNG data URL: for a paste whose event carried no files
/// (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
/// the project view's Paste, which has no paste event. None when it holds no image.
#[tauri::command]
#[specta::specta]
pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
use base64::Engine;
let data_url =
|bytes: Vec<u8>| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
#[cfg(target_os = "linux")]
{
use base64::Engine;
let (tx, rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread(move || {
let sender = std::cell::Cell::new(Some(tx));
@@ -98,14 +109,11 @@ pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
.map_err(|error| {
ide_core::IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}"))
})?;
let png = rx.await.ok().flatten();
Ok(png
.map(|bytes| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))))
Ok(rx.await.ok().flatten().map(data_url))
}
#[cfg(not(target_os = "linux"))]
{
let _ = app;
Ok(None)
Ok(with_clipboard(app, || Ok(ide_clipboard::png())).await?.map(data_url))
}
}
+2
Переглянути файл
@@ -195,6 +195,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
clipboard::clipboard_text,
clipboard::clipboard_file_list,
clipboard::clipboard_has_files,
clipboard::clipboard_has_image,
clipboard::clipboard_image,
clipboard::clipboard_set_file_list,
fonts::system_font_families,
@@ -357,6 +358,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_conflict_versions,
vcs::vcs_diff_text,
vcs::vcs_diff_hunks,
vcs::diff_external_tool,
vcs::vcs_stage_hunks,
vcs::vcs_clone,
vcs::vcs_init,
+15
Переглянути файл
@@ -518,6 +518,21 @@ pub async fn vcs_diff_hunks(app: AppHandle, old_text: String, new_text: String)
.expect("line diff panicked")
}
/// Show Diff in External Tool: starts the tool set in the global settings (never a
/// project's, which a cloned repository could carry) on the two sides, on this machine
/// (a remote window passes the sides as text).
#[tauri::command]
#[specta::specta]
pub async fn diff_external_tool(
state: State<'_, AppState>,
left: ExternalDiffSide,
right: ExternalDiffSide,
title: String,
) -> IdeResult<()> {
let settings = state.global_settings.effective().external_diff;
state.host.blocking(move || launch_external_diff(&settings, &left, &right, &title)).await
}
/// Stages only the selected hunks of a file's working-tree changes.
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
#[tauri::command]
Loaded 100 of 451 files, more files were not shown because too many files have changed in this diff. Show more