Compare commits

..
Author SHA1 Message Date
l0ng-ai 59b71295b2 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH 2026-11-23 22:27:04 +08:00
Bert Verhelstandbertyhell 5eff75cab5 fix(remote): keep scratches and generated requests on the host that writes them (#5439)
In a remote (SSH/WSL) window, Generate Request in HTTP Client failed with Permission denied: the scratches folder was resolved on the desktop and its path sent to the remote host. Scratches and generated HTTP requests now live in the data directory of the host that writes them (created on demand, rechecked on later calls), and remote IPC routing is installed before session listeners run.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:23 +08:00
l0ng-ai aec1382e79 fix(agents): keep the prompt box free of scrollbars until it reaches its height limit (#5472)
After one exchange, a new session's empty prompt box showed a horizontal scrollbar and a vertical thumb (visible with always-on scrollbars): the CodeMirror scroller kept a fixed height slightly taller than its content and allowed horizontal overflow. The scroller now sizes to its wrapped text, never scrolls horizontally, and scrolls vertically only past its 280 px limit.
2026-11-23 22:02:22 +08:00
l0ng-ai 999d84b189 fix(run): resolve Java launches in attached projects (#5471)
Running or debugging a Java main class of a project attached to the window failed to compile (its Maven dependencies were missing): launch preparation used the primary project's root, build model, settings and cache. Run/Debug/test launches now resolve the owning attached project (innermost root containing the module) and use its build model, Maven reactor, settings, classpath and launch-snapshot cache; older saved configurations resolve the same way.
2026-11-23 22:01:15 +08:00
jiejie1133 9fda9b92c2 fix(editor): edit a repeated template variable from one caret (#5443)
After expanding Java `fori`, the three occurrences of `i` were all editing selections, so arrow keys moved three carets. The shared snippet engine now selects only the first occurrence of each variable and mirrors edits to the others, for every live template and language and for LSP snippets with repeated placeholders; the Java-specific handling is gone.

Co-authored-by: jiejie1133 <[email protected]>
2026-11-23 21:41:18 +08:00
fun90andfun90 261eb03009 fix(markdown): open preview links to another file at the linked heading (#5422)
Clicking a link to a heading in another file (e.g. [§5.2](b.md#52-状态机)) in the Markdown preview opened the file at the top. The destination now opens at the heading, in Preview Only and split mode, also when the file wasn't open yet (the preview scrolls once it has rendered). Markdown file-type aliases are honoured and a later link click wins over a slower earlier one.

Co-authored-by: fun90 <[email protected]>
2026-11-23 21:21:17 +08:00
l0ng-ai db8b553364 fix(editor): merge inheritance gutter markers by line and kind (#5470)
Lombok-generated members (@SuperBuilder, @Data) put one override/implemented marker per generated method on the annotation line, filling the gutter. Markers of the same kind on a line now collapse into one icon with a combined tooltip; clicking it opens the target chooser (a single target still opens directly). Applies to all four inheritance marker kinds.
2026-11-23 21:19:14 +08:00
langxpandkradme 2494b2efdf fix(libraries): reveal classes from unlisted classifier jars (#5414)
Select Opened File could not reveal a class opened from a dependency JAR that used a Maven classifier and was absent from External Libraries. The document knew its exact archive, but the Project view only searches registered archive roots.
External Libraries now adds the exact archive referenced by the active library document, labels it with its Maven coordinate when available, and removes the temporary entry once the build model lists the same archive.

Co-authored-by: kradme <[email protected]>
2026-11-23 21:13:35 +08:00
Muuandmuutot d78ce7ec66 fix(editor): offer contributed Copy Path links in the tab and library menus (#5400)
Copy Path/Reference… built a different submenu per entry point: the project view and the editor caret chooser list the contributed copy items (features/vcs: Path From Repository Root, GitHub Link), while the editor tab menu and the External Libraries menu hand-wrote theirs and silently dropped every contribution. Both hand-written submenus now append the same `copyPath` menu group, so all four entry points agree — and future contributions appear everywhere at once.

Co-authored-by: muutot <[email protected]>
2026-11-23 21:10:34 +08:00
Bert Verhelstandbertyhell 9df9499bf5 fix(project-view): open files on single click when preview tabs are enabled (#5419)
With **Settings › Editor › General › Editor Tabs › Enable preview tab** on, a single click on a file in the Project view now opens it in the preview tab, and the next single click reuses that tab. Before, the click did nothing. The cause was two switches that weren't connected. The Project view checked its own "Enable Preview Tab" view option, which was off by default and only reachable from the view's ⋮ menu. The Settings checkbox was a separate setting, `editor.tabs.previewTab`, which was only read when a preview tab was created.
IntelliJ IDEA documents these as two ways into one setting, so this PR makes them one. The Project view reads `editor.tabs.previewTab` for single click and for Autoscroll to Source. Its ⋮ › Behavior › Enable Preview Tab item and the `project.option.previewTab` action (the id is unchanged) now write that setting. The old view option is removed from the saved Project view options when they load.
What existing users will see:
- Defaults (Settings on, view option off): single click now opens a preview tab. This is the fix. The editor setting already defaulted to on, so users who never changed anything get single-click preview after this change.
- Both on: no change.
- Both off: no change.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 21:10:08 +08:00
aconeshanaandaconeshana d4b5581441 fix(ui): paste into a tree's speed search, not the view's Paste (#5401)
In the Project view, copy a keyword, press ⌘F, then ⌘V: the app reported "No files on the clipboard" and the search box stayed empty, instead of pasting the keyword the user had copied to search with.
A tree's speed search is not a text field — its query is built from printable keydowns. So `⌘V` never reached the query: the keymap dispatcher ran `project.paste` on the selected folder, and the paste event that followed bubbled to the Project view's clipboard fallback, which runs the same action again.
The shared `Tree` now claims `⌘V` while a search is active (as it already claims `⌫` since #3226) and takes the clipboard text into its query: pasted text is flattened onto one line and the search jumps to the nearest match. With the search closed, or with a clipboard that holds no text, the view's Paste runs exactly as before.
Every tree with a speed search gets this — the Project view, the Database view, the Services tree and the GitHub changes tree all render `src/ui/Tree.tsx`.

Co-authored-by: aconeshana <[email protected]>
2026-11-23 21:00:08 +08:00
Bert Verhelstandbertyhell d96060f08b fix(ui): scroll text fields while drag-selecting past their edges (#5429)
Drag-selecting in a long Find in Files query (or any text field) and moving the pointer past the field's left or right edge didn't scroll the text, so you couldn't select past what's visible. IntelliJ IDEA does scroll. WebKitGTK extends the selection in this case but never scrolls the field to follow it. Arrow keys do scroll. Now, while a drag that started in the field is past one of its edges, the field moves the selection end and the scroll position itself, faster the further out the pointer is. Once the pointer is back inside, WebKit's own selection takes over again. Both `Input` and `SearchField` get this.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:53 +08:00
Bert Verhelstandbertyhell 507258daec fix(editor): stop clipping Code Vision hints that are taller than 16px (#5418)
The Code Vision row above a declaration (usage count, author) cut off the top or bottom of its text, most visibly for Chinese labels like "10 个用法" / "无用法". The row was a fixed `height: 16px` with `overflow: hidden`, while its text is the editor font size minus 1px. At larger editor fonts, or with CJK fallback fonts that ink below the Latin metrics (Microsoft YaHei, Noto Sans CJK), the glyphs didn't fit.
The row now has `min-height: 16px`, and its items use `line-height: normal`, so the row grows to the ascent and descent of the fonts actually used. At the default font a Latin-only row is still exactly 16px. The line-end hint (Code Vision kinds set to "right") has the same 1em box with `overflow: hidden`. It keeps its size and position but now clips only horizontally.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:37 +08:00
Mr0Bread dae402b966 perf(vcs): make a git history page cost independent of the commit count (#5446)
A Git Log page costs a fixed ~15 ms in a repository with 248 refs (the 100k-commit fixture), even for a one-row page. Every page listed and peeled all refs twice (once for the decorations, once more for the view cache key via `log_refs`), at ~25 µs per ref. The decorations are now cached until `HEAD`, `packed-refs` or a directory under `refs/` changes, and the cache key uses a change counter instead of the full ref map. A warm page no longer reads any ref.
The cost scales with the number of refs, not commits: the audit's 10k/100k fixtures have 50/248 refs, which is why it looked proportional to the commit count. A repository with thousands of remote branches pays correspondingly more.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:43:54 +08:00
Bert Verhelstandbertyhell 39e803b8f9 fix(vcs): keep a filtered log narrow while older matches are still unloaded (#5421)
With a User filter on a merge-heavy history, the first page of the Git Log fanned the top merge out into dozens of dashed lanes, and the graph column pushed the commit subjects to the right. It went back to one line only after every match was loaded. The cause: `pruneFilteredEdges` (the #2670 fix) only judges a filtered connection when its target is on the loaded page. With the first 300 rows of the issue's repository, the merge kept 43 connections, 42 of them to rows that weren't loaded yet.
Now, while another kept connection of the commit already leads below the page, a filtered connection to an unloaded target waits until that target loads, and is then judged exactly like before. If no kept connection leads below the page, one filtered connection stays, so a row never looks like the end of its history. This is a heuristic: a connection that turns out to be needed (two unrelated side branches, both below the page) appears once its target loads. The sibling-branch test pins that behaviour. An exact answer on the first page would need the backend projection (`Visibility::parents`) to drop ancestors that another projected parent already reaches. This PR doesn't touch Rust; that could be a follow-up.
Go to Parent now pages until every unpruned connection of the commit is loaded, as it did before, so a merge still offers all its parents.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:43:44 +08:00
TWINKLE d6b56856d2 Fix/terminal ime caret (#5458)
Closes #4112 (its remaining half: #4347 stopped the terminal sliding sideways while composing, the
candidate window still opened at the far right of pi's input box).
xterm anchors the IME candidate window on its hidden helper textarea, and keeps that textarea on the
terminal cursor — on every render, on `compositionstart` and again on each `compositionupdate`. A
program that paints its own caret leaves the terminal cursor elsewhere: pi asks for a column past the
right edge of its input box (`ESC[21;411H` in a 206-column terminal, which xterm clamps) while it

Co-authored-by: H-TWINKLE <[email protected]>
2026-11-23 20:40:44 +08:00
Yann 8a84e8f473 fix(agents): preserve and display tool result images (#5447)
Claude Code can return an image from a tool call without including a Markdown image in its final reply. OpenIDEA discarded that image while normalizing and saving the tool result, so the conversation showed no preview.
Preserve inline tool images separately from truncated text and show them below the folded work summary. The existing image viewer opens the full preview; expanding the work does not duplicate it, and old conversations without an image field still load.

Co-authored-by: YannABC <[email protected]>
2026-11-23 20:40:35 +08:00
Bert Verhelstandbertyhell f31aa29f3e fix(agents): update the context meter when Claude Code compacts the conversation (#5441)
After a compaction the context meter kept the pre-compaction usage until the next request. compact_boundary now sets the usage to post_tokens; without it the driver asks Claude Code (get_context_usage).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:03:15 +08:00
faysouandfaysou 639e4b3df9 fix(editor): keep completion types and usage captions visible in narrow popups (#5387)
The completion popup can clip a return type after the editor font loads. Its return-type column now uses the row’s existing gap. In Show Usages, same-named files can be hard to distinguish because the filename and directory share too little space. The filename column now gets 38% of a narrow row, with the existing 176 px cap.
| Popup | Before | After |
| ----- | ------ | ----- |
| Completion | ![Return type ends in an ellipsis](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-before.png) | ![RegionalSettlementResult fits](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-after.png) |
| Show Usages | ![The checkout directory is truncated](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-before.png) | ![Both billing and checkout are visible](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-after.png) |

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:54 +08:00
Bert Verhelstandbertyhell 01b9908898 fix(search): offer every project file type in the file mask menu (#5416)
The **File mask** menu in Find in Files now lists every language file type present in the project, most common first, after the recently used masks. Before, `refreshProjectMasks` kept only the 5 most common types, so in a project with six (rs, md, json, toml, yml, properties) the least common one, `*.properties`, could not be picked. The menu already scrolls and stays inside the window, so a long list stays usable.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:43 +08:00
Bert Verhelstandbertyhell 7f201ed87d fix(editor): stop linked tag editing while a tag is being deleted (#5434)
Backspacing through a closing tag such as `</div>` also emptied the opening tag, leaving `<>`. The first Backspace removes `>`. The parser still reads `</div` as the element's close tag, so every later Backspace in the name counted as a rename and was mirrored. Linked tag editing now only pairs two tags that both still end in `>`. A tag missing its `>` is being deleted, so nothing is mirrored into it or out of it. The same applies to an opening tag deleted before its children, in all the HTML-based modes and in JSX/TSX. XML does not use linked tags (`LINKED_TAG_LANGUAGES` in `prefs.ts`).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:33 +08:00
Shohruh Ismoilovandshohruh-genius 85344b86b5 fix(templates): offer Svelte components in the New menu (#5440)
The New menu had no built-in template for `.svelte` files. Add **Svelte Component** for Vite and Node.js projects, including SvelteKit workspace members. The template accepts SvelteKit filenames such as `+page.svelte`.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-23 20:02:23 +08:00
faysouandfaysou 12e85a7c1b test(vcs): check Git Log graph options as separate equivalence cases (#5424)
The Git Log graph-equivalence test compares layouts for eight option combinations, each with five fragment configurations. Running all 40 comparisons in one Vitest case exceeded the five-second timeout on shared Linux runners. Give each option combination its own test for histories with and without refs. Each case still compares the complete layout with the dense reference implementation for all five fragment configurations and the same 2,400 commits.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:13 +08:00
faysouandfaysou 861acabf77 test(search): open the action search from the toolbar (#5386)
The action-search test could time out before reaching its first search assertion when the runner delayed the second Shift press. Open Search Everywhere through the title-bar button for this test, then enter a query and run the matching action. The adjacent shortcut test exercises double Shift directly.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:04 +08:00
faysouandfaysou 96395c979f test(project): control the clock during diagonal submenu navigation (#5384)
The Project tree test moves the pointer diagonally toward the New submenu in ten steps. On a busy runner, the time spent delivering input and checking assertions can exceed the menu’s hover delay and close it mid-gesture. Use Playwright’s browser clock to advance 75 ms at each step and check that the submenu stays open through the final 350 ms pause.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:55 +08:00
Mr0Bread e9f768d8b5 perf(events): serialise an event once for all windows (#5445)
With auxiliary windows open (comparison, diff, etc. that share the project's documents), every backend event was serialised once per window, because `emit_to` serialises its payload on each call. For a large diagnostics event that is 2.3 MB (10k items) or 11.6 MB (50k items) of JSON built again for each window, on the thread that emits the event. `TauriSink` now serialises the event once and sends the same JSON string to each window with `emit_str_to`. The payload is the same `serde_json::to_string(&event)` that `emit_to` produced, so the frontend (`getCurrentWebviewWindow().listen` in `src/platform/ipc.ts`) receives exactly what it did before. Which windows get which events is unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:45 +08:00
Mr0Bread d15abe54e2 perf(vcs): read the restricted-mode scoped status with a pathspec (#5451)
In Restricted Mode, the refresh after a watcher batch (`status_paths`) ignored its paths and answered with the full gitoxide status, which walks the whole tree to report one saved file. In a 100k-file repository that took about 87 ms against about 15 ms for a trusted project. It now runs `git status` with the pathspec, as a trusted project does.
The audit (row S4) blamed the extra `git config --null --list` process. That process is not the cause: the full `status()` never runs it (it runs `gitoxide`), and the old restricted `status_paths` did not run it either. The cause is the early return to the full status in `Repo::status_paths`, left from #3267, when the scoped read was in-process and `git` was not allowed. #3280 moved the scoped read to `git`, with the filter overrides the restricted fallback already used, but the restricted bypass stayed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:29 +08:00
faysouandfaysou b501f51526 test(run): compile the output counting reader only on Unix (#5407)
The Windows Clippy job fails because the test reader `Counted` is compiled on Windows, where its only caller is excluded. The flooding-process test uses `awk` and already requires Unix. Apply the same condition to the reader and its `Read` implementation. The cross-platform queue shutdown test keeps its own reader.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:20 +08:00
faysouandfaysou 50cd478773 test(vfs): allow watch events for an excluded directory itself (#5382)
The per-directory watcher skips the contents of excluded directories. A watch on the parent can still report the directory itself, which macOS did for `node_modules`. The regression test now accepts that event while continuing to reject events for descendants.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:10 +08:00
faysouandfaysou 2c63f0eb22 chore(deps): update cookie to 0.18.3 for RUSTSEC-2026-0594 (#5431)
Update the transitive `cookie` dependency from 0.18.2 to 0.18.3. Cargo Deny reports the older release for possible nonce reuse when encrypting private cookies across a fork. The patched crate obtains those nonces from the operating system. [RustSec advisory](https://rustsec.org/advisories/RUSTSEC-2026-0594.html)

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:00 +08:00
faysouandfaysou ed1730f273 fix(vcs): preserve the index timestamp when preparing a commit selection (#5383)
A commit preview or a commit of selected changes can omit a same-size edit made on the same filesystem clock tick as the Git index. Git uses the index timestamp to decide when it must inspect the file contents. The temporary copy now preserves that timestamp so Git detects the edit.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:00:51 +08:00
akshathayadav378-boopandakshathayadav378-boop d6d0cc7926 fix(vcs): use the Project view selection for Git file actions while it is the context (#5428)
Show History (and Add to VCS / the ignore actions) took the editor's file when the shortcut ran right after clicking a Project view row: the row publishes its selection on mousedown, but tree focus is a separate DOM event, so projectViewFocus was still false. File actions now use the Project view selection while the tree owns the context (its lead is set and the editor has no focus), the same rule External Tools use (shared projectViewContextLead helper).

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-23 20:00:11 +08:00
l0ng-ai a21de32077 fix(editor): give the top and bottom breadcrumbs distinct keys (#5463)
The top and bottom breadcrumb bars are keyed separately, so Markdown and HTML tabs no longer log React's duplicate key error.
2026-11-23 19:38:19 +08:00
Bert Verhelstandbertyhell 546ff9f314 fix(run): resolve External Tools file macros against the Project view selection (#5415)
External Tools expanded $FilePath$ and the other file macros from the editor's file even while the Project view was the user's context. They now take the Project view's selected file while it is the context (no editor focus, not a virtual document); caret macros apply only when the editor shows that same file.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 19:35:44 +08:00
l0ng-ai a144208170 fix(debugger): keep a rerun session's tab in place while its adapter starts (#5460)
Rerun keeps the finished tab in place and selected until the new session appears, which then takes its slot and the selection at once.
2026-11-23 19:33:10 +08:00
l0ng-ai fda2d2ff69 fix(run): scroll configuration choosers to their last item in short windows (#5457)
The configuration choosers' list fills the viewport left by a window-capped popup, so its last items scroll into view in short windows.
2026-11-23 19:28:33 +08:00
l0ng-ai 0fdf37f1bf fix(vcs): list every repository's branches and tags in Go to Hash/Branch/Tag (#5455)
Go to Hash/Branch/Tag reads refs from the repositories it searches (shown log tab, else the filtered ones, else every root) instead of an empty Repository filter, which offered only HEAD.
2026-11-23 19:24:50 +08:00
l0ng-ai 5c592bbc86 fix(editor): move a whole switch case in languages with flat case labels (#5453)
Move Statement on a case label in Go, JavaScript and Java moves the whole branch (stacked labels through its last line) past the neighbouring branch instead of only the label line.
2026-11-23 19:22:35 +08:00
l0ng-ai 819ccb8bb5 docs: refresh WeChat group QR code 2026-11-23 19:18:28 +08:00
l0ng-ai ae893f059f fix(agents): keep unrelated chat rows stable during text selection (#5438) 2026-11-23 18:56:34 +08:00
l0ng-ai fb2f567d5b fix(agents): hide Jump to Latest when the reply end is visible (#5442) 2026-11-23 18:51:44 +08:00
l0ng-ai 22af0931dd fix(vcs): name each repository of a shared branch in the Branches pane tooltip (#5413)
In the Git Log Branches pane with several repositories, a branch every
repository has is listed once with no repository name. Hovering it now
lists each repository with the branch it tracks there.
2026-11-23 17:21:59 +08:00
l0ng-ai 4af81625b1 fix(agents): scroll the container under the pointer and keep fold headers in place (#5411)
The wheel now scrolls only the innermost scrollable container under the
pointer: a run of tool calls from its headers, a tool output from its text,
the conversation elsewhere. A nested container at its edge no longer hands
the rest of the gesture to the conversation, and a gesture stays with the
container it started in.

Opening or closing a section keeps its header where it was. Closing one near
the end leaves temporary room below the conversation that scrolling up or new
content takes back.
2026-11-23 17:16:29 +08:00
l0ng-ai f3d18c0eb8 fix(agents): clarify settings names and align the import dialog (#5403)
* fix(agents): align and shorten the Import Sessions dialog

* fix(agents): clarify settings page names
2026-11-23 16:35:39 +08:00
l0ng-ai e662c915a2 fix(agents): show the changes scope as compact tool window tabs (#5393)
The Whole Task / Last Turn switch in the agent Changes pane was a full-width
segmented pill. It now uses the compact Tabs strip that tool window sub-views
use elsewhere.
2026-11-23 15:45:07 +08:00
l0ng-ai f57a17ec14 fix(vcs): group stashes by repository (#5380) 2026-11-23 15:45:02 +08:00
l0ng-ai 0b8d9135aa fix(github): keep the review composer readable (#5375) 2026-11-23 15:44:50 +08:00
l0ng-ai 290ef6956e fix(diff): align original and modified line numbers (#5370)
Unified Diff shows original line numbers in the first column and modified line numbers in the second. Matching rows show both. Removed and inserted rows show the number for their own revision.

Line numbers stay beside the start of their rows when code wraps, and follow scrolling inside a large removed block. Matching rows keep their original numbers when empty lines are ignored. The column order also applies when the editable side is the Git index.
2026-11-23 15:44:15 +08:00
l0ng-ai 8a4b8f45b4 fix(agents): shorten task context menu labels (#5394) 2026-11-23 15:35:46 +08:00
l0ng-ai 31b265cb41 fix(vcs): align the New Worktree dialog (#5367)
- Align the repository, checkout, branch, name, location and setup fields in one label-and-control grid. Use the standard dialog type size for labels and keep the worktree path preview beneath the Location field.
- Let the `.worktreeinclude` edit action wrap below its checkbox in narrow windows. With setup expanded, the standard dialog is about 118 logical pixels shorter, and the setup field fits without scrolling in a 440 × 520 window.
2026-11-23 15:17:34 +08:00
l0ng-ai a6a05caa2e fix(editor): keep multiline find and replace compact (#5362)
Limit the inline Find and Replace fields to three visible lines each. Longer text scrolls inside the fields, leaving more of the matched code on screen.
2026-11-23 14:56:44 +08:00
Deng Liuanddengliu 4690463c53 feat(services): show Compose service resource usage and named volumes (#5330)
The Compose project dashboard listed only container chips, so resource usage meant opening each container, and the project's named volumes were only findable in the global Volumes group among anonymous hashes. It now shows a per-service table (status, CPU, memory, network and block I/O, PIDs) sampled with bounded concurrency and refreshed every 3 s without overlapping requests while the dashboard is visible (paused when the tool window or app is hidden; the container dashboard's stats use the same live sampling instead of a manual Refresh), plus a Volumes section with the project's named volumes that links to each Volume Overview and back.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:49:42 +08:00
Deng Liuanddengliu 8200ce8b5e feat(services): jump from Compose containers to their Compose file (#5348)
Docker Compose containers carry their Compose files and service name but had no way back to the source. Jump to Source (F4 / Cmd+Down, context menu, docker.jumpToSource) on a Compose container opens the Compose file at its service declaration and on a Compose project at the services section; the container dashboard's Command row has a button that lands on the service's command value (else entrypoint, across inline values, block scalars and sequences, later override files taking precedence), and the Compose project dashboard lists its Compose files as links. Missing or unreadable files show a notification.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:47:10 +08:00
Deng Liuanddengliu b524f738e5 fix(services): keep long Docker commands bounded and collapsible in dashboards (#5337)
Property rows in the Docker dashboards aligned items on their baseline; an inline-block value's baseline is its last line, so a wrapped multi-line command painted its earlier lines upward over the rows above it. Rows now align at start with a minmax(0, 1fr) value column, and container/image commands render as a single-line preview (newline markers, copy button, no auto-ellipsis tooltip via data-no-tooltip) that expands into a bounded scrollable block with Entrypoint and Command arguments shown separately.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:43:37 +08:00
l0ng-ai 1f871dc1c2 fix(search): keep multiline file search fields compact (#5358)
Find in Files and Replace in Files show up to three lines in each query field. Longer text scrolls within its field. Closer spacing between the search and replacement fields gives matches and the source preview more room in short windows.
2026-11-23 14:39:03 +08:00
langxpandkradme ceb3cef1af feat(vcs): scope Commit… to the selected project directory (#5304)
Git > Commit… from the Project view ignored the selection. It now passes the selected paths, and the commit interface (modal or not) opens with only the changes at or below them checked: tracked and unversioned files included, conflicts left out, the rest of the working tree still listed.

Co-authored-by: kradme <[email protected]>
2026-11-23 14:27:36 +08:00
Deng Liuanddengliu 735a0157c1 fix(editor): cap inline highlight backgrounds and frames at line height (#5285)
When the editor font's glyph box is taller than the line height (e.g. 18px font at 18px line height), Find matches, occurrence highlights, in-place rename spans, matched brackets, search results and plugin range marks painted the full inline box into the rows above and below. They now share a 1lh-capped background (and a 1px-framed variant), as selection marks already were, keeping background-color / outline fallbacks for Safari before 16.4.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:25:39 +08:00
Mr0Bread 82f26202ed perf(search): keep Find in Files cost linear while results stream in (#5239)
Every streamed file triggered a Find tool window update that rebuilt the whole result tree and its lookup tables, so a search matching thousands of files grew quadratically and froze the IDE. The session now publishes streamed results at most every 50 ms (the first file still at once), and the tool window builds its tree incrementally: only new files get nodes, merged into the sorted result; a list that is not an extension of the previous one is rebuilt.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 14:18:35 +08:00
l0ng-ai a90a9b20e3 fix(debugger): keep Memory instance fields readable (#5342)
The Memory Instances tree gives field values room beside long names. The panel title uses the workbench font. Field names and value previews that run out of space use ellipses and show the full text on hover, and the row's Show Referrers button stays in reach.
2026-11-23 14:17:51 +08:00
Deng Liuanddengliu aad701ba16 fix(editor): clear selection highlights when hiding kept-alive tabs (#5273)
WebKit skips clearing the selection highlight inside a subtree whose rendering is skipped, so a kept-alive tab (an Agent conversation) hidden with content-visibility kept a stale highlight after switching back. Hiding a kept tab now clears a selection inside it while keeping it rendered (invisibly) for one frame via a shared useSelectionVisibility hook, and the agent stream keeps data-selection independent of visibility so off-screen rows clear too.

Co-authored-by: dengliu <[email protected]>
2026-11-23 14:16:18 +08:00
Mr0Bread 46d4036038 perf(editor): keep typing and Enter fast in large TypeScript files (#5251)
Typing and Enter in a large TypeScript file got slower with its size. @lezer/common 1.5.6 gives each repeat group the look-ahead in effect where it ends, so groups above an edit stay reusable and an edit no longer re-parses the file up to the caret; decoratorRanges scans only subtrees not already known to hold no decorator; and Enter's one-line string check parses and highlights only the caret's line instead of the whole document.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 14:16:13 +08:00
LU XIANGRUIandwildcatDownstairs 19859b4ae2 fix(java): refresh semantic highlighting after a project import (#5319)
jdtls returns no semantic tokens for files outside any Java project (a failed Maven import) and sends no workspace/semanticTokens/refresh once a later import takes them in, so open editors stayed uncoloured until edited or reopened. On ProjectStatus the IDE now asks open editors to fetch semantic tokens again, after generated Maven sources are attached. Refs #5301.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 14:13:06 +08:00
Qingandqtvbwfn f3f05f8b15 fix(vue): keep the vtsls route on TypeScript 7 for Vue projects (#5368)
With a TypeScript 7 workspace the native server replaced vtsls before the Vue branch could inject @vue/typescript-plugin, so .vue files lost TypeScript support (Go to Declaration on the 'vue' import failed). The native swap now skips vtsls in a Vue project whose Vue language server is installed; typescript-language-server still takes the native route. Closes #4876.

Co-authored-by: qtvbwfn <[email protected]>
2026-11-23 14:13:02 +08:00
LU XIANGRUIandwildcatDownstairs b0417c83f4 fix(tools): find the Ruff the IDE installed when formatting (#5372)
The formatter lookup checked the project's node_modules and PATH but never a tool's managed virtualenv, so a Ruff installed from the tools list was reported as not installed by Reformat with Ruff. It now looks there before PATH, which also covers Black and Ruff-based Optimize Imports. Closes #5371.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 14:12:58 +08:00
l0ng-ai 4a5d90a91e fix(coverage): make report columns adjustable (#5331)
Make the Coverage table's Line and Branch columns adjustable. The divider next to Element gives space to the file tree, and the divider between the metrics redistributes space between them. Each column shows the full covered/total count when it has room. Compact columns keep the percentage visible and show the full count on hover.

Drag a divider or focus it and use the arrow keys. Double-click a divider to restore the default widths. The table remembers widths across reloads and fits them to smaller docks.
2026-11-23 13:52:09 +08:00
Mr0Bread 1e61b3b270 perf(search): search large files in context mode and non-UTF-8 encodings without reading them whole (#5254)
Project search read a non-UTF-8 file whole and decoded it as one String, and in the comments/strings modes read every file whole to find its comments, even ones far above what the parser takes. Non-UTF-8 files now stream through an incremental decoder (ide_vfs::decode_stream: a detection pass with the same result as decode_text, then 64 KiB chunks), and files too large for the parser are not read for comments at all. Results, binary detection, the match limit and cancellation are unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:47:56 +08:00
Mr0Bread 0809eb417c perf(vcs): keep Git Log graph layout cost per page linear in the loaded commits (#5243)
computeGraph kept its lanes in a dense array indexed by layout number, which grows with the log, and scanned every slot for each row, making each further page of Git Log quadratic in the loaded commits. Lanes are now kept sparsely so a row costs its live lanes, with identical output (checked against a reference implementation), and the graph is laid out again only when an option that shapes it changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:45:28 +08:00
Mr0Bread 86531ee1ba perf(run): bound the output queue of run and build processes (#5256)
The run and build runners passed every pipe chunk or line to their consumer through an unbounded channel, so a process printing faster than the console drained piled its whole output up in memory (hundreds of MB for a few million lines). Both queues are now bounded (128 x 16 KiB chunks for runs, 64 lines for builds): the reader waits, the pipe fills and the child blocks on its write, as on a terminal. Nothing is dropped, and a reader blocked on a full queue ends once the consumer is gone.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:45:25 +08:00
Mr0Bread 54f0373acf fix(project-tree): find removed directories without checking every loaded dir (#5235)
planRefresh and dropListings compared every loaded folder with every removed path or ignore-rule root. They now look up each folder and its ancestors in a set (insideAnyOf), with the same semantics as isSameOrInside.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:24 +08:00
Mr0Bread 137b1cc384 perf(code-insight): apply diagnostics events to the problems store without copying every file's map (#5234)
Each diagnostics event copied the whole problems map, so a storm of per-file events cost files^2 copies. The store now updates its data in place and publishes a new facade per change, so subscribers still see a new identity exactly when the content changed; the MCP problems report keeps its own copy to diff against, and profiledProblems builds its map without per-file copies.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:19 +08:00
Mr0Bread 6c9d432504 perf(host): run route scan, agent reads and plugin keychain calls off the main thread (#5233)
spring_route_sources (walks the project tree), agent_providers (reads the registry and custom agent files), agent_entries (serialises the whole conversation), plugin_secrets and plugin_set_secret (OS keychain) were sync commands that Tauri runs on the main thread. They are now async, all but agent_entries on the blocking pool, and blocking_commands.rs keeps them there.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:43:16 +08:00
Mr0Bread 2395c9544b fix(project-tree): apply one fs change with a single model build (#5241)
Each folder reloaded for an fs event copied the listings map and notified the store, so the mounted view rebuilt the whole tree model once per folder, and the reads were unbounded. One event now reads its folders at most eight at a time and applies all listings in one store update; a folder dropped while the batch was reading stays dropped.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:18 +08:00
Mr0Bread 4b55039e6e fix(editor): refresh usage counts only when a source file changed (#5242)
The usages code lens re-asked the language server for every visible declaration on every fsChanged event, even ones carrying only images or logs. It now recounts only when a changed path can be a file a language server analyses (by the language registry and Settings > File Types), and still recounts when in doubt: unloaded languages or paths without an extension.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:12 +08:00
Mr0Bread 7264194b0f fix(history): find removed files' snapshots without scanning every removed path (#5238)
LocalHistory::note_removed compared every snapshot entry with every removed path, stalling the watcher thread (and saves waiting on the history lock) for seconds on large deletions. Entries are now matched by looking up their path and its ancestors in a set of the removed paths.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:06 +08:00
Mr0Bread 9ebdf0d68f fix(index): remove a deleted subtree in one pass (#5232)
A removed folder arrives with every path below it in one watcher batch; each child that was already gone was looked up as a folder and triggered another full scan of the indexed paths under the write lock, so the cost was removed paths x indexed files. Removed paths that are not indexed files are now collected and everything below them is removed in a single scan.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:36:02 +08:00
LU XIANGRUIandwildcatDownstairs 0843dd8363 fix(agents): don't reference the same file twice with Send to Agent (#5349)
Send to Agent appended an @ mention for every target even when the message already held the same file and lines, leaving duplicate chips and file entries. Mentions already in the message are skipped (a different line range is still its own reference), the draft keeps one file entry per path, and the composer is still shown when nothing new was added. Part of #5296.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 13:34:40 +08:00
Deng Liuanddengliu 9935bfb7c6 fix(agents): coalesce change reads per task (#5346)
The 500 ms notification timer did not cover a change-list read already running, so slow reads overlapped and an older snapshot could land last. Refreshes for one task now share one active read and one trailing read; results from an old project, a removed task or an evicted cache are dropped, and other tasks refresh independently. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:26 +08:00
Deng Liuanddengliu db08dbc4f5 fix(agents): refresh stale queue rows without error toasts (#5334)
A turn could take the next queued message before its row disappeared, so Send now / Edit / Remove on it failed with "already sent" once per click. The dequeue is now published as soon as the turn takes the message; a stale queue action returns OutOfSync after re-publishing the current queue, which the row ignores, and only the pending row is disabled. A missing task or other failure still shows an error.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:22 +08:00
Deng Liuanddengliu cfab86588b perf(agents): skip change diffs for unattributed sibling checkouts (#5344)
A flat change-list request with known attribution now diffs only the nested checkouts that own the task's paths (deleted files included), resolves the nested layout once, keeps the final attribution filter, and falls back to the full scan when attribution is unknown. A task with no touched paths reads nothing. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:34:18 +08:00
Deng Liuanddengliu ba300ecbf9 fix(agents): bound concurrent change-list reads across tasks (#5343)
Flat, grouped and last-turn change-list reads now share four slots per agent manager, acquired before taking a blocking worker and held until the Git work ends even if the caller goes away. Mutations and other VCS work are not limited. Refs #5335.

Co-authored-by: dengliu <[email protected]>
2026-11-23 13:32:49 +08:00
Muuandmuutot 1e79ccaf41 fix(project): run workspace-member settings work off the IPC thread (#5360)
project_workspace_members and project_workspace_member_set ran synchronously on the main thread; each attached root's for_project() re-parses both settings layers and validates the merge against Settings, which overflowed the main thread's stack from a WebView2 callback in a debug build on Windows (STATUS_STACK_OVERFLOW on project open). Both now use desktop_body = spawn with thin desktop bodies, and blocking_commands.rs keeps them off the main thread.

Co-authored-by: muutot <[email protected]>
2026-11-23 13:31:23 +08:00
LU XIANGRUIandwildcatDownstairs 6815cb5f89 fix(debugger): suppress synthetic continued events superseded by a newer stop (#5226)
resume, step and step_in_target emitted a synthetic Continued after the DAP reply even when the adapter's next stopped event had already landed (php-debug/Xdebug on fast steps), leaving the Debug window showing running while paused. The reply now ends prior stops and emits Continued under the suspension lock only when a prior stop was ended and no newer stop superseded it; stopped and continued adapter events emit under the same lock so a synthetic Continued can never follow a newer Stopped.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-23 13:28:19 +08:00
l0ng-ai a79d551bd3 fix(vcs): anchor the Git Log path editor (#5317)
- Open the resizable text editor from its Git Log filter. It follows the visible Paths or More Filters control as the window narrows.
- Give paths a code-font editing area with soft wrapping. Keep the one-path-per-line hint and apply controls beneath it.
- Enter inserts a newline. The platform's primary modifier with Enter applies the filter, and Escape or clicking outside discards the draft.
2026-11-23 13:27:58 +08:00
langxpandkradme 0284b7091b fix(debugger): keep session tab order when restarting (#5318)
Debug tabs were ordered by the backend's increasing session id, so Rerun or a replaced finished tab jumped to the end. Each tab now has a stable local slot that a rerun, a prepared start, a pinned tab's rerun and a browser page inherit; a new session reuses a stopped tab by configuration id, then name, then the selected one. Child sessions are ordered by their root's slot so they stay next to their parent.

Co-authored-by: kradme <[email protected]>
2026-11-23 13:27:13 +08:00
Charlie.Weiandcharli117 93143ce872 test(ide-host): give the Maven import-roots poll a longer deadline (#5366)
The import_roots helper in maven_external polled the background jdtls Maven re-import for 5s, which a loaded CI runner can exceed. Raise the deadline to 15s.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:25:05 +08:00
Charlie.Weiandcharli117 6cbb27ed82 test(ide-lsp): wait for the retiring transport to close before asserting (#5365)
java_sharing_cancels_a_retiring_initialize_before_starting_its_replacement checked old.is_closed() once right after reconfigure() returned, racing the asynchronous close on a loaded runner. Wait for the close before releasing the initialize response; the ordering guarantee still holds because the gate stays shut until then.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:25:01 +08:00
Charlie.Weiandcharli117 74cf06505f test(ide-docker): wait for the log flush instead of a fixed sleep (#5363)
log_lines_arrive_in_order_as_few_batches slept 80ms and assumed the 30ms flusher had emitted the 1000-line burst by then; on a loaded runner the flusher is starved and the trailing line folds into the burst. Wait until every line of the burst has been flushed before sending the trailing one.

Co-authored-by: charli117 <[email protected]>
2026-11-23 13:22:45 +08:00
l0ng-ai d6d73e1072 test(search): measure the scope pattern field after the dialog settles (#5364)
The Scopes dialog relays out over a few frames after the viewport shrinks; wait until the pattern field's position is stable before measuring it.
2026-11-23 13:09:37 +08:00
l0ng-ai bbea793adf fix(debugger): align the Python table viewer (#5309)
- Keep the shape and paging controls above the table and put the full-width slice expression below it, above Close. The grid scrolls between the controls.
- Open at 700 × 500 when there is room. Give short tables the available width, use workbench typography and center the row and column headers.
- Update the title when a slice is submitted and show expression errors below the field.
2026-11-23 13:01:59 +08:00
l0ng-ai f1c556e2ec fix(editor): align the Find Usages source preview (#5305)
- Start with equal space for the results tree and source preview. Each orientation restores its saved split and starts at 50/50 when it has no saved split.
- Follow the editor's line height and size the preview gutter for the document's longest line number. Keep the selected line visible when the panel height or line metrics change.
2026-11-23 12:42:18 +08:00
l0ng-ai 2d99a79e69 fix(settings): align the Editor Tabs form (#5300)
- Align the tab placement and close button selectors in the Appearance form.
- Put the row and overflow choices on separate lines with the overflow options nested under the single-row choice. The two groups retain their own selections and support independent arrow-key navigation.
- Stack each set of closing policy choices below its heading, so the order stays consistent as the window narrows.
2026-11-23 12:24:08 +08:00
l0ng-ai ca778e2382 fix(search): improve structural template layout (#5298)
- Put the language picker in the Search template header and keep each label next to its template.
- Give both templates 150 px of editing space in a standard window. Tighten the editors on shorter screens and keep the dialog footer accessible.
- Use the configured editor font, size, and line height in both templates.
2026-11-23 12:08:57 +08:00
Deng Liuandl0ng-ai 414353a5bd ci: add Docker Compose setup for persistent self-hosted Actions runners (#5307)
* ci: add Docker Compose setup for persistent self-hosted Actions runners

* ci: wire Linux Rust CI to hardened self-hosted runners under scripts/

* ci: gate self-hosted runners behind a variable and use the jammy image

- Pin the Ubuntu 22.04 runner image; the untagged-distro image is 20.04 and
  cannot install libwebkit2gtk-4.1-dev.
- Route the Linux Rust job to self-hosted runners only while the
  SELFHOSTED_RUNNERS repository variable is 'true', so CI keeps working when
  no runner is online.
- On self-hosted runners, enable incremental compilation and clear the
  persistent target dir once it exceeds 40 GB.
- README: document the variable, passwordless sudo inside the container and
  the target dir shared between main and same-repo branches.

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-11-23 11:54:56 +08:00
l0ng-ai 3080dc6100 fix(editor): balance the Edit Macros panes (#5293)
Edit Macros starts with equal widths for the macro list and recorded steps. The keyboard-resizable divider remembers its position. Rename and Delete sit in the toolbar above the macro list, and the dialog opens with focus on the list. Recorded steps use the UI font and wrap within their pane.
2026-11-23 11:45:46 +08:00
l0ng-ai 1bb9f8d07c fix(analysis): align controls with scope choices (#5292)
The shared analysis scope picker aligns directory and custom scope controls with their radio choices. At narrow widths each control sits directly below its choice. Controls stay visible when inactive, and switching the radio selection keeps both values.
2026-11-23 11:24:06 +08:00
l0ng-ai a539baec37 test(settings): measure Git Log checkboxes after the dialog settles (#5311)
The Git Log settings layout test read two checkbox positions one after the other while the Settings dialog was still opening, so it failed depending on timing. It now polls both positions together until they match.
2026-11-23 11:16:43 +08:00
l0ng-ai 7dff6e1852 fix(debugger): give Memory class filtering room (#5289)
The Debug Memory toolbar uses the available space for class search and places the Changed only filter in View Options at the right edge. The button shows when the filter is active. The search field shows a clear button when a query is present.
2026-11-23 11:07:14 +08:00
l0ng-ai fc7fa85850 fix(maven): give plugin names priority in the tree (#5288)
Maven plugin rows use the plugin prefix as the primary label and show the coordinates in muted text. The coordinates truncate independently in narrow docks and can be read in full from their tooltip.
2026-11-23 10:49:33 +08:00
l0ng-ai 7e5a2cf051 fix(vcs): group Git Log display settings (#5287)
Settings → Version Control → Log now groups the display and column checkboxes under titled separators. Both groups use the same checkbox alignment, row spacing, and UI font size, so the controls are easier to scan at narrow window widths.
2026-11-23 10:32:53 +08:00
341 changed files with 15113 additions and 2298 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 138 KiB

+23 -3
View File
@@ -102,24 +102,44 @@ jobs:
name: Rust (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-22.04, windows-latest]
runs-on: ${{ matrix.os }}
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" }
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- name: Linux deps
if: runner.os == 'Linux'
Generated
+2 -2
View File
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.2"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
dependencies = [
"time",
"version_check",
+45 -29
View File
@@ -38,7 +38,7 @@ pub use skill_installer::{
};
use conversation::{Conversation, SavedSubagent, Session};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use ide_vcs::Repo;
use parking_lot::{Mutex, RwLock};
@@ -95,6 +95,8 @@ const MAX_EMBED: u64 = 256 * 1024;
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
/// How long deleting a task waits for its agent to exit before removing the worktree.
const EXIT_WAIT: Duration = Duration::from_secs(5);
/// Change lists can each open several Git pipes; leave room for interactive VCS operations.
const MAX_CHANGE_READS: usize = 4;
/// The agent tasks of one project.
pub struct AgentManager {
@@ -189,6 +191,7 @@ struct Shared {
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
git_executable: RwLock<Option<GitExecutableHook>>,
change_reads: Arc<tokio::sync::Semaphore>,
known: Arc<Mutex<HashMap<String, Known>>>,
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
@@ -604,6 +607,7 @@ impl AgentManager {
new_task_approvals: RwLock::new(None),
workspace_roots: RwLock::new(None),
git_executable: RwLock::new(None),
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
known,
providers,
probes: Mutex::new(HashMap::new()),
@@ -1168,35 +1172,14 @@ impl AgentManager {
/// Drops a queued message.
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
let task = self.task(id)?;
let item = {
let mut s = task.state.lock();
let i =
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
s.task.queue.remove(i)
};
task.persist();
task.emit_task();
Ok(item)
self.task(id)?.take_queued(queued, false).map(|(item, _)| item)
}
/// Sends queued message `queued` now: into the running turn when the agent takes
/// messages mid-turn, else next, cancelling the current turn if there is one.
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
let task = self.task(id)?;
let (item, busy) = {
let mut s = task.state.lock();
let i =
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
let item = s.task.queue.remove(i);
let busy = s.busy;
if !busy {
s.busy = true;
}
(item, busy)
};
task.persist();
task.emit_task();
let (item, busy) = task.take_queued(queued, true)?;
if !busy {
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
return Ok(());
@@ -1847,7 +1830,7 @@ impl AgentManager {
let task = self.task(id)?;
let at = task.base();
let (before, touched) = task.attribution();
vcs(&self.shared, move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
read_changes(&self.shared, move || at.changes(&before, touched.as_deref())).await
}
/// The task's uncommitted changes and, for a worktree task, the commits made since it
@@ -1856,7 +1839,7 @@ impl AgentManager {
let task = self.task(id)?;
let at = task.base();
let (before, touched) = task.attribution();
vcs(&self.shared, move || {
read_changes(&self.shared, move || {
let mut grouped = at.grouped_changes(&before)?;
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
Ok(grouped)
@@ -1869,7 +1852,7 @@ impl AgentManager {
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
let (cwd, turn, dir) = self.task(id)?.last_turn();
let Some(turn) = turn else { return Ok(Vec::new()) };
vcs(&self.shared, move || {
read_changes(&self.shared, move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
@@ -1926,7 +1909,7 @@ impl AgentManager {
let (restamped, restored) = vcs(&self.shared, move || {
let (changes, rev) = match view {
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before, None)?, at.rev()?),
};
let changes = worktree::made_by_task(changes, touched.as_deref());
let sources = match rev.as_deref() {
@@ -2341,6 +2324,23 @@ impl Task {
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
}
/// Takes the item and, for Send now, claims an idle turn under the same lock.
fn take_queued(&self, id: &str, for_send: bool) -> IdeResult<(AgentQueued, bool)> {
let mut s = self.state.lock();
let Some(index) = s.task.queue.iter().position(|item| item.id == id) else {
drop(s);
self.emit_task();
return Err(IdeError::new(ErrorKind::OutOfSync, "Message is no longer queued"));
};
let item = s.task.queue.remove(index);
let was_busy = s.busy;
s.busy |= for_send;
drop(s);
self.persist();
self.emit_task();
Ok((item, was_busy))
}
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
fn set_retry(&self, retry: Option<AgentRetry>) {
{
@@ -2549,7 +2549,10 @@ impl Task {
self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() });
}
match (next, result) {
(Some(queued), _) => prompt = queued.prompt,
(Some(queued), _) => {
self.emit_task();
prompt = queued.prompt;
}
(None, Ok(stop)) => {
self.set_status(AgentStatus::Ready, None);
if stop != "cancelled" {
@@ -4270,6 +4273,19 @@ async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
}
async fn read_changes<T: Send + 'static>(
shared: &Shared,
f: impl FnOnce() -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
let permit = shared.change_reads.clone().acquire_owned().await.map_err(|e| IdeError::internal(e.to_string()))?;
vcs(shared, move || {
// Dropping the caller doesn't cancel a blocking job. Keep the slot with the work.
let _permit = permit;
f()
})
.await
}
#[cfg(test)]
mod replay;
#[cfg(test)]
+3
View File
@@ -536,6 +536,9 @@ pub enum AgentEntry {
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Images returned by the tool, kept separately from its truncated text.
#[serde(default)]
images: Vec<AgentImage>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
+30
View File
@@ -1007,11 +1007,16 @@ impl Session {
let mut updates = Vec::new();
let mut finished = None;
let mut read_title = false;
let mut refresh_usage = false;
{
let mut st = self.st.lock();
let st = &mut *st;
match kind {
"system" => match msg.get("subtype").and_then(Value::as_str) {
Some("compact_boundary") => {
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
updates.extend(st.tr.on_message(&msg));
}
Some("init") => {
st.terminal_only = strings(msg.get("terminal_slash_commands"));
}
@@ -1115,6 +1120,31 @@ impl Session {
if read_title {
self.read_title();
}
if refresh_usage {
self.refresh_usage();
}
}
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
/// counts it (`get_context_usage`); until then the meter would show the count from before.
fn refresh_usage(self: &Arc<Self>) {
let me = self.clone();
tokio::spawn(async move {
let Some(proc) = me.st.lock().proc.clone() else { return };
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
Ok(usage) => usage,
Err(e) => {
tracing::debug!("reading claude context usage after compaction: {e}");
return;
}
};
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
let update = me.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = me.shim() {
shim.notify(vec![update]);
}
});
}
/// Sends the session's title once it has one: the one in its transcript, or else one
@@ -531,6 +531,38 @@ async fn sessions_without_a_title_get_one_generated() {
assert_eq!(request["request"]["persist"], true);
}
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
/// driver asks Claude Code, and the meter shows that instead of the count from before.
#[tokio::test(flavor = "multi_thread")]
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
let mut processes = load_fixture("simple");
processes[0].extend([
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
"request": {"subtype": "get_context_usage"}})),
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
]);
let cli = replay_cli(processes);
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let session = h.new_session().await;
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
let mut usage = Vec::new();
for _ in 0..100 {
usage = h.updates(&session, "usage_update");
if usage.last().is_some_and(|u| u["used"] == 4200) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_multi_turn() {
let r = replay("multi_turn").await;
@@ -1098,6 +1130,24 @@ fn streamed_text_is_not_sent_twice() {
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
}
#[test]
fn a_compaction_replaces_the_context_usage() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
t.on_message(&assistant);
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
assert_eq!(t.on_result(&result)[0].update["used"], 950);
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
// The `/compact` turn's result reports what compaction left, not the count from before.
assert_eq!(t.on_result(&result)[0].update["used"], 120);
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
assert!(t.on_result(&result).is_empty());
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
@@ -144,6 +144,22 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
content.push(text(&t));
}
}
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
for block in blocks {
if block.get("type").and_then(Value::as_str) != Some("image") {
continue;
}
let Some(source) = block.get("source") else { continue };
if source.get("type").and_then(Value::as_str) != Some("base64") {
continue;
}
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
if !data.is_empty() && mime.starts_with("image/") {
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
}
}
}
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
if !content.is_empty() {
out["content"] = Value::Array(content);
@@ -230,6 +246,43 @@ mod tests {
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
}
#[test]
fn image_tool_results_keep_text_and_inline_images() {
let result = result_fields(
"Read",
&json!({"file_path": "/w/preview.png"}),
&json!({"content": [
{"type": "text", "text": "Preview ready"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
None,
);
assert_eq!(result["status"], "completed");
assert_eq!(
result["content"],
json!([
text("Preview ready"),
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
])
);
}
#[test]
fn failed_shell_tool_images_keep_fallback_error_text() {
let result = result_fields(
"Bash",
&json!({}),
&json!({"is_error": true, "content": [
{"type": "text", "text": "Preview command failed"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
Some(&json!({"stdout": "", "stderr": ""})),
);
assert_eq!(result["status"], "failed");
assert_eq!(result["content"][0], text("Preview command failed"));
assert_eq!(result["content"][1]["content"]["type"], "image");
}
#[test]
fn results() {
let input = json!({"file_path": "/w/n.txt", "content": "two"});
@@ -458,6 +458,13 @@ impl Translator {
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
self.finish_child(&tool_use, stop, last.or(summary))
}
// Compaction replaced the conversation with its summary: the context now holds
// `post_tokens`. Without it the stale count must not come back with the result;
// the driver asks Claude Code instead (`Session::refresh_usage`).
Some("compact_boundary") => {
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
self.usage_update().into_iter().collect()
}
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
Some("background_tasks_changed") => {
@@ -561,6 +568,16 @@ impl Translator {
self.usage_update().into_iter().collect()
}
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
}
Update { session: self.root.clone(), update }
}
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
+91
View File
@@ -452,6 +452,57 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
manager_at(dir, &dir.join("models.json"), agent)
}
#[tokio::test]
async fn change_reads_share_a_budget_until_the_blocking_work_finishes() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::default());
let submitted = Arc::new(AtomicU32::new(0));
mgr.set_git_executable_hook(Arc::new({
let submitted = submitted.clone();
move || {
submitted.fetch_add(1, Ordering::SeqCst);
None
}
}));
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
let (finished, mut finishes) = tokio::sync::mpsc::unbounded_channel();
let mut releases = Vec::new();
let mut reads = Vec::new();
for job in 0..12 {
let (release, gate) = tokio::sync::oneshot::channel::<()>();
releases.push(release);
let (started, finished) = (started.clone(), finished.clone());
let mut read = Box::pin(read_changes(&mgr.shared, move || {
started.send(()).unwrap();
gate.blocking_recv().unwrap();
finished.send(()).unwrap();
Ok(())
}));
tokio::select! { biased; _ = &mut read => panic!("read finished before release"), _ = std::future::ready(()) => {} }
reads.push(read);
if job == 0 {
// Cancelling the requester cannot stop the blocking job or free its slot.
starts.recv().await.unwrap();
drop(reads.pop());
}
}
let admitted = submitted.load(Ordering::SeqCst);
for _ in 1..admitted {
starts.recv().await.unwrap();
}
for release in releases {
release.send(()).unwrap();
}
for read in reads {
read.await.unwrap();
}
for _ in 0..12 {
finishes.recv().await.unwrap();
}
eprintln!("change-read fixture: peak active {admitted}; completed 12/12");
assert_eq!(admitted, 4);
}
#[tokio::test]
async fn subscribers_do_not_replace_or_close_each_other() {
let tmp = tempfile::tempdir().unwrap();
@@ -1375,6 +1426,46 @@ async fn steers_through_session_steering() {
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() {
use ide_core::error::ErrorKind;
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("ask"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.prompt(&task.id, text("again"), false).await.unwrap();
let handle = mgr.task(&task.id).unwrap();
let queued = handle.state.lock().task.queue[0].id.clone();
let permission = *handle.permissions.lock().keys().next().unwrap();
let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel();
let weak = Arc::downgrade(&handle);
mgr.subscribe(Arc::new(move |event| {
if let AgentEvent::Task { task } = event
&& task.queue.is_empty()
&& let Some(handle) = weak.upgrade()
{
let _ = tx.send(handle.turns.load(Ordering::Acquire));
}
}));
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn");
while updates.try_recv().is_ok() {}
for error in
[mgr.unqueue(&task.id, &queued).unwrap_err(), mgr.send_queued_now(&task.id, &queued).await.unwrap_err()]
{
assert_eq!(error.kind, ErrorKind::OutOfSync);
assert_eq!(updates.try_recv().unwrap(), 2, "a stale action gets the current queue");
}
assert!(!handle.state.lock().busy);
assert_eq!(mgr.unqueue("missing-task", &queued).unwrap_err().kind, ErrorKind::NotFound);
}
#[tokio::test(flavor = "multi_thread")]
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
let tmp = tempfile::tempdir().unwrap();
+42 -3
View File
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -84,6 +84,7 @@ impl Timeline {
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
images: Vec::new(),
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
@@ -150,7 +151,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -173,10 +174,20 @@ impl Timeline {
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
if let Some(t) = content_text(item.get("content")) {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
@@ -203,6 +214,9 @@ impl Timeline {
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
@@ -439,6 +453,31 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
old.as_object_mut().unwrap().remove("images");
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
]});
t.apply(&update);
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+103 -11
View File
@@ -65,7 +65,7 @@ impl TurnRepos {
/// The innermost repository holding `path`.
fn owner(&self, path: &Path) -> Option<&Repo> {
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
owning_repo(&self.repos, path)
}
/// `repo`'s `HEAD` as the turn `start` began.
@@ -78,6 +78,10 @@ fn root_key(root: &Path) -> String {
root.to_string_lossy().into_owned()
}
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
}
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
/// one lists it itself; to `repo` its folder is untracked).
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
@@ -91,11 +95,25 @@ fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Optio
}
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
// Match deletions too: find the owner by path components, not by opening the file.
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
// name cannot round-trip from that representation, keep the full-read fallback.
let owners = touched
.filter(|_| {
roots.iter().all(|root| {
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
})
})
.map(|paths| {
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
});
let mut out: Vec<AgentChange> = Vec::new();
for repo in &repos {
for repo in repos {
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
continue;
}
let listed = match repo.head()?.1 {
Some(head) => changes(repo.root(), &head)?,
None => {
@@ -103,7 +121,7 @@ fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
}
};
for mut c in listed {
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
if out.iter().any(|o| o.path == c.path) {
continue;
}
@@ -364,13 +382,30 @@ impl TaskBase {
}
/// The files the task changed, less those changed before it started and untouched since.
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
pub(crate) fn changes(
&self,
before: &BTreeMap<String, Stamp>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<AgentChange>> {
if touched.is_some_and(BTreeSet::is_empty) {
return Ok(Vec::new());
}
Ok(made_by_task(self.read_changes(before, touched)?, touched))
}
fn read_changes(
&self,
before: &BTreeMap<String, Stamp>,
touched: Option<&BTreeSet<String>>,
) -> IdeResult<Vec<AgentChange>> {
let (cwd, start) = match self {
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
Self::Local { cwd, .. } if spans_repos(cwd) => {
return Ok(without_untouched(nested_changes(cwd)?, before));
Self::Local { cwd, start } => {
if let Some((base, repos)) = nested_repos(cwd)? {
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
}
(cwd, start.as_deref())
}
Self::Local { cwd, start } => (cwd, start.as_deref()),
};
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
// What is uncommitted, as the Commit tool window lists it: commits made since the task
@@ -429,7 +464,7 @@ impl TaskBase {
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
let cwd = self.cwd();
if spans_repos(cwd) {
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
}
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1;
@@ -1122,6 +1157,57 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[cfg(unix)]
#[test]
fn attributed_changes_only_diff_the_owning_checkout() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
for n in 0..15 {
let repo = root.join(format!("repo{n:02}"));
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(&repo, &["add", "a.txt"]);
git(&repo, &["commit", "-q", "-m", "initial"]);
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
}
// Count real Git diff processes, not walks to discover the topology.
let git = tmp.path().join("count-git");
let log = tmp.path().join("count-git.log");
std::fs::write(
&git,
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
)
.unwrap();
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
let at = TaskBase::Local { cwd: root, start: None };
let before = BTreeMap::new();
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
let read = |touched: Option<&BTreeSet<String>>| {
std::fs::write(&log, "").unwrap();
let start = std::time::Instant::now();
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
let elapsed = start.elapsed();
let calls = std::fs::read_to_string(&log).unwrap();
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
(changes, calls.lines().count())
};
let (all, full_calls) = read(None);
let (selected, selected_calls) = read(Some(&one));
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
assert_eq!(all.len(), 15);
assert_eq!(
serde_json::to_value(selected).unwrap(),
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
);
assert!(empty.is_empty());
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
assert!(selected_calls > 0);
assert_eq!(selected_calls * 15, full_calls);
assert_eq!(empty_calls, 0);
}
#[test]
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
let tmp = tempfile::tempdir().unwrap();
@@ -1144,7 +1230,7 @@ mod tests {
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
let at = TaskBase::Local { cwd: root.clone(), start: None };
let changed = at.changes(&before).unwrap();
let changed = at.changes(&before, None).unwrap();
let listed: Vec<(&str, &Path)> =
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
assert_eq!(
@@ -1168,6 +1254,12 @@ mod tests {
}
assert!(!nested.join("b.txt").exists());
assert!(root.join("mine.txt").exists(), "the user's own change stays");
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
std::fs::remove_file(deeper.join("a.txt")).unwrap();
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
assert_eq!(removed.len(), 1);
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
assert_eq!(removed[0].kind, ChangeKind::Deleted);
}
#[test]
+148 -9
View File
@@ -24,6 +24,21 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
/// print far more than is ever parsed back out of the retained copy.
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
const LINE_QUEUE: usize = 64;
/// What [`pump_bounded`] reads from a pipe at a time.
const PUMP_CHUNK: usize = 64 * 1024;
/// One line of a child's output, with the stream it came from.
type Line = (Stream, String);
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
/// consumer is behind.
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
mpsc::sync_channel(LINE_QUEUE)
}
pub(crate) struct Output {
pub success: bool,
@@ -33,20 +48,20 @@ pub(crate) struct Output {
pub truncated: bool,
}
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
/// never grows one line buffer without bound.
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
/// Bounded pump for callers that stream every line and only summarize errors: reads
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
/// and never grows one line buffer without bound.
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
let mut reader = BufReader::new(stream);
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
// newline-free run at the line cap must keep a trailing `\r` — it is data.
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
let line = ide_core::output_encoding::decode_tool_output(buf);
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
buf.clear();
tx.send((kind, line)).is_ok()
};
let mut chunk = vec![0u8; 64 * 1024];
let mut chunk = vec![0u8; PUMP_CHUNK];
let mut line: Vec<u8> = Vec::with_capacity(256);
'read: loop {
let n = match reader.read(&mut chunk) {
@@ -179,8 +194,8 @@ fn run_with_env_capture(
}
let mut child =
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
let (tx, rx) = line_queue();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
std::thread::spawn(move || {
if bounded {
pump_bounded(stream, kind, &tx);
@@ -212,7 +227,8 @@ fn run_with_env_capture(
// Retained copy of the output: the first half of the cap, then — once output overflows —
// a rolling tail instead of the middle. Error summaries read the end of the output, while
// listings parsed out of a successful run read from the start. The pipes keep draining
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
// either way: `on_line` still sees every line, and the child waits on its pipe only
// while `on_line` is behind, never because the retained copy is full.
let cap = MAX_TEXT_BYTES / 2;
let mut head = String::new();
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
@@ -295,6 +311,9 @@ fn run_with_env_capture(
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
#[test]
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
@@ -500,4 +519,124 @@ mod tests {
assert!(out.text.starts_with("pad\n"));
assert!(out.text.ends_with("FATAL: the real error\n"));
}
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
/// reports when it is dropped, which is when the pump owning it ends.
const LINE_LEN: usize = 100;
struct NumberedLines {
next: usize,
lines: usize,
taken: Arc<AtomicUsize>,
gone: mpsc::Sender<()>,
}
fn numbered(n: usize) -> String {
format!("{n:0width$}", width = LINE_LEN - 1)
}
impl Read for NumberedLines {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut n = 0;
while self.next < self.lines && n + LINE_LEN <= buf.len() {
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
buf[n + LINE_LEN - 1] = b'\n';
self.next += 1;
n += LINE_LEN;
}
self.taken.fetch_add(n, Ordering::SeqCst);
Ok(n)
}
}
impl Drop for NumberedLines {
fn drop(&mut self) {
let _ = self.gone.send(());
}
}
#[test]
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
const LINES: usize = 50_000;
let taken = Arc::new(AtomicUsize::new(0));
let (gone, _) = mpsc::channel();
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
let (tx, rx) = line_queue();
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
let (mut count, mut peak) = (0usize, 0usize);
loop {
match rx.recv_timeout(Duration::from_secs(60)) {
Ok((stream, line)) => {
assert_eq!(stream, Stream::Stdout);
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
// Read from the pipe but not yet handed over: the rest of the chunk the pump
// is cutting into lines, and the queue.
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
count += 1;
// A consumer that cannot keep up with the process.
if count.is_multiple_of(LINE_QUEUE) {
std::thread::sleep(Duration::from_millis(1));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
}
}
pump.join().unwrap();
assert_eq!(count, LINES);
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
}
#[test]
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
let taken = Arc::new(AtomicUsize::new(0));
let (gone_tx, gone) = mpsc::channel();
// Far more than the queue and a few chunks hold.
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
let (tx, rx) = line_queue();
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
let deadline = Instant::now() + Duration::from_secs(30);
while taken.load(Ordering::SeqCst) == 0 {
assert!(Instant::now() < deadline, "the pump never read");
std::thread::sleep(Duration::from_millis(1));
}
// Time for a pump that does not wait to run ahead.
std::thread::sleep(Duration::from_millis(100));
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
drop(rx);
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
pump.join().unwrap();
}
#[test]
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
if cfg!(windows) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
for bounded in [false, true] {
let mut next = 1usize;
let on_line = |stream: Stream, line: &str| {
assert_eq!(stream, Stream::Stdout);
assert_eq!(line, next.to_string());
next += 1;
if next.is_multiple_of(1000) {
std::thread::sleep(Duration::from_millis(1));
}
};
let cancel = CancellationToken::new();
let out = if bounded {
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
} else {
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
}
.unwrap();
assert!(!out.success);
assert_eq!(next, 300_001, "lines were lost");
}
}
}
+1 -1
View File
@@ -95,7 +95,7 @@ pub enum ErrorKind {
AlreadyExists,
PermissionDenied,
InvalidInput,
/// Document version mismatch; the UI must resync the full text.
/// The requested state is stale; the UI must use the current snapshot.
OutOfSync,
Cancelled,
TimedOut,
+3 -9
View File
@@ -1752,9 +1752,7 @@ impl DebugManager {
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
// DAP: a response without the flag continued every thread.
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
session.suspended.resumed(ticket, thread_id, all);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
session.finish_resume(ticket, thread_id, all);
Ok(())
}
@@ -1801,9 +1799,7 @@ impl DebugManager {
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
session.finish_resume(ticket, thread_id, false);
Ok(())
}
@@ -1913,9 +1909,7 @@ impl DebugManager {
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
.await;
step_settled(&session, sent)?;
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
session.finish_resume(ticket, thread_id, false);
Ok(())
}
+137 -16
View File
@@ -160,19 +160,36 @@ impl Stops {
}
/// Ends the stops taken by ticket `upto` of `thread`, or of every thread.
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) {
/// Returns whether any stop was removed.
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) -> bool {
let latest = self.latest();
let before = (self.all, self.threads.len());
if every || thread.is_none() || self.all.is_some_and(|t| t <= upto) {
self.all = self.all.filter(|&t| t > upto);
self.threads.retain(|&(_, t)| t > upto);
} else {
self.threads.retain(|&(id, t)| Some(id) != thread || t > upto);
}
let changed = (self.all, self.threads.len()) != before;
// Back on an earlier thread's stop, as the JDWP link moves to it with a new generation.
let now = self.latest();
if now.is_some() && now != latest {
self.ticket += 1;
}
changed
}
/// Whether a stop taken after `after` would be undone by a synthetic `continued` event for
/// `thread` (or for every thread when `every` is set).
fn superseded(&self, thread: i64, every: bool, after: u64) -> bool {
if self.all.is_some_and(|t| t > after) {
return true;
}
if every {
self.threads.iter().any(|&(_, t)| t > after)
} else {
self.threads.iter().any(|&(id, t)| id == thread && t > after)
}
}
}
@@ -197,12 +214,27 @@ impl Suspension {
}
}
/// A `continued` event; `all`: its `allThreadsContinued`.
pub fn continued(&self, thread: Option<i64>, all: bool) {
self.0.lock().release(thread, all, u64::MAX);
/// Runs `emit` under the suspension lock so a synthetic `continued` from a resume reply cannot
/// be emitted after a `stopped` event once that stop has been recorded.
pub fn emit_synced(&self, emit: impl FnOnce()) {
let _stops = self.0.lock();
emit();
}
/// Take before sending a resume-like request and pass to [`Self::resumed`].
/// A `continued` event; `all`: its `allThreadsContinued`. Runs `emit` under the same lock so
/// synthetic `continued` events from resume replies stay ordered against it.
pub fn continued_and_emit(&self, thread: Option<i64>, all: bool, emit: impl FnOnce()) {
let mut stops = self.0.lock();
stops.release(thread, all, u64::MAX);
emit();
}
#[cfg(test)]
pub fn continued(&self, thread: Option<i64>, all: bool) {
self.continued_and_emit(thread, all, || {});
}
/// Take before sending a resume-like request and pass to [`Self::resumed_and_emit`].
pub fn ticket(&self) -> u64 {
self.0.lock().ticket
}
@@ -215,8 +247,19 @@ impl Suspension {
}
/// After a successful resume-like request for `thread`; `all`: every thread ran.
/// Runs `emit` under the lock only when a prior stop was ended and no newer stop superseded it.
pub fn resumed_and_emit(&self, ticket: u64, thread: i64, all: bool, emit: impl FnOnce()) {
let mut stops = self.0.lock();
let superseded = stops.superseded(thread, all, ticket);
let released = stops.release(Some(thread), all, ticket);
if released && !superseded {
emit();
}
}
#[cfg(test)]
pub fn resumed(&self, ticket: u64, thread: i64, all: bool) {
self.0.lock().release(Some(thread), all, ticket);
self.resumed_and_emit(ticket, thread, all, || {});
}
}
@@ -316,6 +359,16 @@ impl Session {
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
}
/// Completes a successful resume or step reply (`ticket` taken before the request): ends the
/// prior stops and emits a synthetic `continued` event unless an adapter event already ended
/// them or a newer `stopped` event superseded it.
pub(crate) fn finish_resume(&self, ticket: u64, thread_id: i64, all: bool) {
self.suspended.resumed_and_emit(ticket, thread_id, all, || {
self.emit(DebugEvent::Continued { thread_id, all_threads_continued: all });
});
crate::stream_trace::release_done(self);
}
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
pub fn adapter_path(&self, path: &Path) -> PathBuf {
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
@@ -789,23 +842,26 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
reason = quirks.stop_reason(reason);
}
mgr.restore_breakpoints(s).await;
s.emit(DebugEvent::Stopped {
thread_id: int("threadId").unwrap_or(0),
reason,
description: str_("description").or_else(|| str_("text")),
all_threads_stopped: all,
s.suspended.emit_synced(|| {
s.emit(DebugEvent::Stopped {
thread_id: int("threadId").unwrap_or(0),
reason,
description: str_("description").or_else(|| str_("text")),
all_threads_stopped: all,
});
});
}
"continued" => {
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
// DAP: an event without the flag continues its thread alone. The UI keeps treating
// it as all threads; the suspension, which holds only threads that stopped, need not.
s.suspended.continued(int("threadId"), all.unwrap_or(false));
crate::stream_trace::release_done(s);
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
s.suspended.continued_and_emit(int("threadId"), all.unwrap_or(false), || {
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
});
});
crate::stream_trace::release_done(s);
}
"output" => {
let category = str_("category").unwrap_or_else(|| "console".into());
@@ -1465,6 +1521,71 @@ mod tests {
assert!(!s.get());
}
#[test]
fn synthetic_continued_is_suppressed_when_a_newer_stop_or_continued_already_landed() {
let emit_if_resumed = |s: &Suspension, ticket, thread, all| {
let mut emitted = false;
s.resumed_and_emit(ticket, thread, all, || emitted = true);
emitted
};
// Normal step without an adapter `continued` event emits a synthetic one.
let s = Suspension::default();
s.stopped(Some(1), true);
assert!(emit_if_resumed(&s, s.ticket(), 1, false));
// Next `stopped` (all-threads or single-thread) overtakes the reply: no synthetic `continued`.
for next_all in [true, false] {
let s = Suspension::default();
s.stopped(Some(1), true);
let ticket = s.ticket();
s.stopped(Some(1), next_all);
assert!(!emit_if_resumed(&s, ticket, 1, false), "next_all={next_all}");
assert!(s.get());
}
// Adapter's own `continued` event already ended the stop: no duplicate synthetic `continued`.
let s = Suspension::default();
s.stopped(Some(1), true);
let ticket = s.ticket();
s.continued(Some(1), true);
assert!(!emit_if_resumed(&s, ticket, 1, true));
// Multi-thread: thread 7 steps while thread 9 stops alone -> thread 7 still emits `continued(all=false)`.
let s = two_threads_stopped();
let ticket = s.ticket();
s.stopped(Some(9), false);
assert!(emit_if_resumed(&s, ticket, 7, false));
assert!(s.get());
// Multi-thread: `continue(all=true)` while thread 9 stops alone -> suppressed so thread 9 stays paused.
let s = two_threads_stopped();
let ticket = s.ticket();
s.stopped(Some(9), false);
assert!(!emit_if_resumed(&s, ticket, 7, true));
assert!(s.get());
}
#[test]
fn concurrent_stop_and_resume_never_emit_continued_after_the_new_stop() {
for _ in 0..200 {
let s = std::sync::Arc::new(Suspension::default());
let log = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));
s.stopped(Some(1), true);
let ticket = s.ticket();
let s2 = s.clone();
let log2 = log.clone();
let stop = std::thread::spawn(move || {
s2.stopped(Some(1), false);
s2.emit_synced(|| log2.lock().push("stopped"));
});
s.resumed_and_emit(ticket, 1, false, || log.lock().push("continued"));
stop.join().unwrap();
let events = log.lock().clone();
assert!(events == ["continued", "stopped"] || events == ["stopped"], "unexpected order: {events:?}");
}
}
#[test]
fn kotlin_launch_starts_attach_listener_first() {
assert_eq!(
+107
View File
@@ -157,6 +157,11 @@ struct Script {
breakpoints_after_continue: usize,
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
step_reason: Option<&'static str>,
/// Send `stopped` before answering `next` / `stepIn` / `stepOut` / `continue` (like php-debug
/// when Xdebug finishes a step before the DAP reply is handled).
stop_before_reply: bool,
/// Send `continued` before answering `next` / `continue`.
continued_before_reply: bool,
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
refuse_next: bool,
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
@@ -213,6 +218,8 @@ impl Default for Script {
refuse_continue: false,
breakpoints_after_continue: 0,
step_reason: None,
stop_before_reply: false,
continued_before_reply: false,
refuse_next: false,
invalidated_after_stop: false,
stop_during_threads: false,
@@ -414,6 +421,19 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
tokio::time::sleep(Duration::from_millis(50)).await;
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
}
"next" if script.stop_before_reply => {
let reason = script.step_reason.unwrap_or("step");
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"next" if script.continued_before_reply => {
send!(
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": false}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"next" => {
ok!(msg, Value::Null);
let reason = script.step_reason.unwrap_or("step");
@@ -553,6 +573,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"stepOut" if script.refuse_step_out => send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"})
),
"continue" if script.stop_before_reply => {
send!(
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"allThreadsContinued": true}));
}
"continue" if script.continued_before_reply => {
send!(
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": true}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"allThreadsContinued": true}));
}
"continue" if script.stop_after_continue => {
ok!(msg, json!({"allThreadsContinued": true}));
send!(
@@ -575,6 +609,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}}));
}
}
"stepIn" | "stepOut" if script.stop_before_reply => {
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
"hotReload" => {
ok!(msg, Value::Null);
@@ -2789,6 +2828,74 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
}
}
/// When an adapter emits the next `stopped` event before replying to `next` / `stepIn` / `stepOut`
/// / `continue` (as php-debug / Xdebug can on fast steps), no trailing synthetic `continued` may
/// overwrite the new stop.
#[tokio::test]
async fn stop_before_reply_does_not_emit_trailing_continued() {
let h = harness(Script { stop_before_reply: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let session = h.manager.session(id).unwrap();
let run_events = |from: usize| {
h.events
.lock()
.iter()
.skip(from)
.filter_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(format!("stopped:{reason}")),
IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. } => Some("continued".into()),
_ => None,
})
.collect::<Vec<_>>()
};
for (label, expected) in [
("over", "stopped:step"),
("into", "stopped:step"),
("out", "stopped:step"),
("target", "stopped:step"),
("resume", "stopped:breakpoint"),
] {
let before = h.events.lock().len();
match label {
"over" => h.manager.step(id, 1, StepKind::Over).await.unwrap(),
"into" => h.manager.step(id, 1, StepKind::Into).await.unwrap(),
"out" => h.manager.step(id, 1, StepKind::Out).await.unwrap(),
"target" => h.manager.step_in_target(id, 1, 1).await.unwrap(),
"resume" => h.manager.resume(id, 1).await.unwrap(),
_ => unreachable!(),
}
assert!(session.suspended.get(), "{label}: session must remain suspended");
assert_eq!(run_events(before), [expected], "{label}: must not emit continued after stopped");
}
}
#[tokio::test]
async fn continued_event_before_reply_does_not_emit_duplicate_continued() {
for is_resume in [false, true] {
let h = harness(Script { continued_before_reply: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let before = h.events.lock().len();
if is_resume {
h.manager.resume(id, 1).await.unwrap();
} else {
h.manager.step(id, 1, StepKind::Over).await.unwrap();
}
let continued = h
.events
.lock()
.iter()
.skip(before)
.filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. }))
.count();
assert_eq!(continued, 1, "is_resume={is_resume}: adapter continued event already reported it");
}
}
#[tokio::test]
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
let h = harness(Script::default());
+6 -1
View File
@@ -658,7 +658,12 @@ mod local_tests {
let batches = Mutex::new(Vec::<Vec<u32>>::new());
let result = batched(Duration::from_millis(30), &|b| batches.lock().unwrap().push(b), |line| {
(0..1000).for_each(line);
std::thread::sleep(Duration::from_millis(80));
// Wait for the flusher to emit the whole burst rather than assuming a fixed
// sleep outlasts its scheduling: a loaded runner can starve the thread
// past the quiet spell and fold the trailing line into the burst.
while batches.lock().unwrap().iter().map(Vec::len).sum::<usize>() < 1000 {
std::thread::sleep(Duration::from_millis(5));
}
line(1000);
"done"
});
+2 -1
View File
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
mut config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
config.extras.module = Some(module);
Ok(Ok(RunConfig { command, args, ..config }))
}
+19 -6
View File
@@ -43,12 +43,19 @@ pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeRe
Ok(())
}
/// Reads the ACP registry's install state for every provider from disk, so it runs on the
/// blocking pool.
#[command(trust = trusted)]
pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
host.require_trust(window)?;
let mut providers = host.project(window)?.agents.providers();
ide_agent::registry::mark_updates(&registry_paths(host), &mut providers);
Ok(providers)
let agents = host.project(window)?.agents.clone();
let paths = registry_paths(host);
host.blocking(move || {
let mut providers = agents.providers();
ide_agent::registry::mark_updates(&paths, &mut providers);
Ok(providers)
})
.await
}
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
@@ -249,9 +256,15 @@ pub async fn agent_commands(
host.project(window)?.agents.commands(&provider, task.as_deref()).await
}
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
/// conversation is cloned and serialised off the main thread.
#[command(trust = always)]
pub fn agent_entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
pub async fn agent_entries(
host: &Host,
window: &str,
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
host.project(window)?.agents.entries(&task, subagent)
}
+10 -5
View File
@@ -1,6 +1,6 @@
//! Maven / Gradle tool windows (the build model and its background sync) and
//! Build › Build Project (compiling with the project's build system).
mod workspace;
pub(super) mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use crate::ops::Channel;
@@ -181,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
@@ -952,16 +952,18 @@ pub async fn build_run(
items: Vec::new(),
});
}
let mut launch_caches = Vec::new();
let plan = if let Some(id) = cmake {
launch_caches.push(cache.clone());
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
cmake_plan(&root, kind, &configs, &id)?
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
let mut combined: Option<compile::BuildPlan> = None;
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let member_cache = workspace::cache_at(&root, &cache, member);
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
launch_caches.push(member_cache);
let plan = prepare_plan(
compile::plan(
member,
@@ -985,6 +987,7 @@ pub async fn build_run(
plan
} else {
let model = with_profiles(load(&root, &cache, &settings), &cache);
launch_caches.push(cache.clone());
match compile::plan(
&root,
&model,
@@ -1007,7 +1010,9 @@ pub async fn build_run(
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
for cache in launch_caches {
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
}
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
+23 -6
View File
@@ -1,12 +1,33 @@
use super::*;
use std::path::PathBuf;
pub(super) struct Scope {
pub(in crate::ops) struct Scope {
pub root: PathBuf,
pub cache: PathBuf,
pub settings: Settings,
}
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
let root = workspace
.as_ref()
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
.unwrap_or(&project.root);
Ok(Scope {
cache: cache_at(&project.root, &project.build_cache_dir(), root),
settings: if root == &project.root {
project.settings.effective()
} else {
project.settings.for_project(root).effective()
},
root: root.clone(),
})
}
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
}
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
}
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
cache: cache_at(window_root, cache, &root),
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
+10
View File
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
ide_vfs::create_dir(&path)
}
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
/// keeps its scratches on the server, where its file commands run.
#[command(trust = always)]
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
let dir = host.data_dir.join("scratches");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
#[command(trust = always)]
@@ -383,6 +392,7 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+57 -62
View File
@@ -4,7 +4,7 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::build::load;
use super::build::{load, with_profiles, workspace};
use ide_build::BuildModel;
use ide_build::compile;
use ide_core::error::ErrorKind;
@@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let project = host.project(window)?;
let module = project.root.join(module);
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
let (project, module) = (project.clone(), module.clone());
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
}
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, prefer_maven, is_maven) = {
let project = project.clone();
let settings = settings.clone();
let (model, external, mut delegated, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
tokio::task::spawn_blocking(move || {
project.java_launch_snapshots.lock().initialize();
let model = load(&project.root, &project.build_cache_dir(), &settings);
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
let prefer_maven = settings.languages.java.maven.delegate_build;
launches.snapshots.lock().initialize();
let root = &scope.root;
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(&project.root, &project.build_cache_dir(), &module),
cache::has_record(root, &scope.cache, &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, prefer_maven, is_maven)
(model, external, delegated, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch(
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
Vec::new()
};
@@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
// The modules of the launches sharing this build also share its classpath probe.
@@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch(
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
let built = if delegated {
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
let outputs = launches.snapshots.lock().build(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
@@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch(
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
let maven_cp = compile::module_classpaths(
&project.root,
&model,
&probed,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
);
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
} else {
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
let cache_dir = project.build_cache_dir();
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
Ok(_) => {}
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch(
}
}
let compile_ms = started.elapsed().as_millis() - lsp_ms;
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
module: PathBuf,
scope: workspace::Scope,
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (root, cache, settings, module, cancel) =
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load(&root, &cache, &settings);
let model = load_launch_model(&scope);
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls(
let build_ms = started.elapsed().as_millis();
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let project = project.clone();
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
Some(server) => {
info.project_root = server.classpath.project_root;
@@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls(
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
let is_maven = model
.maven
.as_ref()
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
if !is_maven {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let classpath = compile::module_classpath(
&project.root,
&model,
&module,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
)?;
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls(
}
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -445,10 +440,10 @@ fn apply_library_classpath(
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
async fn build_members(
project: &std::sync::Arc<crate::Project>,
scope: &std::sync::Arc<workspace::Scope>,
model: &std::sync::Arc<BuildModel>,
module: &Path,
test: bool,
prefer_maven: bool,
waiting: &cache::WaitingGuard,
cancel: &CancellationToken,
) -> IdeResult<Vec<cache::Member>> {
@@ -456,10 +451,11 @@ async fn build_members(
if others.is_empty() {
return Ok(Vec::new());
}
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
let joining = {
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
tokio::task::spawn_blocking(move || {
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -500,8 +496,7 @@ fn joining_launches(
others
.into_iter()
.filter(|o| {
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
let is_maven = is_maven_module(root, model, &o.module);
o.test == test
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
+24
View File
@@ -64,6 +64,30 @@ pub(super) struct Member {
pub rebuild_on_jdt_errors: bool,
}
/// Launches share a build only within the same workspace project's cache.
#[derive(Default)]
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
pub(in crate::ops) struct Launches {
pub waiting: Waiting,
pub snapshots: Mutex<Session>,
}
impl Sessions {
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
self.0
.lock()
.entry(cache.to_owned())
.or_insert_with(|| {
Arc::new(Launches {
waiting: Waiting::default(),
snapshots: Mutex::new(Session::new(cache.to_owned())),
})
})
.clone()
}
}
/// Java launches from their start until their build: one launch's Maven run also builds
/// the modules of launches still waiting (configurations started together, #3971).
#[derive(Default)]
+6 -2
View File
@@ -140,7 +140,10 @@ pub struct WorkspaceMember {
}
/// The workspace projects outside the window's project folder, for Mark Directory as there.
#[command(trust = always)]
/// Each member's `for_project().layer(Project)` re-parses both settings layers and validates the
/// merged tree against `Settings`; that stack-hungry work must not run on the IPC (main) thread,
/// whose 1 MiB stack overflows on project open (STATUS_STACK_OVERFLOW).
#[command(trust = always, desktop_body = spawn)]
pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<WorkspaceMember>> {
let project = host.project(window)?;
Ok(project
@@ -156,7 +159,8 @@ pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<Wor
/// Sets a `projectStructure.*` key in the settings of `root`, a project attached to the window's
/// project (Mark Directory as there). Every open window holding that project follows.
#[command(trust = always)]
/// Like `project_workspace_members`, its `for_project` settings re-parse runs off the IPC thread.
#[command(trust = always, desktop_body = spawn)]
pub fn project_workspace_member_set(
host: &Arc<Host>,
window: &str,
+17 -13
View File
@@ -67,20 +67,24 @@ fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
roots
}
/// Every mapping source of the project, for the request-path index.
pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
/// Every mapping source of the project, for the request-path index. Walks the whole tree,
/// so it runs on the blocking pool.
pub async fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
let project = host.project(window)?;
let mut out = Vec::new();
for root in scan_roots(&project.root, project.content_roots()) {
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
}
out.sort_by(|a, b| a.path.cmp(&b.path));
out.dedup_by(|a, b| a.path == b.path);
match out.len() {
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
}
Ok(out)
host.blocking(move || {
let mut out = Vec::new();
for root in scan_roots(&project.root, project.content_roots()) {
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
}
out.sort_by(|a, b| a.path.cmp(&b.path));
out.dedup_by(|a, b| a.path == b.path);
match out.len() {
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
}
Ok(out)
})
.await
}
#[cfg(test)]
+4 -1
View File
@@ -242,7 +242,10 @@ fn settings_only(
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
if jvm && member.is_some() && config.cwd.is_none() {
config.cwd = Some(owner.into());
} else if config.extras.module.is_none() && !jvm {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
+7 -2
View File
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
@@ -139,7 +139,7 @@ pub(crate) fn search_project(
&remaining,
Some(&filter),
Some(&literals),
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback },
cancel,
&|mut file| {
if let Some(prefix) = &prefix {
@@ -188,6 +188,11 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
#[test]
fn search_leaves_unread_the_texts_the_parser_does_not_take() {
assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES);
}
#[test]
fn masks_follow_the_root_they_search() {
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
+4 -12
View File
@@ -51,10 +51,8 @@ pub struct Project {
pub(crate) member_excludes: MemberExcludes,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Superseded launch snapshots retained until this project session ends.
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
/// Java launches waiting for their build, which can share one Maven run.
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
/// Pending launches and retained snapshots, scoped to each workspace project.
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Database tool window: data sources and their connections.
@@ -641,10 +639,7 @@ impl Host {
detected_roots,
member_excludes,
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
@@ -891,10 +886,7 @@ impl Host {
detected_roots: Arc::default(),
member_excludes: Arc::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
+4 -4
View File
@@ -24,8 +24,8 @@ fn remember_codex_modes(data: &Path, root: &Path) {
std::fs::write(data.join("agents/models.json"), modes.to_string()).unwrap();
}
fn codex_mode(host: &Host) -> Option<String> {
let providers = ide_host::ops::agent::agent_providers(host, "main").unwrap();
async fn codex_mode(host: &Host) -> Option<String> {
let providers = ide_host::ops::agent::agent_providers(host, "main").await.unwrap();
let codex = providers.into_iter().find(|p| p.id == "codex").expect("codex is listed");
codex.config.into_iter().find(|o| o.id == "mode").and_then(|o| o.current)
}
@@ -54,10 +54,10 @@ async fn new_tasks_start_asking_for_approval_when_the_user_chose_so() {
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
assert_eq!(codex_mode(&host).as_deref(), Some("ask"));
assert_eq!(codex_mode(&host).await.as_deref(), Some("ask"));
// The default keeps starting new tasks without approvals.
std::fs::remove_file(config.join("settings.toml")).unwrap();
host.project("main").unwrap().settings.reload();
assert_eq!(codex_mode(&host).as_deref(), Some("full-access"));
assert_eq!(codex_mode(&host).await.as_deref(), Some("full-access"));
}
+5 -5
View File
@@ -30,8 +30,8 @@ fn open(host: &Host, tmp: &tempfile::TempDir) {
host.open_project("main", &root).unwrap();
}
fn env_of(host: &Host, id: &str) -> BTreeMap<String, String> {
let providers = ide_host::ops::agent::agent_providers(host, "main").unwrap();
async fn env_of(host: &Host, id: &str) -> BTreeMap<String, String> {
let providers = ide_host::ops::agent::agent_providers(host, "main").await.unwrap();
providers.into_iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}")).env
}
@@ -60,8 +60,8 @@ async fn agent_environment_values_stay_out_of_agent_files() {
let host = self::host(tmp.path());
open(&host, &tmp);
assert_eq!(env_of(&host, "claude"), env);
assert_eq!(env_of(&host, "mine"), env);
assert_eq!(env_of(&host, "claude").await, env);
assert_eq!(env_of(&host, "mine").await, env);
ide_host::ops::agent::remove_custom_agent(&host, "main", "mine".into()).unwrap();
ide_host::ops::agent::agent_set_env(&host, "main", "claude".into(), BTreeMap::new()).unwrap();
assert_eq!(host.agent_secrets.keys("agent/"), Vec::<String>::new());
@@ -81,6 +81,6 @@ async fn values_in_agent_files_move_to_the_credential_store() {
let host = host(tmp.path());
open(&host, &tmp);
assert_eq!(files_containing(tmp.path(), VALUE), Vec::<PathBuf>::new());
assert_eq!(env_of(&host, "mine"), BTreeMap::from([("TOKEN".to_owned(), VALUE.to_owned())]));
assert_eq!(env_of(&host, "mine").await, BTreeMap::from([("TOKEN".to_owned(), VALUE.to_owned())]));
host.close_project("main");
}
+3 -2
View File
@@ -71,9 +71,10 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
}
/// The language server's Maven import roots once `ready` holds: a settings change refreshes them in
/// the background.
/// the background. The deadline is generous because a loaded CI runner can take well over a few
/// seconds to re-import.
async fn import_roots(host: &Host, ready: impl Fn(&[std::path::PathBuf]) -> bool) -> Vec<std::path::PathBuf> {
for _ in 0..200 {
for _ in 0..600 {
let roots = host.project("main").unwrap().lsp.jdtls_import_roots();
if ready(&roots) {
return roots;
+7
View File
@@ -74,6 +74,13 @@ async fn serves_projects_files_documents_search_and_runs() {
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
let scratch_path = base.join("data/scratches");
assert!(!scratch_path.exists());
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
assert!(scratch_path.is_dir());
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
+101
View File
@@ -6,6 +6,107 @@ use std::{
time::Duration,
};
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn java_launch_builds_the_owning_workspace_reactor() {
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::{fs, os::unix::fs::PermissionsExt};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let config_dir = base.join("config");
let primary = base.join("primary");
let sibling = base.join("spring");
let nested = primary.join("nested");
let roots = [&primary, &sibling, &nested];
for (i, root) in roots.into_iter().enumerate() {
fs::create_dir_all(root.join("app")).unwrap();
fs::write(
root.join("pom.xml"),
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
)
.unwrap();
fs::write(
root.join("app/pom.xml"),
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
)
.unwrap();
let wrapper = root.join("mvnw");
fs::write(
&wrapper,
r#"#!/bin/sh
set -eu
printf '%s\n' "$*" >> calls
mkdir -p app/target/classes
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
scope=runtime
for arg in "$@"; do
case "$arg" in
-Dmdep.includeScope=*) scope="${arg#*=}";;
esac
done
for arg in "$@"; do
case "$arg" in
-Dmdep.outputFile=*)
touch "app/$scope.jar"
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
esac
done
"#,
)
.unwrap();
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
SettingsStore::load(&config_dir, Some(root))
.set(
SettingsScope::Project,
"languages.java.maven.activeProfiles",
serde_json::json!(format!("member-{i}")),
)
.unwrap();
}
// Exercise the build-tool classpath fallback without starting an installed server.
let global = SettingsStore::load(&config_dir, None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(HostConfig {
config_dir,
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,
});
for root in roots {
host.trust.decide(root, true, false).unwrap();
}
host.open_project("main", &primary).unwrap();
for root in [&sibling, &nested] {
ops::project::attach_workspace(&host, "main", root).unwrap();
}
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
let temp = tempfile::tempdir().unwrap();
+34 -7
View File
@@ -11,7 +11,7 @@
use ide_core::{Range, SymbolKind};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
/// Bit set of the (lower-cased) ASCII letters/digits/punctuation present in a
@@ -588,6 +588,9 @@ pub(crate) struct IndexData {
free: Vec<u32>,
pub file_count: u32,
pub symbol_count: u32,
/// Full passes over `by_path` made to remove folders.
#[cfg(test)]
pub key_scans: usize,
}
impl IndexData {
@@ -792,9 +795,15 @@ impl IndexData {
Some(old)
}
/// Removes every file at or below `dir`; returns their paths.
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<PathBuf> {
let doomed: Vec<PathBuf> = self.by_path.keys().filter(|p| p.starts_with(dir)).cloned().collect();
/// Removes every file at or below any of `dirs` in a single pass over the
/// indexed paths; returns their paths.
pub(crate) fn remove_trees(&mut self, dirs: &HashSet<PathBuf>) -> Vec<PathBuf> {
#[cfg(test)]
{
self.key_scans += 1;
}
let doomed: Vec<PathBuf> =
self.by_path.keys().filter(|p| p.ancestors().any(|a| dirs.contains(a))).cloned().collect();
doomed.into_iter().filter(|p| self.remove(p).is_some()).collect()
}
@@ -867,6 +876,10 @@ mod tests {
FileEntry::new(PathBuf::from("/r").join(path), path.to_owned(), record)
}
fn path_set(paths: &[&str]) -> HashSet<PathBuf> {
paths.iter().map(PathBuf::from).collect()
}
fn insert(d: &mut IndexData, path: &str, symbols: usize) {
let (e, s) = entry(path, symbols);
d.insert(e, s);
@@ -944,11 +957,25 @@ mod tests {
d.remove(Path::new("/r/a/b/c.rs"));
assert!(!d.dirs.contains_key("a/b/"));
assert_consistent(&d);
d.remove_tree(Path::new("/r/a"));
d.remove_trees(&path_set(&["/r/a"]));
assert!(d.dirs.is_empty());
assert_consistent(&d);
}
#[test]
fn remove_trees_takes_only_files_below_the_given_folders() {
let mut d = IndexData::default();
for path in ["a/x.rs", "a/b/y.rs", "ab/z.rs", "c/d/w.rs", "c/keep.rs", "top.rs"] {
insert(&mut d, path, 1);
}
let mut gone = d.remove_trees(&path_set(&["/r/a", "/r/a/b", "/r/c/d", "/r/missing"]));
gone.sort();
assert_eq!(gone, ["/r/a/b/y.rs", "/r/a/x.rs", "/r/c/d/w.rs"].map(PathBuf::from));
assert_eq!(d.file_count, 3);
assert!(["/r/ab/z.rs", "/r/c/keep.rs", "/r/top.rs"].iter().all(|p| d.get(Path::new(p)).is_some()));
assert_consistent(&d);
}
#[test]
fn insert_replace_remove_keep_counts() {
let mut d = IndexData::default();
@@ -964,7 +991,7 @@ mod tests {
insert(&mut d, "d.rs", 0);
assert_eq!(d.files.len(), 2, "slot reused");
assert_consistent(&d);
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
assert_eq!(d.remove_trees(&path_set(&["/r/a"])), vec![PathBuf::from("/r/a/b.rs")]);
assert_eq!((d.file_count, d.symbol_count), (1, 0));
let e = d.get(Path::new("/r/d.rs")).unwrap();
assert_eq!((e.name(), e.dir()), ("d.rs", ""));
@@ -1039,7 +1066,7 @@ mod tests {
insert(&mut d, "a/b/two.rs", 3);
insert(&mut d, "a/three.rs", 1);
insert(&mut d, "elsewhere/four.rs", 1);
assert_eq!(d.remove_tree(Path::new("/r/a")).len(), 3);
assert_eq!(d.remove_trees(&path_set(&["/r/a"])).len(), 3);
assert_consistent(&d);
assert_eq!(d.hot.rows.iter().filter(|r| r.live).count(), 1);
assert!(d.hot.row(0).is_none(), "removed slots have no live row");
+73 -5
View File
@@ -900,16 +900,21 @@ impl Shared {
// Removals first; a path removed then re-created shows up in `changed` too.
let mut deletes = Vec::new();
// Paths that are not indexed files: removed directories (or files that were never indexed).
let mut gone_dirs = HashSet::new();
for path in removed {
if path.exists() {
changed.push(path);
continue;
}
let mut d = self.data.write();
let gone = match d.remove(&path) {
Some(_) => vec![path],
None => d.remove_tree(&path),
};
if self.data.write().remove(&path).is_some() {
deletes.extend(filter.store_key(&path));
} else {
gone_dirs.insert(path);
}
}
if !gone_dirs.is_empty() {
let gone = self.data.write().remove_trees(&gone_dirs);
deletes.extend(gone.iter().filter_map(|p| filter.store_key(p)));
}
if !deletes.is_empty() {
@@ -1156,6 +1161,69 @@ mod metric_tests {
)
}
#[test]
fn removed_subtree_costs_one_key_scan_per_batch() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let shared = shared(&root);
let mut batch = std::collections::BTreeSet::new();
for i in 0..40 {
let sub = root.join("gone").join(format!("p{}", i / 10));
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join(format!("f{i}.txt")), "x").unwrap();
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
}
std::fs::write(root.join("keep.txt"), "x").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 41);
std::fs::remove_dir_all(root.join("gone")).unwrap();
shared.data.write().key_scans = 0;
// The watcher's batches are sorted: each directory precedes its children.
shared.process(vec![Job::Removed(batch.into_iter().collect())]);
let data = shared.data.read();
assert_eq!(data.file_count, 1);
assert!(data.get(&root.join("keep.txt")).is_some());
assert!(data.key_scans <= 1, "{} full key scans for one removed subtree", data.key_scans);
}
#[test]
fn batch_removal_handles_files_dirs_recreated_and_unknown_paths() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
let shared = shared(&root);
for rel in ["gone/a.txt", "gone/deep/b.txt", "kept/c.txt", "redo/d.txt", "redo/e.txt", "lone.txt", "stay.txt"] {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "x").unwrap();
}
shared.scan(None, None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 7);
std::fs::remove_dir_all(root.join("gone")).unwrap();
std::fs::remove_file(root.join("lone.txt")).unwrap();
std::fs::remove_file(root.join("redo/e.txt")).unwrap();
let outside = root.join("never/indexed/f.txt");
let removed = [
root.join("gone/deep/b.txt"),
root.join("gone"),
root.join("gone/deep"),
root.join("lone.txt"),
root.join("redo"),
root.join("redo/e.txt"),
root.join("stay.txt"),
outside,
];
shared.process(vec![Job::Removed(removed.to_vec())]);
let data = shared.data.read();
let mut left: Vec<_> = data.paths().map(|p| p.strip_prefix(&root).unwrap().to_owned()).collect();
left.sort();
// `redo` and `stay.txt` still exist: they are re-read, not dropped.
assert_eq!(left, ["kept/c.txt", "redo/d.txt", "stay.txt"].map(PathBuf::from));
}
#[test]
fn streaming_scan_counts_full_batch_and_tail() {
let dir = tempfile::tempdir().unwrap();
+8 -1
View File
@@ -646,7 +646,10 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Generated Maven sources are attached first, so that recheck sees them.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -663,6 +666,10 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
+30 -3
View File
@@ -635,11 +635,12 @@ async fn java_sharing_cancels_a_retiring_initialize_before_starting_its_replacem
let old = state.peer();
shared.store(true, Ordering::SeqCst);
let switched = tokio::time::timeout(Duration::from_secs(2), h.mgr.reconfigure()).await;
let closed_before_response = old.is_closed();
gate.open();
switched.expect("initialize cancellation must not wait for its response");
// The retiring transport closes asynchronously; wait for it before releasing
// the initialize response so the ordering check does not race the close.
eventually(|| old.is_closed()).await;
gate.open();
eventually(|| state.requested("initialize").len() == 2).await;
assert!(closed_before_response, "the old transport must close before its initialize response is released");
assert_eq!(h.mgr.servers().len(), 1);
assert_eq!(h.mgr.servers()[0].root.as_ref(), h.root.as_path());
h.mgr.shutdown_all().await;
@@ -3164,6 +3165,32 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
eventually(|| refreshed() == expected).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_semantic_tokens() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
let refreshes = || {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(refreshes(), 0);
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
let mut caps = incremental_caps();
+129 -6
View File
@@ -12,11 +12,17 @@ use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
use std::time::{Duration, Instant};
const BATCH_INTERVAL: Duration = Duration::from_millis(8);
const BATCH_BYTES: usize = 64 * 1024;
/// Size of one pipe read, so the most one queued [`Msg::Data`] holds.
const READ_BUF: usize = 16 * 1024;
/// Chunks the readers may queue ahead of the pump (at most `OUTPUT_QUEUE_CHUNKS * READ_BUF`,
/// 2 MiB). A process printing faster than the console takes its output waits on its full
/// pipe, as it would on a terminal, instead of piling the flood up in memory here.
const OUTPUT_QUEUE_CHUNKS: usize = 128;
/// After the main process exits, how long to wait for pipes still held by
/// orphaned descendants before reporting the exit.
const EXIT_DRAIN: Duration = Duration::from_millis(500);
@@ -112,6 +118,12 @@ enum Msg {
Exited(Exit),
}
/// The queue from the readers (and the waiter) to the pump: bounded, so the readers wait
/// while the pump is behind.
fn output_queue() -> (SyncSender<Msg>, mpsc::Receiver<Msg>) {
mpsc::sync_channel(OUTPUT_QUEUE_CHUNKS)
}
/// The program and arguments actually executed, plus the echoed command line.
pub(crate) struct Invocation {
pub program: PathBuf,
@@ -484,7 +496,7 @@ impl ProcessManager {
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = mpsc::channel();
let (tx, rx) = output_queue();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let result = (|| -> std::io::Result<()> {
@@ -631,7 +643,7 @@ impl ProcessManager {
self.register(entry.clone());
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = mpsc::channel();
let (tx, rx) = output_queue();
let result = spawn_reader(
id,
Stream::Stdout,
@@ -824,7 +836,7 @@ fn run_followup(
config: &RunConfig,
cwd: &Path,
entry: &Entry,
tx: &Sender<Msg>,
tx: &SyncSender<Msg>,
) -> std::io::Result<ExitStatus> {
let mut pid = entry.pid.lock();
if entry.stopping.load(Ordering::Acquire) {
@@ -1106,16 +1118,19 @@ fn kill_tree(entry: &Entry, pid: u32, _force: bool) {
.status();
}
/// Reads `pipe` into `tx` until EOF. It waits in `send` while the pump is a full queue behind
/// (the process then waits on its pipe). The pump dropping its receiver fails the `send`
/// and ends the reader, so no reader stays blocked once the pump is gone.
fn spawn_reader(
id: RunId,
stream: Stream,
mut pipe: impl Read + Send + 'static,
tx: Sender<Msg>,
tx: SyncSender<Msg>,
#[cfg(unix)] mut wait_readable: Option<Box<dyn FnMut() -> std::io::Result<()> + Send>>,
) -> std::io::Result<()> {
let label = if stream == Stream::Stdout { "out" } else { "err" };
std::thread::Builder::new().name(format!("openidea-run-{label}-{}", id.0)).spawn(move || {
let mut buf = vec![0u8; 16 * 1024];
let mut buf = vec![0u8; READ_BUF];
loop {
match pipe.read(&mut buf) {
Ok(0) => break,
@@ -1424,6 +1439,7 @@ fn input_writer(
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;
#[cfg(unix)]
#[test]
@@ -1569,4 +1585,111 @@ mod tests {
assert_eq!(resolve_program("./gradlew", cwd, &config, true), cwd.join("./gradlew"));
assert_eq!(resolve_program(".venv/bin/python", cwd, &config, false), cwd.join(".venv/bin/python"));
}
/// A pipe stand-in that counts the bytes taken from it.
#[cfg(unix)]
struct Counted<R> {
inner: R,
taken: Arc<AtomicUsize>,
}
#[cfg(unix)]
impl<R: Read> Read for Counted<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
self.taken.fetch_add(n, Ordering::SeqCst);
Ok(n)
}
}
#[cfg(unix)]
#[test]
fn a_slow_pump_holds_a_flooding_process_back_instead_of_queueing_its_output() {
const LINES: usize = 2_000_000;
// (Not `seq`: macOS prints large numbers in exponent form.)
let mut child = Command::new("awk")
.arg(format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}"))
.stdout(Stdio::piped())
.spawn()
.expect("awk");
let taken = Arc::new(AtomicUsize::new(0));
let pipe = Counted { inner: child.stdout.take().unwrap(), taken: taken.clone() };
let (tx, rx) = output_queue();
spawn_reader(RunId::next(), Stream::Stdout, pipe, tx, None).unwrap();
let (mut received, mut peak, mut all) = (0usize, 0usize, Vec::new());
loop {
match rx.recv_timeout(Duration::from_secs(60)) {
Ok(Msg::Data(stream, bytes)) => {
assert!(stream == Stream::Stdout);
// Read from the pipe but not yet handled: the queue, plus the chunk the
// reader holds while it waits for room, plus the one just received.
peak = peak.max(taken.load(Ordering::SeqCst) - received);
received += bytes.len();
all.extend_from_slice(&bytes);
// A console that cannot keep up with the process.
std::thread::sleep(Duration::from_millis(1));
}
Ok(Msg::Exited(_)) => unreachable!("only the waiter sends the exit"),
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the reader stalled"),
}
}
assert!(child.wait().unwrap().success());
let bound = (OUTPUT_QUEUE_CHUNKS + 2) * READ_BUF;
assert!(peak <= bound, "{peak} bytes queued ahead of the pump, more than {bound}");
let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect();
assert!(all == expected.as_bytes(), "the output arrived incomplete or out of order");
}
/// Endless output (cut at a size an unbounded queue could still hold in a test) that
/// reports when it is dropped, which is when the reader thread owning it ends.
struct Endless {
served: Arc<AtomicUsize>,
gone: mpsc::Sender<()>,
}
impl Read for Endless {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.served.load(Ordering::SeqCst) >= 8 * OUTPUT_QUEUE_CHUNKS {
return Ok(0);
}
self.served.fetch_add(1, Ordering::SeqCst);
buf.fill(b'x');
Ok(buf.len())
}
}
impl Drop for Endless {
fn drop(&mut self) {
let _ = self.gone.send(());
}
}
#[test]
fn a_reader_blocked_on_a_full_queue_ends_when_the_pump_is_gone() {
let served = Arc::new(AtomicUsize::new(0));
let (gone_tx, gone) = mpsc::channel();
let (tx, rx) = output_queue();
spawn_reader(
RunId::next(),
Stream::Stdout,
Endless { served: served.clone(), gone: gone_tx },
tx,
#[cfg(unix)]
None,
)
.unwrap();
// A pump that takes nothing: the queue fills and the reader holds one more chunk.
let deadline = Instant::now() + Duration::from_secs(30);
while served.load(Ordering::SeqCst) < OUTPUT_QUEUE_CHUNKS + 1 {
assert!(Instant::now() < deadline, "the reader never filled the queue");
std::thread::sleep(Duration::from_millis(1));
}
// Time for a reader that does not wait to run ahead.
std::thread::sleep(Duration::from_millis(100));
assert_eq!(served.load(Ordering::SeqCst), OUTPUT_QUEUE_CHUNKS + 1, "the reader ran past the full queue");
assert!(gone.try_recv().is_err(), "the reader ended while its pump was still there");
drop(rx);
gone.recv_timeout(Duration::from_secs(30)).expect("the reader stayed blocked after the pump was gone");
}
}
+67
View File
@@ -278,6 +278,73 @@ fn large_output_is_complete_and_batched() {
assert!(chunks.lock().len() < 3000);
}
#[test]
fn a_console_slower_than_the_process_still_gets_all_output_in_order_and_the_exit() {
const LINES: usize = 1_000_000;
let h = harness();
let chunks: Chunks = Arc::default();
let sink = chunks.clone();
let info =
h.pm.start(
h.root.path(),
&cfg("t:slow-console", "awk", &[&format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}")]),
&StartOptions::default(),
h.sink.clone(),
Box::new(move |c| {
sink.lock().push(c);
std::thread::sleep(Duration::from_millis(1));
}),
)
.expect("start");
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(120)), Some(0));
let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect();
assert!(text(&chunks, stdout) == expected, "the output arrived incomplete or out of order");
// The exit is reported after the output, never before the last of it.
let all = chunks.lock();
assert!(matches!(all.last(), Some(OutputChunk::System { text }) if text.contains("exit code 0")));
}
#[test]
fn stop_ends_a_flooding_run_whose_console_stalled() {
let h = harness();
let chunks: Chunks = Arc::default();
let sink = chunks.clone();
let (stalled_tx, stalled) = mpsc::channel();
let (resume_tx, resume) = mpsc::channel::<()>();
// The first output blocks the console until `resume_tx` is dropped.
let resume = Mutex::new(Some(resume));
let info =
h.pm.start(
h.root.path(),
&cfg("t:stalled-console", "yes", &[]),
&StartOptions::default(),
h.sink.clone(),
Box::new(move |c| {
let output = matches!(c, OutputChunk::Stdout { .. });
sink.lock().push(c);
if output && let Some(resume) = resume.lock().take() {
let _ = stalled_tx.send(());
let _ = resume.recv();
}
}),
)
.expect("start");
stalled.recv_timeout(Duration::from_secs(10)).expect("no output reached the console");
// The pipe and the queue behind the stalled console fill up and `yes` waits on its pipe.
std::thread::sleep(Duration::from_millis(300));
h.pm.stop(info.id).unwrap();
let pid = i32::try_from(info.pid.expect("pid")).unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
while alive(pid) {
assert!(Instant::now() < deadline, "the stalled run survived Stop");
std::thread::sleep(Duration::from_millis(20));
}
drop(resume_tx);
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(30)), Some(130));
let out = text(&chunks, stdout);
assert!(!out.is_empty() && out.lines().all(|l| l == "y"), "the output was damaged");
}
#[test]
fn relative_program_resolves_against_cwd() {
let h = harness();
+59 -4
View File
@@ -1365,8 +1365,15 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
_ => {}
}
}
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server.
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
let vue_pkg = vue::server_package(&vue_command, &search_path());
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server, whose plugin
// host goes away with it. The Vue language server's `@vue/typescript-plugin` loads into
// that host, so a Vue project that has the server keeps the vtsls route and its `.vue`
// support; elsewhere the native server still wins.
if matches!(name, "vtsls" | "typescript-language-server")
&& !(name == "vtsls" && vue_pkg.is_some() && (vue::vue_project(server_root) || vue::vue_project(root)))
&& let Some(native) = native_tsdk(server_root, s).or_else(|| native_tsdk(root, s))
{
cfg.command = native.to_string_lossy().into_owned();
@@ -1380,10 +1387,8 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
cfg.tsserver_project = false;
return;
}
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
if name == "vtsls"
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
&& let Some(vue) = vue_pkg
{
let plugin = vue::tsserver_plugin(&vue);
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
@@ -2453,6 +2458,56 @@ mod maven_linkage_tests {
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
}
#[test]
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
// The Vue server, as the hybrid block finds it through the tool's package dir.
let bin = root.join("tools/node_modules/.bin/vue-language-server");
let pkg = root.join("tools/node_modules/@vue/language-server/package.json");
std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
std::fs::create_dir_all(pkg.parent().unwrap()).unwrap();
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
std::fs::write(&pkg, "{}").unwrap();
let mut s = Settings::default();
s.tools
.insert(vue::SERVER.into(), ide_core::settings::ToolSettings { path: bin.to_string_lossy().into_owned() });
// A Vue project whose TypeScript is 7: the native executable would take over.
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^3.0.0"}}"#).unwrap();
let modules = root.join("node_modules");
let os = match std::env::consts::OS {
"macos" => "darwin",
"windows" => "win32",
os => os,
};
let arch = match std::env::consts::ARCH {
"aarch64" => "arm64",
"x86_64" => "x64",
arch => arch,
};
std::fs::create_dir_all(modules.join("typescript/lib")).unwrap();
std::fs::write(modules.join("typescript/package.json"), r#"{"name":"typescript","version":"7.0.2"}"#).unwrap();
let native = modules.join(format!("@typescript/typescript-{os}-{arch}/lib")).join(crate::exe("tsc"));
std::fs::create_dir_all(native.parent().unwrap()).unwrap();
std::fs::write(&native, "").unwrap();
s.languages.typescript.version = "workspace".into();
// vtsls hosts the Vue plugin's tsserver; the native server cannot, so it loses.
let mut cfg = crate::tests::server("vtsls");
configure_server(&mut cfg, root, root, &s);
assert_eq!(cfg.command, "vtsls");
assert_eq!(
serde_json::to_value(cfg.initialization_options).unwrap().pointer("/vtsls/tsserver/globalPlugins/0/name"),
Some(&json!("@vue/typescript-plugin"))
);
assert_eq!(cfg.tsserver_project_extras.extensions, [vue::EXTENSION.to_string()]);
// typescript-language-server gets no plugin route: the native server still applies.
let mut cfg = crate::tests::server("typescript-language-server");
configure_server(&mut cfg, root, root, &s);
assert_eq!(Path::new(&cfg.command), native);
}
#[test]
fn hybrid_without_a_config_keeps_type_acquisition_and_plain_vtsls_stays_default() {
let tmp = tempfile::tempdir().unwrap();
+10
View File
@@ -42,6 +42,16 @@ pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
package_dir(&find_command(command, path)?, PACKAGE)
}
/// Whether `root`'s manifest depends on Vue or `@vue/cli-service`, i.e. it is a Vue project.
/// The tsserver plugin host that `vtsls` carries cannot be loaded into the native TS7
/// server, so this decides whether the tsserver route stays for a Vue project.
pub(crate) fn vue_project(root: &Path) -> bool {
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else {
return false;
};
package_dependencies(&manifest).iter().any(|d| d == "vue" || d == CLI_SERVICE)
}
/// vtsls `globalPlugins` entry loading the Vue plugin shipped with `package`.
pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
serde_json::json!({
+68 -21
View File
@@ -24,6 +24,11 @@ const CANCEL_CHECK_LINES: u32 = 256;
/// How many matches a file keeps before claiming them from the shared budget: each file
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
const CLAIM_BATCH: u32 = 64;
/// Bytes at the start of a text that the searcher checks for binary content up front.
const BINARY_HEAD_LEN: usize = 64 * 1024;
/// Files longer than this hold no text the parser takes, whatever their encoding (UTF-16 halves
/// the bytes of ASCII text, nothing else comes close): their comments and strings are not looked for.
const MAX_LITERALS_FILE_BYTES: u64 = 2 * crate::MAX_LITERALS_TEXT_BYTES as u64;
pub(crate) struct Request<'a> {
pub root: &'a Path,
@@ -63,9 +68,11 @@ impl Control<'_> {
/// Also polls the cancellation token (which takes a lock).
fn should_stop(&self) -> bool {
if self.stopped() {
return true;
}
self.stopped() || self.cancel_requested()
}
/// Polls the cancellation token only: a search stopped by its match limit is not cancelled.
fn cancel_requested(&self) -> bool {
if self.cancel.is_cancelled() {
self.cancelled.store(true, Relaxed);
self.stop.store(true, Relaxed);
@@ -302,22 +309,37 @@ impl Ctx<'_> {
{
return;
}
// The search context needs the whole text to find comments and string literals.
// The search context needs the whole text to find comments and string literals. A file
// whose text is past the longest the parser takes has none, so it is not read for them.
let in_context = match self.literals {
Some(literals) => {
Some(literals) => 'context: {
let text = match (self.text.overlay)(path) {
Some(text) => text,
None => match std::fs::read(path) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => text,
// Binary content has nothing to classify.
Err(e) => match (self.text.decode)(path, e.as_bytes()) {
Some(text) => text,
None => return,
None => {
match std::fs::metadata(path) {
Ok(meta) if meta.len() > MAX_LITERALS_FILE_BYTES => {
if self.context.needs_literals() {
return;
}
break 'context None;
}
Ok(_) => {}
Err(_) => return,
}
match std::fs::read(path) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => text,
// Binary content has nothing to classify.
Err(e) => {
match ide_vfs::decode_text(e.as_bytes(), (self.text.fallback)(path).as_deref()) {
Some(text) => text,
None => return,
}
}
},
},
Err(_) => return,
},
Err(_) => return,
}
}
};
let ranges = literals(path, &text);
if ranges.is_none() && self.context.needs_literals() {
@@ -354,7 +376,8 @@ impl Ctx<'_> {
}
/// Streams the file's bytes; a file that turns out not to be UTF-8 (GBK,
/// UTF-16 …) is searched again in the text `decode` gives it.
/// UTF-16 …) is searched again in its text decoded as the editor opens it,
/// which is decoded as it is read.
fn search_disk<'s>(
&'s self,
path: &Path,
@@ -362,7 +385,7 @@ impl Ctx<'_> {
searcher: &mut Searcher,
sink: &mut FileSink<'s>,
) -> io::Result<()> {
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl });
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: true });
let result = searcher.search_reader(matcher, &mut reader, &mut *sink);
// NUL bytes in the head of UTF-16 text stop the byte search; later ones mark binary.
let decode = if sink.binary {
@@ -374,14 +397,29 @@ impl Ctx<'_> {
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
return result;
}
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
// Only cancellation ends the reading: a search that hit the match limit still fills its claim.
let open = || Ok(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: false });
let Some(text) = ide_vfs::decode_stream(open, (self.text.fallback)(path).as_deref())? else {
sink.binary = true;
return Ok(());
};
let mut text = text;
// Text held whole gets the searcher's binary check only on its first 64 KiB and on the
// lines that match; this keeps that for the text read piece by piece.
let mut head = Vec::with_capacity(BINARY_HEAD_LEN);
(&mut text).take(BINARY_HEAD_LEN as u64).read_to_end(&mut head)?;
if head.contains(&0) {
sink.binary = true;
return Ok(());
}
let claimed = sink.claimed;
*sink = FileSink::new(matcher, &self.ctl, None);
sink.claimed = claimed;
searcher.search_slice(matcher, text.as_bytes(), sink)
sink.binary_in_matches = true;
searcher.set_binary_detection(BinaryDetection::none());
let result = searcher.search_reader(matcher, io::Cursor::new(head).chain(text), sink);
searcher.set_binary_detection(BinaryDetection::quit(0));
result
}
}
@@ -404,6 +442,8 @@ struct FileSink<'a> {
/// file is searched again under the claim of its byte search.
claimed: u32,
binary: bool,
/// A NUL byte in a matching line marks the file binary (the searcher's own check is off).
binary_in_matches: bool,
ticks: u32,
/// Scratch buffers reused across lines.
found: Vec<(usize, usize)>,
@@ -425,6 +465,7 @@ impl<'a> FileSink<'a> {
count: 0,
claimed: 0,
binary: false,
binary_in_matches: false,
ticks: 0,
found: Vec::new(),
ranges: Vec::new(),
@@ -467,6 +508,10 @@ impl Sink for FileSink<'_> {
type Error = io::Error;
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
if self.binary_in_matches && memchr::memchr(0, m.bytes()).is_some() {
self.binary = true;
return Ok(false);
}
self.ticks += 1;
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
// Unless cancelled, a decoded file still fills the claim its byte search took.
@@ -534,15 +579,17 @@ impl Sink for FileSink<'_> {
}
}
/// Aborts disk reads once the search is stopped or cancelled.
/// Aborts disk reads once the search is cancelled, or with `hard` once it is stopped.
struct StopReader<'a, R> {
inner: R,
ctl: &'a Control<'a>,
hard: bool,
}
impl<R: Read> Read for StopReader<'_, R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.ctl.should_stop() {
let stop = if self.hard { self.ctl.should_stop() } else { self.ctl.cancel_requested() };
if stop {
return Err(io::Error::other("search stopped"));
}
self.inner.read(buf)
+14 -6
View File
@@ -112,8 +112,14 @@ impl SearchContext {
}
}
/// The longest file text, in bytes, that is searched for comments and string literals: the
/// parser's limit (`ide_language::MAX_PARSE_BYTES`), above which a [`Literals`] finds none.
/// The search leaves a longer text unread by it.
pub const MAX_LITERALS_TEXT_BYTES: usize = 16 * 1024 * 1024;
/// Comments and string literals of a file's text (sorted, non-overlapping),
/// or `None` when its language has no syntax tree.
/// or `None` when its language has no syntax tree or the text is longer than
/// [`MAX_LITERALS_TEXT_BYTES`].
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -198,21 +204,23 @@ pub struct SearchSummary {
/// Text of unsaved open documents takes precedence over disk content.
pub type Overlay<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
/// Text of a file whose bytes are not UTF-8 (GBK, UTF-16 …); `None` for binary content.
pub type Decode<'a> = &'a (dyn Fn(&Path, &[u8]) -> Option<String> + Sync);
/// The encoding to read a file with when it is not UTF-8 and the encoding detected for it is not
/// trusted to be right (GBK, UTF-16 …): its label, or `None` to go by what is detected.
pub type FallbackEncoding<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
/// Where a search reads file text from: the open document when `overlay` has
/// it, else the file on disk, decoded by `decode` when it is not UTF-8.
/// it, else the file on disk, decoded as the editor opens it when it is not UTF-8
/// (`fallback` picks the encoding that [`ide_vfs::decode_text`] takes).
#[derive(Clone, Copy)]
pub struct TextSource<'a> {
pub overlay: Overlay<'a>,
pub decode: Decode<'a>,
pub fallback: FallbackEncoding<'a>,
}
impl<'a> TextSource<'a> {
/// Non-UTF-8 files decode as detected, without a configured fallback encoding.
pub fn detected(overlay: Overlay<'a>) -> Self {
Self { overlay, decode: &|_, bytes| ide_vfs::decode_text(bytes, None) }
Self { overlay, fallback: &|_| None }
}
}
+159
View File
@@ -0,0 +1,159 @@
//! Searching a big file holds a bounded amount of it in memory, whatever its encoding and the
//! search context. Allocations of the whole process are counted, so this is one test with
//! sequential scenarios.
use ide_core::CancellationToken;
use ide_search::{
FileMatches, Literals, SearchContext, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context,
};
use std::alloc::{GlobalAlloc, Layout, System};
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
struct Counting;
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
fn grow(by: usize) {
let live = LIVE.fetch_add(by, Relaxed) + by;
PEAK.fetch_max(live, Relaxed);
}
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size(), Relaxed);
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
if new_size >= layout.size() {
grow(new_size - layout.size());
} else {
LIVE.fetch_sub(layout.size() - new_size, Relaxed);
}
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOC: Counting = Counting;
const MIB: usize = 1024 * 1024;
/// What a search may hold at once: a few buffers of the reader and the decoder. The files are
/// 16 to 40 MiB, so a search that reads one whole (or decodes it whole) is far over.
const BOUND: usize = 4 * MIB;
fn query(context: SearchContext) -> SearchQuery {
SearchQuery {
pattern: "needle".into(),
is_regex: false,
case_sensitive: true,
whole_word: false,
include: vec![],
exclude: vec![],
scope: SearchScope::Project,
max_matches: 1_000_000,
context,
include_excluded: false,
}
}
/// Runs a search and returns its result with the most memory it held over what was live before.
fn measured(
root: &Path,
context: SearchContext,
literals: Option<Literals<'_>>,
) -> (Vec<FileMatches>, SearchSummary, usize) {
let out = Mutex::new(Vec::new());
let before = LIVE.load(Relaxed);
PEAK.store(before, Relaxed);
let summary = search_in_context(
root,
&query(context),
None,
literals,
TextSource::detected(&|_| None),
&CancellationToken::new(),
&|f| out.lock().unwrap().push(f),
)
.unwrap();
let held = PEAK.load(Relaxed).saturating_sub(before);
// The results are in `out` and count against the search; they are small.
(out.into_inner().unwrap(), summary, held)
}
fn write_repeated(path: &Path, bom: &[u8], block: &[u8], size: usize) {
use std::io::Write;
let mut file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
file.write_all(bom).unwrap();
for _ in 0..size / block.len() + 1 {
file.write_all(block).unwrap();
}
}
fn utf16le(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
#[test]
fn searching_a_big_file_holds_a_bounded_part_of_it() {
let block = "2026-11-22 13:00:01 INFO caf\u{e9} \u{4e2d}\u{6587} request ok\n".repeat(50)
+ "2026-11-22 13:00:02 ERROR needle marker found\n";
let latin_text = block.replace(['\u{4e2d}', '\u{6587}'], "x");
let (latin1, _, _) = encoding_rs::WINDOWS_1252.encode(&latin_text);
let (gbk, _, _) = encoding_rs::GBK.encode(&block);
let parsed = Mutex::new(Vec::new());
let literals = |path: &Path, _: &str| {
parsed.lock().unwrap().push(path.file_name().unwrap().to_string_lossy().into_owned());
None
};
let dir = tempfile::tempdir().unwrap();
let mut expected = Vec::new();
for (name, bom, bytes, size) in [
("latin1.log", &b""[..], &latin1[..], 16 * MIB),
("gbk.log", &b""[..], &gbk[..], 16 * MIB),
("utf16.log", &[0xFF, 0xFE][..], &utf16le(&block)[..], 24 * MIB),
("utf8.log", &b""[..], block.as_bytes(), 40 * MIB),
] {
let one = tempfile::tempdir_in(dir.path()).unwrap();
write_repeated(&one.path().join(name), bom, bytes, size);
// Plain search: the byte search, then the decoded search of a non-UTF-8 file.
let (files, summary, held) = measured(one.path(), SearchContext::Any, None);
assert_eq!(files.len(), 1, "{name}");
assert!(summary.matches > 100, "{name}");
assert!(held < BOUND, "{name}: plain search held {} MiB", held / MIB);
expected.push((name, summary.matches, one));
}
// Searching with a context reads a file whole only to find its comments and strings, and
// past the parser's limit it has none: the file is searched as it is read.
for (name, matches, one) in &expected {
for context in [SearchContext::ExceptComments, SearchContext::ExceptCommentsAndStringLiterals] {
let (files, summary, held) = measured(one.path(), context, Some(&literals));
if *name == "utf8.log" {
assert_eq!(summary.matches, *matches, "{name} {context:?}");
assert_eq!(files.len(), 1);
assert!(held < BOUND, "{name}: {context:?} held {} MiB", held / MIB);
}
}
}
let (_, only_in, held) = measured(expected[3].2.path(), SearchContext::InComments, Some(&literals));
assert_eq!(only_in.matches, 0, "a file without comments has no match in them");
assert!(held < BOUND, "held {} MiB", held / MIB);
let parsed = parsed.into_inner().unwrap();
assert!(parsed.iter().any(|name| name == "gbk.log"), "files within the limit are still analysed");
assert!(!parsed.iter().any(|name| name == "utf8.log"), "a 40 MiB text is never handed to the parser");
}
+1 -2
View File
@@ -890,8 +890,7 @@ fn non_utf8_files_use_the_given_decoder() {
// Text too short to detect reliably decodes with the configured encoding.
let p = project(&[("a.txt", &gbk("中文\n"))]);
let out = Mutex::new(Vec::new());
let decode = |_: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, Some("gbk"));
let source = TextSource { overlay: &|_| None, decode: &decode };
let source = TextSource { overlay: &|_| None, fallback: &|_| Some("gbk".into()) };
ide_search::search_in_context(p.path(), &query("中文"), None, None, source, &CancellationToken::new(), &|f| {
out.lock().unwrap().push(f)
})
+200
View File
@@ -0,0 +1,200 @@
//! Files that are not UTF-8 are decoded while they are searched. Searching the text decoded whole
//! (what an unsaved editor buffer of the file is) is the reference: the matches must be the same.
use ide_core::CancellationToken;
use ide_search::{FileMatches, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context};
use std::path::Path;
use std::sync::Mutex;
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
SearchQuery {
pattern: pattern.into(),
is_regex,
case_sensitive: false,
whole_word: false,
include: vec![],
exclude: vec![],
scope: SearchScope::Project,
max_matches: 1_000_000,
context: Default::default(),
include_excluded: false,
}
}
fn run(root: &Path, q: &SearchQuery, source: TextSource<'_>) -> (Vec<FileMatches>, SearchSummary) {
let out = Mutex::new(Vec::new());
let summary =
search_in_context(root, q, None, None, source, &CancellationToken::new(), &|f| out.lock().unwrap().push(f))
.unwrap();
let mut files = out.into_inner().unwrap();
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
(files, summary)
}
/// The matches of every file in `root`, read from disk and from its whole decoded text.
fn both_ways(root: &Path, q: &SearchQuery, fallback: Option<&str>) -> (String, String) {
let streamed = run(root, q, TextSource { overlay: &|_| None, fallback: &|_| fallback.map(str::to_owned) });
let whole = run(
root,
q,
TextSource {
overlay: &|path| ide_vfs::decode_text(&std::fs::read(path).unwrap(), fallback),
fallback: &|_| None,
},
);
let show = |(files, summary): (Vec<FileMatches>, SearchSummary)| {
format!("{:#?}\nmatches {} limit {}", files, summary.matches, summary.limit_hit)
};
(show(streamed), show(whole))
}
fn first_difference(a: &str, b: &str) -> String {
let (a, b): (Vec<_>, Vec<_>) = (a.lines().collect(), b.lines().collect());
let at = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
format!(
"line {at}:\nstreamed {:?}\nwhole {:?}",
&a[at.saturating_sub(3)..a.len().min(at + 3)],
&b[at.saturating_sub(3)..b.len().min(at + 3)]
)
}
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
let mut bytes = if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
for unit in text.encode_utf16() {
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
}
bytes
}
/// Lines of mixed width: ASCII, accents, CJK, astral characters (surrogate pairs), CRLF.
fn lines(count: usize) -> String {
let mut text = String::new();
for i in 0..count {
match i % 6 {
0 => text.push_str(&format!("{i} needle in plain ascii\n")),
1 => text.push_str(&format!("{i} caf\u{e9} needle cr\u{e8}me\n")),
2 => text.push_str(&format!("{i} \u{4e2d}\u{6587} needle \u{6d4b}\u{8bd5}\n")),
3 => text.push_str(&format!("{i} \u{1f600} needle \u{1f4a9}\n")),
4 => text.push_str(&format!("{i} crlf needle\r\n")),
_ => text.push_str(&format!("{i} nothing here\n")),
}
}
text
}
fn write(dir: &Path, name: &str, bytes: &[u8]) {
std::fs::write(dir.join(name), bytes).unwrap();
}
#[test]
fn decoded_files_give_the_matches_of_their_whole_text() {
let wide = lines(12_000);
let gbk_text = wide.replace(['\u{1f600}', '\u{1f4a9}', '\u{e9}', '\u{e8}'], "");
let latin_text = wide.replace(|c: char| c as u32 > 0xff, "");
let dir = tempfile::tempdir().unwrap();
// (BOM-less UTF-16 is not searched in decoded text, and not covered here: only the byte search sees it.)
// Each file is well past the sizes the decoder reads at a time (64 KiB).
assert!(wide.len() > 250_000);
write(dir.path(), "utf16le_bom.txt", &utf16(&wide, true, false));
write(dir.path(), "utf16be_bom.txt", &utf16(&wide, true, true));
write(dir.path(), "gbk.txt", &encoding_rs::GBK.encode(&gbk_text).0);
write(dir.path(), "latin1.txt", &encoding_rs::WINDOWS_1252.encode(&latin_text).0);
write(dir.path(), "utf8.txt", wide.as_bytes());
let queries = [
query("needle", false),
query("caf\u{e9}", false),
query("\u{1f600}", false),
query("\u{4e2d}\u{6587} needle", false),
query(r"\d+ \S+ needle", true),
query(r"needle\r?$", true),
// A multi-line pattern reads the whole text, however it arrives.
query("needle in plain ascii\n1 caf", false),
SearchQuery { case_sensitive: true, whole_word: true, ..query("needle", false) },
];
for q in &queries {
for fallback in [None, Some("gbk"), Some("windows-1252")] {
let (streamed, whole) = both_ways(dir.path(), q, fallback);
assert!(
streamed == whole,
"{:?} fallback {fallback:?}\n{}",
q.pattern,
first_difference(&streamed, &whole)
);
assert!(streamed.len() > 100, "{:?} found nothing", q.pattern);
}
}
// The match limit keeps the first matches of a file, and files take their share in any order:
// one file at a time.
for name in ["utf16le_bom.txt", "utf16be_bom.txt", "gbk.txt", "latin1.txt"] {
for max_matches in [7, 64, 65, 5_000] {
let q = SearchQuery { max_matches, include: vec![name.into()], ..query("needle", false) };
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{name} limit {max_matches}\n{}", first_difference(&streamed, &whole));
assert!(streamed.contains(&format!("matches {max_matches} limit true")), "{name} {max_matches}");
}
}
}
#[test]
fn decoded_files_keep_their_multibyte_characters_across_every_read_boundary() {
// A character sits on each of the 64 KiB read boundaries, at all alignments.
let dir = tempfile::tempdir().unwrap();
for pad in 0..8usize {
let mut gbk = "x".repeat(64 * 1024 - 5 + pad);
let mut utf16_text = gbk.clone();
for i in 0..40 {
gbk.push_str("\u{4e2d}\u{6587}");
utf16_text.push_str(if i % 2 == 0 { "\u{1f600}" } else { "\u{4e2d}" });
gbk.push_str(&"y".repeat(i % 3));
utf16_text.push_str(&"y".repeat(i % 3));
}
gbk.push_str("yy needle\n");
utf16_text.push_str("yy needle\n");
write(dir.path(), &format!("gbk{pad}.txt"), &encoding_rs::GBK.encode(&gbk).0);
write(dir.path(), &format!("utf16_{pad}.txt"), &utf16(&utf16_text, true, pad % 2 == 0));
write(
dir.path(),
&format!("latin{pad}.txt"),
&[gbk.as_bytes()[..64 * 1024 - 7 + pad].to_vec(), b"\xe9\xe8 needle\n".to_vec()].concat(),
);
}
for pattern in ["needle", "y+ needle", "\u{4e2d}\u{6587}"] {
let q = query(pattern, pattern.contains('+'));
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{pattern}\n{}", first_difference(&streamed, &whole));
assert!(streamed.len() > 100, "{pattern} found nothing");
}
}
#[test]
fn nul_characters_in_decoded_text_mark_it_binary_as_in_the_whole_text() {
// Text held whole is binary when a NUL is in its first 64 KiB or in a line that matches,
// which is not the same as a NUL anywhere.
let text = lines(20_000);
let with_nul = |at: &str| text.replacen(at, &format!("\0{at}"), 1);
let cases = [
("early", with_nul("5 nothing here"), false),
("late in a line that does not match", with_nul("19997 nothing here"), true),
("late in a line that matches", with_nul("19998 needle"), false),
];
for (name, text, found) in cases {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", &utf16(&text, true, false));
let (streamed, whole) = both_ways(dir.path(), &query("needle", false), None);
assert!(streamed == whole, "{name}\n{}", first_difference(&streamed, &whole));
assert_eq!(streamed.contains("a.txt"), found, "{name}");
}
}
#[test]
fn a_file_is_decoded_when_its_search_reaches_the_byte_that_is_not_utf8() {
// Valid UTF-8 up to the last line: the whole file is read as the detected Windows-1252.
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "late.txt", &[lines(1500).as_bytes(), b"caf\xe9 needle\n"].concat());
for q in [query("needle", false), query("caf", false)] {
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{}", first_difference(&streamed, &whole));
assert!(streamed.contains("café"), "decoded as Windows-1252");
}
}
+22
View File
@@ -81,6 +81,12 @@ fn npm_package(tool: &str) -> &str {
}
impl Tools {
/// The IDE's own installation of `tool` outside `node_modules` (Ruff's private virtualenv).
fn managed_executable(&self, tool: &str) -> Option<PathBuf> {
let spec = crate::registry::find(tool)?;
self.exe_in(&crate::managed_bin_dir(&self.root, spec, self.platform)?, spec.commands[0])
}
/// Explicit executable/script, then the nearest project package, then managed tools and PATH.
pub fn formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
self.resolve_formatter_command(tool, file, custom).map_err(|e| e.with_tool(tool))
@@ -100,6 +106,8 @@ impl Tools {
(package_bin(manifest.parent().unwrap(), tool)?, true)
} else if self.root.join(&manifest).is_file() {
(package_bin(&self.root.join(&package), tool)?, true)
} else if let Some(path) = self.managed_executable(tool) {
(path, false)
} else {
(self.which(tool).ok_or_else(|| IdeError::missing_tool(tool))?, false)
};
@@ -241,6 +249,20 @@ mod tests {
assert_eq!(failure.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: false }));
}
#[cfg(unix)]
#[test]
fn a_formatter_the_ide_installed_in_its_virtualenv_is_found() {
let dir = tempfile::tempdir().unwrap();
let tools = Tools::with_paths(dir.path().join("tools"), OsString::new(), crate::platform::Platform::current());
let file = dir.path().join("main.py");
assert!(tools.formatter_command("ruff", &file, None).is_err());
let bin = dir.path().join("tools/ruff/venv/bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(bin.join("ruff"), "").unwrap();
let command = tools.formatter_command("ruff", &file, None).unwrap();
assert_eq!(Path::new(command.get_program()), bin.join("ruff"));
}
#[cfg(unix)]
#[test]
fn stderr_is_preserved_verbatim_even_when_longer_than_four_thousand_characters() {
+15 -5
View File
@@ -478,12 +478,11 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
all.request = None;
all.stop_at = None;
let repo = r.gix()?;
let decorations = decorations(&repo)?;
let (decorations, generation) = r.ref_decorations(&repo)?;
let shallow_vec =
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
let refs = r.log_refs()?;
let key = format!("{}:{refs:?}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let cached = index.views.get(&key).cloned();
let view = if let Some(cached) = cached {
cached
@@ -646,7 +645,7 @@ fn log_indexed(
let repo = r.gix()?;
let shallow: HashSet<ObjectId> =
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default();
let decorations = decorations(&repo)?;
let (decorations, _) = r.ref_decorations(&repo)?;
let range = q.range.as_deref().map(str::trim).filter(|s| !s.is_empty());
let revs: Vec<&str> = q.branch.iter().chain(&q.branches).map(|b| b.trim()).filter(|b| !b.is_empty()).collect();
let ranges: Vec<_> = q.ranges.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
@@ -741,7 +740,7 @@ fn log_indexed_rows(
if tips.is_empty() && range.is_none() && ranges.is_empty() {
return Ok(Vec::new());
}
let decorations = decorations(&repo)?;
let (decorations, _) = r.ref_decorations(&repo)?;
let paths: Vec<String> = q
.path
.iter()
@@ -1406,8 +1405,19 @@ fn tips(repo: &gix::Repository, revs: &[&str]) -> IdeResult<Vec<ObjectId>> {
Ok(tips)
}
#[cfg(test)]
thread_local!(static DECORATION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
/// How many times this thread listed all refs.
#[cfg(test)]
pub(crate) fn decorations_scans() -> usize {
DECORATION_SCANS.get()
}
/// Commit id → decoration labels.
pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId, Vec<String>>> {
#[cfg(test)]
DECORATION_SCANS.set(DECORATION_SCANS.get() + 1);
let mut map: HashMap<ObjectId, Vec<String>> = HashMap::new();
if let Ok(id) = repo.head_id() {
map.entry(id.detach()).or_default().push("HEAD".to_string());
+5 -5
View File
@@ -939,6 +939,7 @@ mod preserve;
mod push_preview;
mod push_report;
mod rebase_editor;
mod ref_decorations;
mod worktree_config;
pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE;
mod incoming;
@@ -1078,6 +1079,7 @@ pub struct Repo {
cli_status: std::sync::atomic::AtomicBool,
automatic_shelf: std::sync::RwLock<Option<shelf::AutomaticShelf>>,
log_index: std::sync::Mutex<log_index::LogIndex>,
ref_decorations: std::sync::Mutex<ref_decorations::RefDecorations>,
log_signatures: std::sync::Mutex<history::LogSignatureCache>,
conflict_mutation: std::sync::Mutex<()>,
amend_recovery: std::sync::Mutex<Option<commit_rewrite::PendingAmend>>,
@@ -1137,11 +1139,9 @@ impl Repo {
/// dirty-scope refresh after a watcher batch. An empty list is the full status.
pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<FileStatus>> {
let _scope = self.execution_scope();
// Restricted Mode starts no program of the repository, and the scoped read is `git status`
// with a pathspec: answer with the full gitoxide status instead.
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
return status::status(self);
}
// Restricted Mode reads this through git too: `cli::command` strips what the repository's
// config could run, and the status call empties its clean/process filters. The full
// gitoxide status it used to answer with walked the whole tree for one changed file.
if paths.is_empty() {
return status::status_paths(self, &[]);
}
+264
View File
@@ -0,0 +1,264 @@
//! Ref decorations of the history, reused while git's ref storage has not changed.
//!
//! Listing and peeling every ref costs about 25 µs each, which a history page paid in full
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
use crate::Repo;
use crate::repo::absolute;
use gix::ObjectId;
use ide_core::IdeResult;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
/// A timestamp this close to the time it was read cannot tell two writes apart: a later write
/// may leave the same value (coarse file systems, FAT's 2 s). Such a snapshot is never reused.
const RACY_WINDOW: Duration = Duration::from_secs(2);
type Stat = Option<(SystemTime, u64)>;
pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
#[derive(Default)]
pub(crate) struct RefDecorations {
snapshot: Option<Snapshot>,
/// Changes when the decorations do, so cached views of them can be keyed by it.
generation: u64,
}
struct Snapshot {
map: Decorations,
stamp: Vec<(PathBuf, Stat)>,
reusable: bool,
}
fn stat(path: &Path) -> Stat {
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.modified().ok()?, metadata.len()))
}
/// `HEAD`, `packed-refs` and every directory under `refs/`.
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
let mut pending = vec![common_dir.join("refs")];
while let Some(dir) = pending.pop() {
if let Ok(entries) = std::fs::read_dir(&dir) {
pending.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
}
paths.push(dir);
}
paths.into_iter().map(|path| (path.clone(), stat(&path))).collect()
}
impl RefDecorations {
fn get(&mut self, repo: &gix::Repository, git_dir: &Path, common_dir: &Path) -> IdeResult<(Decorations, u64)> {
if let Some(snapshot) = &self.snapshot
&& snapshot.reusable
&& snapshot.stamp.iter().all(|(path, before)| stat(path) == *before)
{
return Ok((snapshot.map.clone(), self.generation));
}
// Stamped before the refs are read, so a write after the stamp shows in the next one.
let taken = SystemTime::now();
let stamp = stamp(git_dir, common_dir);
let map = crate::history::decorations(repo)?;
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
let map = match &self.snapshot {
Some(old) if unchanged => old.map.clone(),
_ => {
self.generation += 1;
Arc::new(map)
}
};
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
Ok((map, self.generation))
}
}
impl Repo {
/// Commit id → decoration labels, and a number that changes whenever they do.
pub(crate) fn ref_decorations(&self, repo: &gix::Repository) -> IdeResult<(Decorations, u64)> {
let common_dir = absolute(repo.common_dir())?;
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
}
}
#[cfg(test)]
mod tests {
use crate::history::decorations_scans;
use crate::{LogOrder, LogQuery, Repo};
use std::path::Path;
use std::time::{Duration, SystemTime};
fn git(dir: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "init.defaultBranch=main", "-c", "user.name=T", "-c", "[email protected]"])
.args(["-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn commit(dir: &Path, message: &str) -> String {
std::fs::write(dir.join("f"), message).unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-qm", message]);
git(dir, &["rev-parse", "HEAD"])
}
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
fn set_ref_times(repo: &Repo, time: SystemTime) {
let git = repo.git_dir.clone();
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
let mut pending = vec![git.join("refs")];
while let Some(dir) = pending.pop() {
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
paths.push(dir);
}
let mut options = std::fs::File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
options.access_mode(FILE_WRITE_ATTRIBUTES).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
}
for path in paths.into_iter().filter(|p| p.exists()) {
options.open(path).unwrap().set_modified(time).unwrap();
}
}
/// As if the refs were written long ago, then reads the history once so the decorations
/// are cached; a second read must not list the refs again.
fn settle(repo: &Repo) {
set_ref_times(repo, SystemTime::now() - Duration::from_secs(3600));
page(repo, 0, 1);
let scans = decorations_scans();
page(repo, 0, 1);
assert_eq!(decorations_scans(), scans, "the decorations were not reusable");
}
fn page(repo: &Repo, skip: u32, limit: u32) -> Vec<crate::Commit> {
repo.log(&LogQuery { skip, limit, summary_only: true, order: LogOrder::Topo, ..Default::default() }).unwrap()
}
fn labels(repo: &Repo, id: &str) -> Vec<String> {
let all = page(repo, 0, 0);
all.into_iter().find(|c| c.id == id).unwrap().refs
}
#[test]
fn warm_pages_do_not_list_the_refs() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
for i in 0..30 {
commit(dir, &format!("c{i}"));
}
for i in 0..20 {
git(dir, &["branch", &format!("b{i}")]);
}
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let after_first = decorations_scans();
for skip in [10, 20, 0, 5] {
assert_eq!(page(&repo, skip, 1).len(), 1);
assert_eq!(page(&repo, skip, 10).len(), 10);
}
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
}
#[test]
fn fresh_ref_timestamps_are_not_trusted() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
let repo = Repo::discover(dir).unwrap().unwrap();
set_ref_times(&repo, SystemTime::now());
page(&repo, 0, 10);
let scans = decorations_scans();
// A write within the timestamp's resolution would leave it unchanged: rescan every time.
page(&repo, 0, 10);
assert!(decorations_scans() > scans);
assert!(labels(&repo, &first).contains(&"main".to_string()));
}
#[test]
fn decorations_follow_every_kind_of_ref_change() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let first_labels = labels(&repo, &first);
assert!(first_labels.contains(&"HEAD".to_string()) && first_labels.contains(&"main".to_string()));
// A new commit moves HEAD and the branch.
settle(&repo);
let second = commit(dir, "second");
assert_eq!(labels(&repo, &first), Vec::<String>::new());
assert!(labels(&repo, &second).contains(&"main".to_string()));
// A new tag, then an annotated one, in a directory that did not exist before.
settle(&repo);
git(dir, &["tag", "v1", &first]);
assert_eq!(labels(&repo, &first), ["tag: v1"]);
settle(&repo);
git(dir, &["tag", "-a", "-m", "m", "rel/v2", &first]);
assert_eq!(labels(&repo, &first), ["tag: rel/v2", "tag: v1"]);
// A new branch, one moved to another commit, and one deleted.
settle(&repo);
git(dir, &["branch", "side", &first]);
assert!(labels(&repo, &first).contains(&"side".to_string()));
settle(&repo);
git(dir, &["branch", "-f", "side", &second]);
assert!(!labels(&repo, &first).contains(&"side".to_string()));
assert!(labels(&repo, &second).contains(&"side".to_string()));
settle(&repo);
git(dir, &["branch", "-D", "side"]);
assert!(!labels(&repo, &second).contains(&"side".to_string()));
// Refs in packed-refs: packing changes nothing visible, deleting one rewrites the file.
git(dir, &["branch", "packed", &first]);
git(dir, &["pack-refs", "--all"]);
settle(&repo);
assert!(labels(&repo, &first).contains(&"packed".to_string()));
git(dir, &["branch", "-D", "packed"]);
assert!(!labels(&repo, &first).contains(&"packed".to_string()));
// A detached HEAD and a tag deleted again.
settle(&repo);
git(dir, &["checkout", "-q", "--detach", &first]);
assert!(labels(&repo, &first).contains(&"HEAD".to_string()));
assert!(!labels(&repo, &second).contains(&"HEAD".to_string()));
settle(&repo);
git(dir, &["tag", "-d", "v1"]);
assert_eq!(labels(&repo, &first), ["HEAD", "tag: rel/v2"]);
}
#[test]
fn a_ref_change_between_pages_replaces_the_cached_view() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
commit(dir, "second");
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
page(&repo, 0, 10);
settle(&repo);
git(dir, &["tag", "v1", &first]);
let rows = page(&repo, 0, 10);
assert_eq!(rows.iter().find(|c| c.id == first).unwrap().refs, ["tag: v1"]);
}
}
+1
View File
@@ -88,6 +88,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
cli_status: Default::default(),
automatic_shelf: Default::default(),
log_index: Default::default(),
ref_decorations: Default::default(),
log_signatures: Default::default(),
conflict_mutation: Default::default(),
amend_recovery: Default::default(),
+56
View File
@@ -583,4 +583,60 @@ mod tests {
cli_status(&repo, &IgnoredNames::default()).unwrap();
assert!(marker.exists(), "control: git status did not run the filter");
}
fn committed_repo(dir: &Path) {
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "same\n").unwrap();
std::fs::write(dir.join("b.txt"), "same\n").unwrap();
commit_all(dir, "base");
}
/// The dirty-scope refresh in Restricted Mode reads the named paths only: it used to answer
/// with the full status, which walks the whole tree for one saved file.
#[test]
fn restricted_status_paths_reads_only_the_named_paths() {
let temp = tempfile::tempdir().unwrap();
let dir = temp.path();
committed_repo(dir);
std::fs::write(dir.join("a.txt"), "changed\n").unwrap();
std::fs::write(dir.join("b.txt"), "changed\n").unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
let one = repo.status_paths(&[repo.root().join("a.txt")]).unwrap();
assert_eq!(one.iter().map(|s| s.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
assert_eq!(repo.status().unwrap().len(), 2, "the full status still lists both");
}
/// The scoped read is `git status`, which applies the repository's clean filters to compare
/// content: Restricted Mode must empty them there as it does for the full read.
#[cfg(unix)]
#[test]
fn restricted_status_paths_does_not_run_repository_filters() {
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let dir = temp.path();
committed_repo(dir);
let marker = dir.join(".git/executed");
let script = dir.join(".git/marker.sh");
std::fs::write(&script, format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display())).unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
git(dir, &["config", "filter.marker.clean", script.to_str().unwrap()]);
std::fs::write(dir.join(".gitattributes"), "*.txt filter=marker\n").unwrap();
// Same size, new mtime: git has to read (and clean) the file to tell whether it changed.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "diff\n").unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
let paths = [repo.root().join("a.txt")];
let listed = repo.status_paths(&paths).unwrap();
assert_eq!(listed.len(), 1, "the change is still listed");
assert!(!marker.exists(), "Restricted Mode ran the repository's clean filter");
// Control: a trusted run does use the filter, so the fixture is live.
repo.set_execution_allowed(true);
repo.status_paths(&paths).unwrap();
assert!(marker.exists(), "control: git status did not run the filter");
}
}
+11 -2
View File
@@ -591,8 +591,17 @@ fn select_into(
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<String>> {
let index = r.git_dir.join("index");
if index.exists() {
std::fs::copy(&index, &tmp.0)?;
match std::fs::File::open(index) {
Ok(mut source) => {
let metadata = source.metadata()?;
let mut copy = std::fs::File::create(&tmp.0)?;
copy.set_permissions(metadata.permissions())?;
std::io::copy(&mut source, &mut copy)?;
// Git uses the index timestamp to decide which same-size files need a content check.
copy.set_modified(metadata.modified()?)?;
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
fill_commit_index(r, &env, options, encoding)
+9
View File
@@ -2017,11 +2017,17 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
#[test]
fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index() {
let fx = Fixture::new();
fx.git(&["config", "core.checkStat", "minimal"]);
fx.git(&["config", "core.trustctime", "false"]);
let same_tick = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
let set_mtime =
|path| std::fs::File::options().write(true).open(fx.path(path)).unwrap().set_modified(same_tick).unwrap();
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
fx.write("f.txt", base);
fx.write("staged.txt", "s\n");
fx.write("old.txt", "moved\nfile\nwith\nlines\n");
fx.write("bin.dat", "\0\x01");
set_mtime("bin.dat");
fx.commit_all("base");
let repo = fx.repo();
let utf8 = |_: &Path| -> ide_core::IdeResult<&encoding_rs::Encoding> { Ok(encoding_rs::UTF_8) };
@@ -2032,6 +2038,9 @@ fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index()
fx.git(&["add", "staged.txt"]);
fx.git(&["mv", "old.txt", "new.txt"]);
fx.write("bin.dat", "\0\x02");
// Git must recheck a same-size edit made on the same clock tick as the index.
set_mtime("bin.dat");
set_mtime(".git/index");
fx.write("added.txt", "new\n");
let index_before = std::fs::read(fx.dir.join(".git/index")).unwrap();
+366
View File
@@ -0,0 +1,366 @@
//! [`decode_text`](crate::decode_text) for files too large to hold: the same
//! decisions, taken while reading a chunk at a time.
use crate::encoding::{SNIFF_LEN, sniff_utf16};
use encoding_rs::{Decoder, Encoding, UTF_8, UTF_16BE, UTF_16LE};
use std::io::{self, Read};
/// Raw bytes read per step; a step holds this plus its UTF-8 expansion (at most 3x).
const CHUNK: usize = 64 * 1024;
/// The text of a file as UTF-8 bytes, decoded as it is read.
pub struct DecodedReader<R> {
reader: R,
decoder: Decoder,
raw: Vec<u8>,
/// Decoded bytes of the last step; `out[pos..len]` is unread.
out: Vec<u8>,
pos: usize,
len: usize,
done: bool,
}
/// Decodes the file `open` reads like [`decode_text`](crate::decode_text) does (BOM, UTF-8 and
/// UTF-16 as detected, other text as `fallback` or else the detected encoding) without holding
/// it: `None` for binary content, else a reader of the text as UTF-8.
///
/// Deciding the encoding of text that is neither BOM-marked nor UTF-8 needs a pass over the whole
/// file before the decoding pass, so `open` gives a fresh reader of the file up to twice.
pub fn decode_stream<R: Read>(
open: impl FnMut() -> io::Result<R>,
fallback: Option<&str>,
) -> io::Result<Option<DecodedReader<R>>> {
decode_stream_in(open, fallback, CHUNK)
}
fn decode_stream_in<R: Read>(
mut open: impl FnMut() -> io::Result<R>,
fallback: Option<&str>,
chunk: usize,
) -> io::Result<Option<DecodedReader<R>>> {
let Some((detected, bom_len, has_bom)) = detect(&mut open, chunk)? else { return Ok(None) };
let fallback = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes()));
let encoding = match fallback {
Some(enc)
if !has_bom && enc != detected && detected != UTF_8 && detected != UTF_16LE && detected != UTF_16BE =>
{
enc
}
_ => detected,
};
let mut reader = open()?;
io::copy(&mut (&mut reader).take(bom_len as u64), &mut io::sink())?;
let decoder = encoding.new_decoder_without_bom_handling();
let out = vec![0; decoder.max_utf8_buffer_length(chunk).unwrap_or(chunk * 3)];
Ok(Some(DecodedReader { reader, decoder, raw: vec![0; chunk], out, pos: 0, len: 0, done: false }))
}
/// The encoding [`decode`](crate::encoding::decode) finds for the file, its BOM length and
/// whether it has a BOM; `None` for binary content.
fn detect<R: Read>(
open: &mut impl FnMut() -> io::Result<R>,
chunk: usize,
) -> io::Result<Option<(&'static Encoding, usize, bool)>> {
let mut reader = open()?;
let mut head = vec![0; SNIFF_LEN];
let n = read_full(&mut reader, &mut head)?;
head.truncate(n);
if let Some((enc, bom_len)) = Encoding::for_bom(&head) {
return Ok(Some((enc, bom_len, true)));
}
if head.contains(&0) {
return Ok(sniff_utf16(&head).map(|enc| (enc, 0, false)));
}
let mut detector = chardetng::EncodingDetector::new();
let mut utf8 = Utf8Check::default();
detector.feed(&head, false);
utf8.feed(&head);
if n == SNIFF_LEN {
let mut buf = vec![0; chunk];
loop {
let n = read_retry(&mut reader, &mut buf)?;
if n == 0 {
break;
}
detector.feed(&buf[..n], false);
utf8.feed(&buf[..n]);
}
}
detector.feed(&[], true);
let encoding = if utf8.is_valid() { UTF_8 } else { detector.guess(None, true) };
Ok(Some((encoding, 0, false)))
}
/// Reads until `buf` is full or the reader ends.
fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
let mut filled = 0;
while filled < buf.len() {
match read_retry(reader, &mut buf[filled..])? {
0 => break,
n => filled += n,
}
}
Ok(filled)
}
fn read_retry(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
loop {
match reader.read(buf) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
result => return result,
}
}
}
/// Checks that bytes fed in pieces form valid UTF-8, as `std::str::from_utf8` does for the whole.
#[derive(Default)]
struct Utf8Check {
/// The start of a character cut by the end of the previous piece.
tail: Vec<u8>,
invalid: bool,
}
impl Utf8Check {
fn feed(&mut self, mut bytes: &[u8]) {
if self.invalid {
return;
}
while !self.tail.is_empty() && !bytes.is_empty() {
self.tail.push(bytes[0]);
bytes = &bytes[1..];
match std::str::from_utf8(&self.tail) {
Ok(_) => self.tail.clear(),
Err(e) if e.error_len().is_none() => {}
Err(_) => {
self.invalid = true;
return;
}
}
}
if !self.tail.is_empty() {
return;
}
match std::str::from_utf8(bytes) {
Ok(_) => {}
Err(e) if e.error_len().is_none() => self.tail.extend_from_slice(&bytes[e.valid_up_to()..]),
Err(_) => self.invalid = true,
}
}
/// Whether everything fed so far was UTF-8 (a truncated final character is not).
fn is_valid(&self) -> bool {
!self.invalid && self.tail.is_empty()
}
}
impl<R: Read> Read for DecodedReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while self.pos == self.len {
if self.done {
return Ok(0);
}
let n = read_retry(&mut self.reader, &mut self.raw)?;
let last = n == 0;
let needed = self.decoder.max_utf8_buffer_length(n).unwrap_or(n * 3 + 16);
if self.out.len() < needed {
self.out.resize(needed, 0);
}
// Malformed input becomes U+FFFD, as in `decode_without_bom_handling`.
let (_, _, written, _) = self.decoder.decode_to_utf8(&self.raw[..n], &mut self.out, last);
self.pos = 0;
self.len = written;
self.done = last;
}
let n = buf.len().min(self.len - self.pos);
buf[..n].copy_from_slice(&self.out[self.pos..self.pos + n]);
self.pos += n;
Ok(n)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::decode_text;
/// Hands out at most `step` bytes per read, so chunk edges fall everywhere.
struct Trickle<'a> {
bytes: &'a [u8],
step: usize,
}
impl Read for Trickle<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = buf.len().min(self.step).min(self.bytes.len());
buf[..n].copy_from_slice(&self.bytes[..n]);
self.bytes = &self.bytes[n..];
Ok(n)
}
}
fn streamed(bytes: &[u8], fallback: Option<&str>, chunk: usize, step: usize) -> Option<Vec<u8>> {
let reader = decode_stream_in(|| Ok(Trickle { bytes, step }), fallback, chunk).unwrap()?;
let mut out = Vec::new();
let mut reader = reader;
// Small reads too: the consumer's buffer is not the chunk either.
let mut buf = [0; 7];
loop {
let n = reader.read(&mut buf).unwrap();
if n == 0 {
return Some(out);
}
out.extend_from_slice(&buf[..n]);
}
}
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
let mut bytes =
if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
for unit in text.encode_utf16() {
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
}
bytes
}
/// Text with multi-byte characters and surrogate pairs at every alignment.
fn sample(len: usize) -> String {
let mut text = String::new();
let pieces = [
"ascii line\n",
"caf\u{e9} cr\u{e8}me\n",
"\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\n",
"\u{1f600}\u{1f4a9} x\n",
"\u{20ac}5\r\n",
];
let mut i = 0;
while text.len() < len {
text.push_str(pieces[i * 7 % pieces.len()]);
i += 1;
}
text
}
fn inputs() -> Vec<(String, Vec<u8>)> {
let text = sample(1500);
let mut inputs = vec![
("utf8".to_string(), text.clone().into_bytes()),
("utf8 bom".to_string(), [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat()),
("utf16le bom".to_string(), utf16(&text, true, false)),
("utf16be bom".to_string(), utf16(&text, true, true)),
("utf16le".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, false)),
("utf16be".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, true)),
(
"gbk".to_string(),
encoding_rs::GBK
.encode(&sample(1500).replace(['\u{1f600}', '\u{1f4a9}', '\u{20ac}'], ""))
.0
.into_owned(),
),
(
"latin1".to_string(),
encoding_rs::WINDOWS_1252
.encode(&sample(1500).replace(|c: char| c as u32 > 0xff && c != '\u{20ac}', ""))
.0
.into_owned(),
),
("empty".to_string(), Vec::new()),
("binary".to_string(), b"\x7FELF\x02\x01\x01\x00\x00\x00 and text".repeat(100)),
("late nul".to_string(), [&b"abc caf\xe9 ".repeat(1200)[..], b"\0 tail"].concat()),
("truncated utf8".to_string(), text.as_bytes()[..text.len() - 1].to_vec()),
("truncated utf16".to_string(), utf16(&text, true, false)[..utf16(&text, true, false).len() - 1].to_vec()),
(
"lone surrogate".to_string(),
[&[0xFF, 0xFE][..], &[0x3D, 0xD8, b'a', 0][..], &utf16(&text, false, false)[..]].concat(),
),
("invalid in the middle".to_string(), [text.as_bytes(), b"\xff\xfe\xc3", text.as_bytes()].concat()),
(
"shift jis".to_string(),
encoding_rs::SHIFT_JIS
.encode(
"\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{ff76}\u{ff85}\n"
.repeat(200)
.as_str(),
)
.0
.into_owned(),
),
];
// The evidence for the encoding comes long after the sniffed head.
let chinese = "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\u{4e00}\u{6bb5}\u{6587}\u{672c}\n".repeat(300);
let gbk = encoding_rs::GBK.encode(&chinese).0.into_owned();
let head = "plain ascii line\n".repeat(1500);
inputs.push(("gbk after a long ascii head".to_string(), [head.as_bytes(), &gbk].concat()));
// Characters at every alignment against the sniffing head and the chunks.
for pad in 0..5 {
let mut bytes = "x".repeat(SNIFF_LEN - 3 + pad).into_bytes();
bytes.extend("\u{4e2d}\u{1f600}\u{e9}".as_bytes());
inputs.push((format!("utf8 at the head edge {pad}"), bytes));
let mut bytes = "y".repeat(SNIFF_LEN - 2 + pad).into_bytes();
bytes.extend([0xE9, b'z', 0xFF, b'e']);
inputs.push((format!("latin1 at the head edge {pad}"), bytes));
}
inputs
}
#[test]
fn streamed_text_equals_the_whole_file_decode() {
for (name, bytes) in inputs() {
for fallback in [None, Some("gbk"), Some("windows-1252"), Some("utf-16le"), Some("nonsense")] {
let expected = decode_text(&bytes, fallback).map(String::into_bytes);
for chunk in [1, 2, 3, 4, 5, 16, 255, 4096, CHUNK] {
for step in [1, 3, 8192, usize::MAX] {
assert_eq!(
streamed(&bytes, fallback, chunk, step),
expected,
"{name}, fallback {fallback:?}, chunk {chunk}, step {step}"
);
}
}
}
}
}
#[test]
fn utf8_check_matches_from_utf8_for_any_split() {
let samples: [&[u8]; 6] = [
"a\u{e9}\u{4e2d}\u{1f600}z".as_bytes(),
b"ab\xe4\xb8",
b"\xe4\xb8a",
b"\xf0\x9f\x98",
b"ok\xc3(",
b"\xed\xa0\x80",
];
for bytes in samples {
for first in 0..=bytes.len() {
for second in first..=bytes.len() {
let mut check = Utf8Check::default();
check.feed(&bytes[..first]);
check.feed(&bytes[first..second]);
check.feed(&bytes[second..]);
assert_eq!(check.is_valid(), std::str::from_utf8(bytes).is_ok(), "{bytes:?} {first} {second}");
}
}
}
}
#[test]
fn reads_at_most_a_bounded_number_of_bytes_per_step() {
// A reader that fails if asked for more than one chunk shows nothing is read whole.
struct Capped<'a>(&'a [u8]);
impl Read for Capped<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
assert!(buf.len() <= SNIFF_LEN.max(1024), "asked for {} bytes", buf.len());
let n = buf.len().min(self.0.len());
buf[..n].copy_from_slice(&self.0[..n]);
self.0 = &self.0[n..];
Ok(n)
}
}
let bytes = encoding_rs::WINDOWS_1252.encode(&"caf\u{e9}\n".repeat(50_000)).0.into_owned();
let mut reader = decode_stream_in(|| Ok(Capped(&bytes)), None, 1024).unwrap().unwrap();
let mut text = String::new();
reader.read_to_string(&mut text).unwrap();
assert_eq!(text, "caf\u{e9}\n".repeat(50_000));
assert!(reader.out.len() <= 4 * 1024 + 16 && reader.raw.len() == 1024);
}
}
+1 -1
View File
@@ -103,7 +103,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult<f64> {
}
/// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text.
fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
pub(crate) fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
if sample.len() < 4 {
return None;
}
+2
View File
@@ -3,6 +3,7 @@
mod archive;
mod bytes;
mod compare;
mod decode_stream;
mod encoding;
mod ops;
mod private;
@@ -30,6 +31,7 @@ pub use compare::{
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge,
};
pub use decode_stream::{DecodedReader, decode_stream};
use encoding::SNIFF_LEN;
pub use encoding::{
LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
+2 -1
View File
@@ -1753,7 +1753,8 @@ mod tests {
std::fs::write(root.join("src/a/after.rs"), "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/a/after.rs"))));
let paths = all_paths(&batches.lock());
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
let excluded = root.join("node_modules");
assert!(!paths.iter().any(|p| p != &excluded && p.starts_with(&excluded)), "{paths:?}");
assert!(!paths.contains(&root.join("lib/out/o.txt")));
// Un-ignoring lib/out keeps its existing filename watch.
+100 -7
View File
@@ -464,15 +464,12 @@ impl LocalHistory {
/// The watcher saw `paths` disappear: files with history that are gone get a
/// "Deleted" entry pointing at their last content (unless one was recorded already).
pub fn note_removed(&self, paths: &[PathBuf]) -> IdeResult<()> {
if paths.is_empty() {
return Ok(());
}
let mut state = self.state.lock();
let gone: Vec<(PathBuf, String, u64)> = {
let mut latest: HashMap<&Path, &HistoryEntry> = HashMap::new();
for e in state.entries.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
if paths.iter().any(|p| e.path.starts_with(p)) {
latest.insert(&e.path, e);
}
}
latest
latest_snapshots_under(&state.entries, paths)
.into_values()
.filter(|e| e.label != DELETED && !e.path.exists())
.map(|e| (e.path.to_path_buf(), e.id.clone(), e.size))
@@ -700,9 +697,32 @@ fn collect_files(dir: &Path, limit: usize, out: &mut Vec<PathBuf>) {
}
}
/// The newest snapshot entry of every file at or below one of `roots`.
/// Each entry is checked by looking up its own path and its ancestors in a set of the roots,
/// so the cost does not grow with the number of roots (a batch can name tens of thousands).
fn latest_snapshots_under<'a>(entries: &'a [HistoryEntry], roots: &[PathBuf]) -> HashMap<&'a Path, &'a HistoryEntry> {
let roots: HashSet<&Path> = roots.iter().map(PathBuf::as_path).collect();
let mut latest = HashMap::new();
for e in entries.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
if e.path.ancestors().any(|dir| {
#[cfg(test)]
tests::ROOT_LOOKUPS.with(|n| n.set(n.get() + 1));
roots.contains(dir)
}) {
latest.insert(&*e.path, e);
}
}
latest
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
thread_local! {
pub(super) static ROOT_LOOKUPS: Cell<usize> = const { Cell::new(0) };
}
#[test]
fn record_list_dedupe_prune() {
@@ -846,6 +866,79 @@ mod tests {
assert_eq!(h.stored_bytes(), 0);
}
#[test]
fn note_removed_work_does_not_grow_with_the_number_of_removed_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let kept: Vec<PathBuf> =
(0..300).map(|i| root.join("keep").join(format!("g{}", i / 50)).join(format!("f{i}.rs"))).collect();
{
let mut state = h.state.lock();
for p in &kept {
state.entries.push(HistoryEntry::snapshot(p, "x", "External change", now_ms()));
}
}
let removed: Vec<PathBuf> =
(0..5_000).map(|i| root.join("gone").join(format!("g{}", i / 50)).join(format!("f{i}.rs"))).collect();
ROOT_LOOKUPS.with(|n| n.set(0));
h.note_removed(&removed).unwrap();
// At most one lookup per path component of each entry, however many paths were removed.
let bound: usize = kept.iter().map(|p| p.components().count()).sum();
let lookups = ROOT_LOOKUPS.with(Cell::get);
assert!(lookups > 0 && lookups <= bound, "{lookups} root lookups for {} entries (bound {bound})", kept.len());
assert_eq!(h.state.lock().entries.len(), kept.len(), "nothing was deleted, so nothing is appended");
}
#[test]
fn note_removed_marks_only_files_gone_under_a_removed_path() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
fs::create_dir_all(root.join("dir")).unwrap();
fs::create_dir_all(root.join("dir2")).unwrap();
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let (a, b) = (root.join("dir/a.txt"), root.join("dir/b.txt"));
let sibling = root.join("dir2/c.txt");
let (solo, multi, present, already) =
(root.join("solo.txt"), root.join("multi.txt"), root.join("present.txt"), root.join("already.txt"));
for (path, text) in [(&a, "a"), (&b, "b"), (&sibling, "c"), (&solo, "s"), (&present, "p"), (&already, "d")] {
h.record(path, text, "Saved").unwrap();
}
h.record(&multi, "v1", "Saved").unwrap();
std::thread::sleep(std::time::Duration::from_millis(2));
h.record(&multi, "v2", "Saved").unwrap();
h.put_label(&root, "Before Git checkout").unwrap();
let snapshots = |path: &Path| -> Vec<HistoryEntry> {
h.list(path).unwrap().into_iter().filter(|e| e.kind == HistoryKind::Snapshot).collect()
};
fs::write(&present, "p").unwrap();
h.note_removed(std::slice::from_ref(&already)).unwrap();
let entries_before_removal = h.state.lock().entries.len();
assert_eq!(snapshots(&already)[0].label, DELETED, "recorded as deleted before the batch");
let already_entries = snapshots(&already).len();
// `dir2` shares the name prefix of `dir` but is not below it.
h.note_removed(&[]).unwrap();
assert_eq!(h.state.lock().entries.len(), entries_before_removal, "an empty batch changes nothing");
h.note_removed(&[root.join("dir"), solo.clone(), multi.clone(), present.clone(), already.clone()]).unwrap();
for (path, text) in [(&a, "a"), (&b, "b"), (&solo, "s"), (&multi, "v2")] {
let newest = &snapshots(path)[0];
assert_eq!((newest.label.as_str(), h.content(&newest.id).unwrap().as_str()), (DELETED, text));
}
assert_eq!(snapshots(&multi).len(), 3, "Saved v1, Saved v2, Deleted");
assert!(snapshots(&sibling).iter().all(|e| e.label != DELETED), "sibling with a shared name prefix");
assert!(snapshots(&present).iter().all(|e| e.label != DELETED), "still on disk");
assert_eq!(snapshots(&already).len(), already_entries, "already recorded as deleted");
assert_eq!(
h.state.lock().entries.len(),
entries_before_removal + 4,
"one Deleted entry each for a, b, solo and multi"
);
}
#[test]
fn deletion_undo_captures_current_bytes_and_empty_folders() {
let tmp = tempfile::tempdir().unwrap();
+3 -3
View File
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
## Manage agents
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
**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**.
**Settings › 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**.
### External MCP servers
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
+1
View File
@@ -69,6 +69,7 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
Selecting an item shows tabs in the detail pane:
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
- **Volume** and **network**: **Dashboard** and **Inspect**.
+1 -1
View File
@@ -20,7 +20,7 @@ A file holds only the values that differ from the layer below. Tables merge key
Some settings are ignored in the project file: `mcpServer`, imported color schemes (`editor.customSchemes`) and `agents.newTaskApprovals` are global only. Project trust is never read from settings.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › External MCP Servers**, and again after its definition changes.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › MCP Connections**, and again after its definition changes.
## File format
+3 -3
View File
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
## 管理 agent
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
**设置 › 智能体 › MCP 连接** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
+1
View File
@@ -69,6 +69,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
选中某项后,详情区会显示以下标签页:
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
+1 -1
View File
@@ -20,7 +20,7 @@ description: "OpenIDEA 的设置保存在哪里、全局文件与项目文件如
有些设置在项目文件中会被忽略:`mcpServer`、导入的配色方案(`editor.customSchemes`)和 `agents.newTaskApprovals` 只能全局配置。项目信任状态永远不会从设置文件中读取。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › 外部 MCP 服务器** 中将其开启;服务器定义改变后也需要重新开启。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › MCP 连接** 中将其开启;服务器定义改变后也需要重新开启。
## 文件格式
+57
View File
@@ -131,3 +131,60 @@ for (const home of [false, true]) {
}
}
}
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
await prepare(page, true, false);
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
const scroller = page.locator(".cm-scroller").filter({ has: box });
const overflow = () =>
scroller.evaluate((el) => ({
x: el.scrollWidth - el.clientWidth,
y: el.scrollHeight - el.clientHeight,
}));
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Reply with OK.");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Start", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
useAgents.setState({
entries: new Map([
[
id,
[
{ type: "user", text: "Reply with OK.", attachments: [] },
{ type: "agent", text: "OK" },
],
],
]),
});
}, task.id);
await expect(page.getByText("OK", { exact: true })).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect(scroller).toHaveCSS("overflow-x", "hidden");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Short draft");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("word".repeat(2000));
await expect(scroller).toHaveCSS("overflow-y", "auto");
await expect
.poll(async () => {
const { x, y } = await overflow();
return x === 0 && y > 0;
})
.toBe(true);
await box.fill("");
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
});
+8 -4
View File
@@ -308,11 +308,15 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
await sessionPopup.getByRole("button", { name: "Reset" }).click();
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
// 2. Jump directly from the session MCP popover's gear button to Settings › Agents › MCP Connections.
await sessionPopup.getByRole("button", { name: "MCP Connections…", exact: true }).click();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "MCP Connections", exact: true })).toBeVisible();
await expect(settingsDialog.getByRole("treeitem", { name: "MCP Connections", exact: true })).toHaveAttribute(
"aria-selected",
"true",
);
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
@@ -321,7 +325,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "External MCP Servers" })
.getByRole("heading", { name: "MCP Connections", exact: true })
.evaluate((el) => el.scrollIntoView({ block: "start" }));
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
+111
View File
@@ -0,0 +1,111 @@
import { Buffer } from "node:buffer";
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const task: AgentTask = {
id: "tool-images",
title: "Render preview",
provider: "claude",
model: null,
status: "ready",
isolation: "local",
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="220" viewBox="0 0 900 220">
<rect width="900" height="220" fill="#f1f5f9"/>
<g fill="#0f766e"><circle cx="150" cy="92" r="48"/><rect x="103" y="137" width="94" height="42" rx="8"/></g>
<g fill="#2563eb"><ellipse cx="450" cy="92" rx="28" ry="48"/><rect x="420" y="137" width="60" height="42" rx="8"/></g>
<g fill="#b45309"><circle cx="750" cy="92" r="48"/><rect x="703" y="137" width="94" height="42" rx="8"/></g>
<g fill="#0f172a" font-size="20" font-family="sans-serif" text-anchor="middle"><text x="150" y="208">Front</text><text x="450" y="208">Side</text><text x="750" y="208">Back</text></g></svg>`;
const image = { mimeType: "image/svg+xml", data: Buffer.from(svg).toString("base64"), name: null };
const entries: AgentEntry[] = [
{
type: "user",
text: "Render three views of the sample model.",
attachments: [],
sentMs: 1000,
doneMs: 2000,
steered: false,
},
{ type: "thought", text: "Rendering the sample views." },
{
type: "tool",
id: "render",
title: "Render preview",
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
images: [image],
},
{
type: "tool",
id: "inspect",
title: "Read preview metadata",
kind: "read",
status: "completed",
locations: [],
output: "Preview generated successfully.",
diffs: [],
},
{ type: "agent", text: "The preview is ready: front, side and back." },
];
for (const foldTurns of [true, false]) {
test(`tool images remain visible and open a full preview with turn folding=${foldTurns}`, async ({
workbench: page,
}) => {
if (!foldTurns) await page.setViewportSize({ width: 700, height: 750 });
await page.evaluate(
async ({ task, entries, foldTurns }) => {
const storePath = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { useProject } = await import(projectPath);
const { commands } = await import(ipcPath);
commands.agentEntries = async () => ({ status: "ok", data: entries });
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, entries]]),
unread: new Set(),
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
);
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
const preview = page.getByRole("img", { name: "Image", exact: true });
await expect(preview).toBeVisible();
await expect(preview).toHaveJSProperty("naturalWidth", 900);
expect(await preview.evaluate((img) => img.closest("details") === null)).toBe(true);
const box = (await preview.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
const fold = page.locator("details").first();
await expect(fold).not.toHaveAttribute("open");
await preview.click();
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
await dialog.getByText("Close", { exact: true }).click();
await expect(dialog).toHaveCount(0);
await fold.locator("summary").first().click();
await expect(preview).toHaveCount(1);
await fold.locator("summary").first().click();
await expect(preview).toBeVisible();
});
}
+71
View File
@@ -0,0 +1,71 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function show(page: Page, action: string) {
await page.evaluate(async (action) => {
const actions = "/src/platform/actions.ts";
if (!(await (await import(/* @vite-ignore */ actions)).executeAction(action))) throw Error(action);
}, action);
}
test("analysis scope fields align with their radio choices and retain their values", async ({ workbench: page }) => {
await page.evaluate(async () => {
const search = "/src/platform/search.ts";
(await import(/* @vite-ignore */ search)).saveCustomScopes([
{ name: "Frontend", pattern: "file:src//*" },
{ name: "Tests", pattern: "file:tests//*" },
]);
});
await show(page, "analyze.inspectCode");
const dialog = page.getByRole("dialog", { name: "Specify Inspection Scope" });
const scope = dialog.getByRole("group", { name: "Scope" });
const directory = scope.getByRole("textbox", { name: "Directory" });
const custom = scope.getByRole("button", { name: "Custom scope", exact: true });
const radio = scope.getByRole("radio", { name: "Module or directory" });
const label = scope.getByText("Module or directory", { exact: true });
await radio.check();
const path = (await directory.boundingBox())!;
const choice = (await label.boundingBox())!;
expect(path.y + path.height / 2).toBeCloseTo(choice.y + choice.height / 2, 0);
await directory.fill("/dev/acme-api/src");
await expect(custom).toBeDisabled();
await scope.getByRole("radio", { name: "Custom scope", exact: true }).check();
await expect(directory).toBeDisabled();
expect((await custom.boundingBox())!.x).toBeCloseTo(path.x, 0);
await custom.click();
await page.getByRole("option", { name: /^Tests/ }).click();
await expect(custom).toContainText("Tests");
await radio.check();
await expect(directory).toHaveValue("/dev/acme-api/src");
await scope.getByRole("radio", { name: "Custom scope", exact: true }).check();
await expect(custom).toContainText("Tests");
await page.setViewportSize({ width: 400, height: 640 });
const stacked = (await directory.boundingBox())!;
const customBox = (await custom.boundingBox())!;
const radioBox = (await label.boundingBox())!;
const next = (await scope.getByText("Current file", { exact: true }).boundingBox())!;
expect(stacked.y).toBeGreaterThan(radioBox.y + radioBox.height);
expect(stacked.y + stacked.height).toBeLessThan(next.y);
expect(stacked.x).toBeCloseTo(customBox.x, 0);
expect(await scope.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
for (const [action, title] of [
["code.cleanup", "Run Code Cleanup"],
["analyze.locateDuplicates", "Locate Duplicates"],
["find.structural", "Structural Search"],
["find.replaceStructural", "Structural Replace"],
] as const) {
test(`${title} keeps directory options with their scope choice`, async ({ workbench: page }) => {
await show(page, action);
const dialog = page.getByRole("dialog", { name: title });
const scope = dialog.getByRole("group", { name: "Scope" });
const directory = scope.getByRole("textbox", { name: "Directory" });
await expect(directory).toBeDisabled();
await scope.getByRole("radio", { name: "Module or directory" }).check();
await expect(directory).toBeEnabled();
await expect(scope.getByRole("button", { name: "Browse…" })).toBeEnabled();
});
}
+1
View File
@@ -274,6 +274,7 @@ test("completion clips long parameters before the suggestion name and return typ
});
await expect(row.locator(".cm-lsp-type")).toHaveText(returnType);
await page.setViewportSize({ width: 820, height: 760 });
await page.evaluate(() => document.fonts.ready);
await expect
.poll(() =>
row.evaluate((el) => {
+52
View File
@@ -0,0 +1,52 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
/** Opens the sample with the server's lenses `titles` above its first line, at editor font `fontSize`. */
async function lensRow(page: Page, fontSize: number, titles: string[]): Promise<{ editor: Locator; row: Locator }> {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(
async ({ fontSize, titles }) => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = useProject.getState().settings;
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize } } });
const at = { line: 0, col: 0 };
window.__ipc.handlers.lsp_code_lens = () =>
titles.map((title) => ({ range: { start: at, end: at }, command: { title, command: "noop", arguments: [] } }));
},
{ fontSize, titles },
);
// An edit asks the server for its lenses again.
await editor.locator(".cm-line").first().click();
await page.keyboard.press("End");
await page.keyboard.type(" ");
const row = editor.locator(".cm-openidea-lens");
await expect(row).toContainText(titles[0]!);
return { editor, row };
}
test("a Code Vision row fits CJK hints at a large editor font", async ({ workbench: page }) => {
const { editor, row } = await lensRow(page, 20, ["10 个用法", "无用法"]);
const overflow = await row.evaluate((el) => {
const box = el.getBoundingClientRect();
return [...el.querySelectorAll(".cm-openidea-lensItem")].map((item) => {
const range = document.createRange();
range.selectNodeContents(item);
const text = range.getBoundingClientRect();
return Math.max(box.top - text.top, text.bottom - box.bottom);
});
});
expect(overflow).toHaveLength(2);
for (const px of overflow) expect(px).toBeLessThanOrEqual(0);
// The editor measured the taller row: the lines below it still sit beside their numbers.
const line = editor.locator(".cm-line", { hasText: "class OrderController" });
const number = editor.locator(".cm-lineNumbers .cm-gutterElement", { hasText: /^8$/ });
const [lineTop, numberTop] = [(await line.boundingBox())!.y, (await number.boundingBox())!.y];
expect(Math.abs(lineTop - numberTop)).toBeLessThanOrEqual(1);
});
test("a Code Vision row keeps its height at the default editor font", async ({ workbench: page }) => {
const { row } = await lensRow(page, 13, ["3 usages"]);
expect((await row.boundingBox())!.height).toBe(16);
});
+68 -7
View File
@@ -1,11 +1,12 @@
import { expect, stubDesktop, test } from "./fixtures";
import type { Page } from "@playwright/test";
import { expect, PROJECT, stubDesktop, test } from "./fixtures";
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
workbench: page,
}) => {
async function importCoverage(page: Page, width: number) {
await page.setViewportSize({ width: 1050, height: 550 });
await expect(page.getByRole("tree", { name: "Project" }).getByRole("treeitem", { name: PROJECT })).toBeVisible();
await expect(page.locator("#splash")).toHaveCount(0);
await stubDesktop(page);
await page.evaluate(async () => {
await page.evaluate(async (width) => {
const projectModule = "/src/platform/project.ts";
const actionsModule = "/src/platform/actions.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
@@ -26,10 +27,15 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
hasBranches: path === "/tmp/coverage.lcov",
files,
});
setToolWindowSize("right", 280);
setToolWindowSize("right", width);
await executeAction("coverage.importReport", "/tmp/coverage.lcov");
});
}, width);
}
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
workbench: page,
}) => {
await importCoverage(page, 280);
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
const tree = coverage.getByRole("tree", { name: "Coverage" });
const line = coverage.getByRole("columnheader", { name: "Line, %" });
@@ -70,3 +76,58 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
await expect(line).toBeVisible();
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
});
test("Coverage column widths follow the dividers and survive a narrower dock and reload", async ({
workbench: page,
}) => {
await importCoverage(page, 460);
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
const line = coverage.getByRole("columnheader", { name: "Line, %" });
const branch = coverage.getByRole("columnheader", { name: "Branch, %" });
const lineDivider = coverage.getByRole("separator", { name: "Resize Line, % column" });
const branchDivider = coverage.getByRole("separator", { name: "Resize Branch, % column" });
const ready = coverage.getByRole("treeitem", { name: /^Ready\.ts/ });
const nameHeader = coverage.getByRole("columnheader", { name: "Element" });
await expect(lineDivider).toBeVisible();
const width = async (loc: typeof line) => (await loc.boundingBox())!.width;
const originalLine = await width(line);
const originalBranch = await width(branch);
const originalName = await width(nameHeader);
const drag = (await lineDivider.boundingBox())!;
await page.mouse.move(drag.x + drag.width / 2, drag.y + drag.height / 2);
await page.mouse.down();
await page.mouse.move(drag.x + drag.width / 2 + 32, drag.y + drag.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 32, 0);
await expect.poll(() => width(nameHeader)).toBeCloseTo(originalName + 32, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
await expect(line).toHaveAttribute("aria-sort", "none");
await branchDivider.press("ArrowRight");
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
const resizeDock = (size: number) =>
page.evaluate(async (size) => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
setToolWindowSize("right", size);
}, size);
await resizeDock(240);
await expect.poll(() => width(line)).toBeLessThan(originalLine - 22);
const tree = coverage.getByRole("tree", { name: "Coverage" });
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
await expect(branchDivider).toBeInViewport({ ratio: 1 });
await resizeDock(460);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await page.reload();
await importCoverage(page, 460);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await branchDivider.dblclick();
await expect.poll(() => width(line)).toBeCloseTo(originalLine, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
});
+78
View File
@@ -3,6 +3,7 @@
* with its frames and variables, and stepping and resuming go back to the adapter. The adapter is
* stubbed at the IPC layer; `crates/ide-dap/tests` drives real ones.
*/
import type { JvmMemoryResult } from "../src/platform/ipc";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
@@ -114,6 +115,83 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
});
test("Memory gives class filtering the available toolbar width and exposes changed-only filtering", async ({
workbench: page,
}) => {
const rows = [
{ name: "OrderCache", instances: 64, deltaInstances: 12 },
{ name: "OrderRepository", instances: 16, deltaInstances: 0 },
].map((row) => ({ ...row, bytes: row.instances * 16, deltaBytes: null, module: null, ambiguous: false }));
const result: JvmMemoryResult = {
status: "ready",
snapshot: {
rows,
totalInstances: 80,
totalBytes: 1280,
javaVersion: "21",
takenWhileSuspended: true,
hasBaseline: true,
elapsedMs: 5,
source: "debugger",
},
};
await stubDesktop(page);
await page.evaluate(
async ({ result, id }) => {
const caps = { jvmMemory: true, jvmHeap: true };
window.__ipc.handlers.debug_capabilities = () => caps;
window.__ipc.handlers.debug_jvm_memory_classes = () => result;
const debugPath = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugPath);
adoptSession(id, { adapter: "java-debug", name: "Billing Service", status: "paused", caps });
const dockPath = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ dockPath);
layout.moveToolWindow("debug", "bottom");
layout.setToolWindowSize("bottom", 300);
layout.showToolWindow("debug", true);
},
{ result, id: SESSION },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Memory" }).click();
const toolbar = debug.getByRole("toolbar", { name: "Memory", exact: true });
const filter = toolbar.getByRole("textbox", { name: "Filter classes" });
const options = toolbar.getByRole("button", { name: "View Options" });
const grid = debug.getByRole("grid", { name: "Memory", exact: true });
await expect(grid.getByText("OrderRepository", { exact: true })).toBeVisible();
expect((await filter.boundingBox())!.width).toBeGreaterThan((await toolbar.boundingBox())!.width / 2);
await page.evaluate(async () => {
const dockPath = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ dockPath);
layout.moveToolWindow("debug", "right");
layout.setToolWindowSize("right", 330);
});
await expect.poll(async () => (await toolbar.boundingBox())!.width).toBeCloseTo(330, 0);
const bar = (await toolbar.boundingBox())!;
const gear = (await options.boundingBox())!;
const input = (await filter.boundingBox())!;
expect(input.width).toBeGreaterThan(bar.width / 2);
expect(input.x + input.width).toBeLessThan(gear.x);
expect(gear.x + gear.width).toBeLessThanOrEqual(bar.x + bar.width);
await filter.fill("cache");
await expect(grid.getByText("OrderRepository", { exact: true })).toBeHidden();
await toolbar.getByRole("button", { name: "Clear", exact: true }).click();
await expect(grid.getByText("OrderRepository", { exact: true })).toBeVisible();
await options.press("Enter");
const changed = page.getByRole("menuitemcheckbox", { name: "Changed only" });
await expect(changed).not.toBeChecked();
await changed.press("Enter");
await expect(grid.getByText("OrderRepository", { exact: true })).toBeHidden();
await expect(options).toHaveAttribute("aria-pressed", "true");
await expect(options).toBeFocused();
await options.press("Enter");
await expect(changed).toBeChecked();
});
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 580, height: 420 });
await stubDesktop(page);
+106
View File
@@ -0,0 +1,106 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const className = "com.example.billing.SettlementSnapshot";
const amountField = "crossBorderSettlementAmountInMinorUnitsBeforeExchangeRateAdjustment";
const amount = "125486.75";
const referenceField = "externalSettlementProcessorReconciliationReferenceForMonthlyReport";
const reference = "EU-West / settlement batch 701 / reconciliation complete";
test("Memory Instances leaves room for field values and referrer actions in a narrow dock", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1180, height: 720 });
await stubDesktop(page);
await page.evaluate(
async ({ className, amountField, amount, referenceField, reference }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const h = window.__ipc.handlers;
h.debug_jvm_memory_classes = () => ({
status: "ready",
snapshot: {
rows: [{ name: className, instances: 1, bytes: 48, deltaInstances: null, deltaBytes: null, module: null }],
totalInstances: 1,
totalBytes: 48,
hasBaseline: false,
elapsedMs: 2,
source: "debugger",
javaVersion: "21",
takenWhileSuspended: true,
},
});
h.debug_jvm_memory_instances = () => ({
status: "ready",
generation: 1,
instances: [{ kind: "object", typeName: className, id: 12 }],
truncated: false,
});
h.debug_jvm_memory_fields = ({ object }) => ({
status: "ready",
fields:
(object as { id: number }).id === 12
? [
{ name: amountField, value: { kind: "primitive", typeName: "double", text: amount } },
{ name: referenceField, value: { kind: "string", text: reference, length: reference.length, id: 16 } },
]
: [],
});
h.debug_jvm_memory_referrers = () => ({
status: "ready",
referrers: [{ value: { kind: "object", id: 12, typeName: className }, via: [referenceField] }],
truncated: false,
});
adoptSession(91, {
name: "Billing Service",
adapter: "java-debug",
status: "paused",
stops: 1,
caps: { jvmMemory: true, jvmInstances: true },
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 330);
showToolWindow("debug", true);
},
{ className, amountField, amount, referenceField, reference },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Memory", exact: true }).click();
await debug.getByRole("row").filter({ hasText: className }).dblclick();
const title = `Instances of ${className}`;
const instances = debug.getByRole("region", { name: title, exact: true });
const tree = instances.getByRole("tree", { name: title });
const root = tree.getByRole("treeitem", { name: /SettlementSnapshot@12/ });
await root.locator("[data-tree-toggle]").click();
const fieldName = instances.getByText(amountField, { exact: true });
const fieldValue = instances.getByText(amount, { exact: true });
const fits = (el: Element) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1;
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
await expect.poll(() => fieldName.evaluate(fits)).toBe(false);
await expect(fieldName).toHaveAttribute("title", amountField);
await expect(fieldValue).toHaveAttribute("title", amount);
await expect(instances.getByText(title, { exact: true })).toHaveCSS(
"font-family",
await instances.evaluate((el) => getComputedStyle(el).fontFamily),
);
const referrerRow = tree.getByRole("treeitem").filter({ hasText: referenceField });
const showReferrers = referrerRow.getByRole("button", { name: "Show Referrers" });
await referrerRow.hover();
await expect(showReferrers).toBeInViewport({ ratio: 1 });
await showReferrers.press("Enter");
await expect(tree.getByText("Referrers", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "debug_jvm_memory_referrers")).toHaveLength(1);
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
setToolWindowSize("bottom", 400);
});
await expect.poll(() => fieldName.evaluate(fits)).toBe(true);
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
});
+110
View File
@@ -0,0 +1,110 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openTable(page: Page, columns: number) {
await stubDesktop(page);
await page.evaluate(async (columns) => {
window.__ipc.handlers.debug_evaluate_in = ({ expression }) => {
const query = String(expression);
const sliced = query.includes("totals.iloc[:2, :2]");
const visibleColumns = sliced ? 2 : Math.min(30, columns);
const columnsInFrame = sliced ? 2 : columns;
const start = query.includes("100, 100,") ? 100 : 0;
const rows = sliced ? 2 : 220;
const count = sliced ? 2 : 100;
const result = query.includes("missing_table")
? { error: "NameError: missing_table" }
: {
kind: "frame",
shape: [rows, columnsInFrame],
rows,
columns: columnsInFrame,
headers: Array.from({ length: visibleColumns }, (_, i) => `Amount ${i + 1}`),
dtypes: Array.from({ length: visibleColumns }, () => "int64"),
index: Array.from({ length: count }, (_, i) => String(i + start)),
cells: Array.from({ length: count }, (_, row) =>
Array.from({ length: visibleColumns }, (_, column) => String((row + start + 1) * 10 + column)),
),
};
return {
name: "",
value: JSON.stringify(JSON.stringify(result)),
typeName: "str",
variablesReference: 0,
evaluateName: null,
};
};
const stateModule = "/src/features/debugger/state.ts";
const overlaysModule = "/src/features/debugger/ui/popoverStore.ts";
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
const { openTableView } = await import(/* @vite-ignore */ overlaysModule);
adoptSession(91, { name: "Settlement review", adapter: "debugpy", status: "paused", selectedFrame: 11 });
openTableView("totals", 91);
}, columns);
const dialog = page.getByRole("dialog", { name: "Table view of totals", exact: true });
await expect(dialog.getByRole("table")).toBeVisible();
return dialog;
}
test("View as Table gives the grid the dialog width and puts the expression below it", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const dialog = await openTable(page, 3);
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
const grid = dialog.getByRole("table");
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
const shape = dialog.getByText("Shape (220, 3)", { exact: true });
const body = (await scroll.boundingBox())!;
const input = (await expression.boundingBox())!;
expect(input.y).toBeGreaterThan(body.y + body.height);
expect((await shape.boundingBox())!.y).toBeLessThan(body.y);
expect(Math.abs((await grid.boundingBox())!.width - (await scroll.evaluate((el) => el.clientWidth)))).toBeLessThan(1);
expect((await dialog.boundingBox())!.width).toBeCloseTo(700, 0);
await expect(expression).toBeFocused();
await expect(grid).toHaveCSS("font-family", /Inter/);
await expect(grid.getByRole("columnheader").nth(1)).toHaveCSS("text-align", "center");
await expect(grid.getByRole("rowheader").first()).toHaveCSS("text-align", "center");
await expect(grid.getByRole("cell").first()).toHaveCSS("text-align", /^(start|left)$/);
});
test("View as Table keeps paging, slice input and Close usable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 450, height: 620 });
const dialog = await openTable(page, 36);
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
const rows = dialog.getByRole("button", { name: "Next Rows", exact: true });
const columns = dialog.getByRole("button", { name: "Next Columns", exact: true });
const close = dialog.getByRole("button", { name: "Close", exact: true }).filter({ hasText: /^Close$/ });
const input = (await expression.boundingBox())!;
const grid = (await scroll.boundingBox())!;
expect(input.y).toBeGreaterThan(grid.y + grid.height);
expect(input.width).toBeCloseTo(grid.width, 0);
for (const control of [expression, rows, columns, close]) await expect(control).toBeInViewport({ ratio: 0.98 });
await scroll.evaluate((el) => {
el.scrollLeft = 300;
el.scrollTop = 150;
});
await expect(dialog.getByRole("rowheader").filter({ hasText: /^9$/ })).toBeInViewport({ ratio: 0.98 });
await rows.click();
await expect(dialog.getByText("Rows 101–200 of 220", { exact: true })).toBeVisible();
await expect
.poll(() => ipcCalls(page, "debug_evaluate_in"))
.toContainEqual(expect.objectContaining({ expression: expect.stringContaining("100, 100, 0, 30") }));
await expression.fill("totals.iloc[:2, :2]");
await expression.press("Enter");
const sliced = page.getByRole("dialog", { name: "Table view of totals.iloc[:2, :2]", exact: true });
await expect(sliced.getByText("Shape (2, 2)", { exact: true })).toBeVisible();
const slicedExpression = sliced.getByRole("textbox", { name: "Expression", exact: true });
await slicedExpression.fill("missing_table");
await slicedExpression.press("Enter");
const failed = page.getByRole("dialog", { name: "Table view of missing_table", exact: true });
const alert = failed.getByRole("alert");
await expect(alert).toHaveText("NameError: missing_table");
expect((await alert.boundingBox())!.y).toBeGreaterThan(
(await failed.getByRole("textbox", { name: "Expression", exact: true }).boundingBox())!.y,
);
await failed
.getByRole("button", { name: "Close", exact: true })
.filter({ hasText: /^Close$/ })
.click();
await expect(failed).toHaveCount(0);
});
+124
View File
@@ -487,6 +487,45 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
for (const mode of ["Preview Only", "Editor and Preview"]) {
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
const path = "/dev/acme-api/linked-heading.md";
const heading = "5.2 状态机";
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
const editor = await openFromTree(page, "README.md");
await page.evaluate(
async ({ path, target }) => {
const backendModule = "/src/editor/core/backend.ts";
const routeModule = "/src/platform/tauriCore.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
docBackend().files.set(path, target);
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
);
},
{ path, target },
);
await editor.locator(".cm-content").focus();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(destinationTab).toHaveCount(0);
await preview.getByRole("link", { name: "Linked heading" }).click();
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
if (mode === "Editor and Preview") {
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
}
});
}
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
@@ -629,6 +668,91 @@ test("single-line selection stays on its own row when font glyphs exceed line he
expect(Math.abs(selBox!.height - lineBox!.height)).toBeLessThanOrEqual(1);
});
test("find and occurrence highlights stay on their own row when font glyphs exceed line height", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({
settings: { ...base, editor: { ...base.editor, fontSize: 18, lineHeight: 18 } },
});
const root = document.documentElement.style;
root.setProperty("--bg-editor", "#ffffff");
root.setProperty("--bg-current-line", "#ffffff");
root.setProperty("--bg-identifier-under-caret", "#cc0000");
root.setProperty("--bg-search-match", "#cc00cc");
root.setProperty("--bg-search-match-current", "#cc8800");
await document.fonts.ready;
});
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(
[" ", "description", " ", "description", " "].join("\n"),
);
const lines = editor.locator(".cm-line");
await expect(lines).toHaveCount(5);
const blankRowsAreUnpainted = async () => {
const [editorBox, b0, b2, b4, matchBox] = await Promise.all([
editor.boundingBox(),
lines.nth(0).boundingBox(),
lines.nth(2).boundingBox(),
lines.nth(4).boundingBox(),
lines.nth(1).boundingBox(),
]);
const png = await editor.screenshot();
const base64 = png.toString("base64");
return page.evaluate(
async ({ base64, editorBox, blanks, probeX }) => {
const img = new Image();
img.src = `data:image/png;base64,${base64}`;
await img.decode();
const scale = img.width / editorBox!.width;
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d")!;
ctx.drawImage(img, 0, 0);
const x = Math.round((probeX - editorBox!.x) * scale);
for (const row of blanks) {
const yStart = Math.ceil((row!.y - editorBox!.y) * scale) + 1;
const yEnd = Math.floor((row!.y + row!.height - editorBox!.y) * scale) - 1;
for (let y = yStart; y <= yEnd; y++) {
const [r, g, b] = ctx.getImageData(x, y, 1, 1).data;
if (r !== 255 || g !== 255 || b !== 255) return { ok: false, x, y, rgb: [r, g, b] };
}
}
return { ok: true };
},
{ base64, editorBox, blanks: [b0, b2, b4], probeX: matchBox!.x + 30 },
);
};
// Selection match on line 4 (`description`) when line 2 is selected.
await lines.nth(1).dblclick();
await expect(editor.locator(".cm-selectionMatch")).toHaveCount(1);
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
// Find matches: line 2 is `.cm-openidea-findMatch-current` (with 1px frame), line 4 is `.cm-openidea-findMatch`.
await page.keyboard.press("Meta+f");
const find = page.getByRole("textbox", { name: "Find" });
await expect(find).toBeFocused();
await find.fill("description");
await expect(editor.locator(".cm-openidea-findMatch-current")).toHaveCount(1);
await expect(editor.locator(".cm-openidea-findMatch")).toHaveCount(2);
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
});
test("vertical tabs leave a narrow editor group most of its width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 900, height: 600 });
await openFromTree(page, "settings.gradle.kts");
+81
View File
@@ -0,0 +1,81 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openEditorTabsSettings(page: Page) {
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("file.settings", "editor.general.editorTabs");
});
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog.getByRole("region", { name: "Closing Policy", exact: true })).toBeVisible();
return dialog;
}
test("Editor Tabs aligns appearance fields and stacks closing choices at both widths", async ({ workbench: page }) => {
const settings = await openEditorTabsSettings(page);
const appearance = settings.getByRole("region", { name: "Appearance", exact: true });
const placement = appearance.getByRole("button", { name: "Tab placement", exact: true });
const closePosition = appearance.getByRole("button", { name: "Close button position", exact: true });
const closing = settings.getByRole("region", { name: "Closing Policy", exact: true });
const limit = closing.getByRole("textbox", { name: "Tab limit", exact: true });
const footer = settings.getByRole("button", { name: "OK", exact: true });
for (const width of [1100, 580]) {
await page.setViewportSize({ width, height: 760 });
const placementBox = (await placement.boundingBox())!;
const closeBox = (await closePosition.boundingBox())!;
expect(Math.abs(placementBox.x - closeBox.x)).toBeLessThanOrEqual(1);
expect(Math.abs(placementBox.width - closeBox.width)).toBeLessThanOrEqual(1);
await expect(placement).toBeInViewport();
await expect(limit).toHaveValue("30");
for (const name of ["When the tab limit is reached", "When the current tab is closed, activate"]) {
const choices = closing.getByRole("radiogroup", { name, exact: true }).getByRole("radio");
const first = (await choices.first().boundingBox())!;
const last = (await choices.last().boundingBox())!;
expect(Math.abs(first.x - last.x)).toBeLessThanOrEqual(1);
expect(last.y).toBeGreaterThan(first.y + first.height);
expect(last.x + last.width).toBeLessThanOrEqual(width);
}
await expect(footer).toBeInViewport();
}
});
test("Editor Tabs keeps row and overflow choices independently selected and keyboard operable", async ({
workbench: page,
}) => {
const settings = await openEditorTabsSettings(page);
const group = settings.getByRole("radiogroup", { name: "Show tabs in", exact: true });
const one = group.getByRole("radio", { name: /^One row/ });
const multiple = group.getByRole("radio", { name: "Multiple rows", exact: true });
const scroll = group.getByRole("radio", { name: "Scroll the tabs panel", exact: true });
const squeeze = group.getByRole("radio", { name: "Squeeze tabs", exact: true });
await expect(one).toBeChecked();
await expect(scroll).toBeChecked();
const oneBox = (await one.boundingBox())!;
const scrollBox = (await scroll.boundingBox())!;
const multipleBox = (await multiple.boundingBox())!;
expect(scrollBox.x).toBeGreaterThan(oneBox.x + 8);
expect(scrollBox.y).toBeGreaterThan(oneBox.y);
expect(Math.abs(multipleBox.x - oneBox.x)).toBeLessThanOrEqual(1);
expect(multipleBox.y).toBeGreaterThan(scrollBox.y);
await scroll.press("ArrowDown");
await expect(squeeze).toBeFocused();
await expect(squeeze).toBeChecked();
await expect(one).toBeChecked();
await one.press("ArrowDown");
await expect(multiple).toBeFocused();
await expect(multiple).toBeChecked();
await expect(squeeze).toBeDisabled();
await expect(squeeze).toBeChecked();
await multiple.press("ArrowUp");
await expect(one).toBeChecked();
await expect(squeeze).toBeEnabled();
await settings.getByRole("button", { name: "OK", exact: true }).click();
const reopened = await openEditorTabsSettings(page);
await expect(reopened.getByRole("radio", { name: /^One row/ })).toBeChecked();
await expect(reopened.getByRole("radio", { name: "Squeeze tabs", exact: true })).toBeChecked();
});
+52
View File
@@ -0,0 +1,52 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
// #5402: an External Tool run from Find Action resolves $FilePath$ against the focused component,
// the Project view's selected file while the tree has focus, else the editor's file.
test("External Tools take $FilePath$ from the Project view selection, else the editor", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
const editor = page.locator(".cm-content");
await expect(editor).toBeFocused();
await stubDesktop(page);
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const tool = { id: "echo", name: "Echo File Path", program: "echo", arguments: "$FilePath$ $FileName$" };
useProject.setState({ settings: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
let id = 0;
window.__ipc.handlers.run_start = ({ config }) => {
id++;
// Exits at once, so the next run of the same tool doesn't ask to stop this one.
window.__ipc.emit({ type: "runExited", run: id, code: 0 });
return {
id,
configId: (config as { id: string }).id,
name: (config as { name: string }).name,
pid: 4242,
running: true,
pty: false,
};
};
});
const runTool = async () => {
await page.keyboard.press("Meta+Shift+A");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
await search.getByRole("combobox").fill("Echo File Path");
await expect(search.getByRole("option", { name: /Echo File Path/ })).toBeVisible();
await search.getByRole("combobox").press("Enter");
await expect(search).toBeHidden();
};
const startedArgs = async () =>
(await ipcCalls(page, "run_start")).map((c) => (c as { config: { args: string[] } }).config.args);
await page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }).click();
await runTool();
await expect.poll(startedArgs).toEqual([["/dev/acme-api/build.gradle.kts", "build.gradle.kts"]]);
await editor.click();
await runTool();
await expect.poll(startedArgs).toEqual([
["/dev/acme-api/build.gradle.kts", "build.gradle.kts"],
["/dev/acme-api/README.md", "README.md"],
]);
});
+51
View File
@@ -0,0 +1,51 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
async function stubProjectTypes(page: Page, types: string[]) {
await stubDesktop(page);
await page.evaluate((types) => {
const h = window.__ipc.handlers;
h.index_file_extensions = () => types.map((extension, i) => ({ extension, files: 100 - i }));
h.languages = () => types.map((extension) => ({ id: extension, name: extension, extensions: [extension] }));
h.search_validate = () => null;
}, types);
}
async function openMaskMenu(page: Page) {
await page.keyboard.press("Meta+Shift+f");
const dialog = page.getByRole("dialog", { name: "Find in Files" });
await dialog.getByRole("button", { name: "Recent file masks" }).click();
const menu = page.getByRole("menu").last();
await expect(menu).toBeVisible();
return menu;
}
test("the file mask menu offers every known file type in the project", async ({ workbench: page }) => {
await stubProjectTypes(page, ["rs", "md", "json", "toml", "yml", "properties"]);
const menu = await openMaskMenu(page);
await expect(menu.getByRole("menuitem")).toHaveText(["*.rs", "*.md", "*.json", "*.toml", "*.yml", "*.properties"]);
await menu.getByRole("menuitem", { name: "*.properties" }).click();
await expect(page.getByRole("textbox", { name: "File mask" })).toHaveValue("*.properties");
});
test("a long file mask menu stays inside the window and scrolls to its last type", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 520 });
const types = Array.from({ length: 40 }, (_, i) => `type${String(i).padStart(2, "0")}`);
await stubProjectTypes(page, types);
const menu = await openMaskMenu(page);
const popup = menu.locator("..");
await expect(menu.getByRole("menuitem")).toHaveCount(40);
await expect
.poll(async () => {
const { y, height } = (await popup.boundingBox())!;
return y >= 0 && y + height <= 520;
})
.toBe(true);
await menu.getByRole("menuitem").first().focus();
await page.keyboard.press("End");
const last = menu.getByRole("menuitem", { name: "*.type39" });
await expect(last).toBeFocused();
await expect(last).toBeInViewport();
await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
});
+93
View File
@@ -2,6 +2,7 @@
* Git Log toolbar buttons close their popup when clicked again, as in IDEA, instead of
* keeping it open (Branch) or replaying its opening (the menus). Git is stubbed at the IPC layer.
*/
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
test.beforeEach(async ({ workbench: page }) => {
@@ -60,6 +61,98 @@ test.beforeEach(async ({ workbench: page }) => {
await expect(page.getByRole("listbox", { name: "Commits" }).getByRole("option").first()).toBeVisible();
});
async function openLogPathEditor(page: Page) {
const toolbar = page.getByRole("toolbar", { name: "Log filters", exact: true });
const filter = toolbar.getByRole("button", { name: /^Paths(:|$)/ });
const overflow = toolbar.getByRole("button", { name: "More Filters", exact: true });
const visible = await filter.isVisible();
const anchor = visible ? filter : overflow;
await anchor.click();
if (!visible) await page.getByRole("menuitem", { name: /^Paths(:|$)/ }).click();
await page.getByRole("menuitem", { name: "Select…", exact: true }).click();
const editor = page.getByRole("dialog", { name: "Filter by Paths", exact: true });
await expect(editor.getByRole("textbox", { name: "Paths", exact: true })).toBeFocused();
return { anchor, editor };
}
test("the Git Log path editor anchors to its filter and wraps long paths", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await page.evaluate(async () => {
const logPath = "/src/features/vcs/logStore.ts";
const optionsPath = "/src/features/vcs/logOptions.ts";
const { setLogFilters } = await import(/* @vite-ignore */ logPath);
const { setLogOptions } = await import(/* @vite-ignore */ optionsPath);
setLogOptions({ showBranches: false, showDetails: false });
setLogFilters({
paths: ["/dev/acme-api/src/" + "settlement-".repeat(12) + "report.ts", "/dev/acme-api/docs/guide.md"],
});
});
const { anchor, editor } = await openLogPathEditor(page);
const input = editor.getByRole("textbox", { name: "Paths", exact: true });
const popupBox = (await editor.boundingBox())!;
const anchorBox = (await anchor.boundingBox())!;
const gap = Math.min(
Math.abs(popupBox.y - anchorBox.y - anchorBox.height),
Math.abs(anchorBox.y - popupBox.y - popupBox.height),
);
expect(gap).toBeLessThanOrEqual(6);
expect((await input.boundingBox())!.height).toBeGreaterThan(120);
expect(await input.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(editor.getByText("One path per line", { exact: true })).toBeVisible();
const grip = (await editor.getByRole("separator", { name: "Resize", exact: true }).boundingBox())!;
const x = grip.x + grip.width / 2;
const y = grip.y + grip.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x, y + 34, { steps: 4 });
await page.mouse.up();
await expect.poll(async () => (await editor.boundingBox())!.height).toBeGreaterThan(popupBox.height + 20);
await input.fill("src\ndocs/draft.md");
await page.setViewportSize({ width: 460, height: 550 });
const overflow = page.getByRole("toolbar", { name: "Log filters" }).getByRole("button", { name: "More Filters" });
await expect(overflow).toBeVisible();
await expect(input).toHaveValue("src\ndocs/draft.md");
await expect(editor).toBeInViewport({ ratio: 0.98 });
await input.press("Escape");
await expect(editor).toHaveCount(0);
});
test("the narrow Git Log path editor applies with the primary shortcut and discards outside clicks", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 460, height: 550 });
const { editor } = await openLogPathEditor(page);
const input = editor.getByRole("textbox", { name: "Paths", exact: true });
await expect(editor.getByRole("separator", { name: "Resize", exact: true })).toBeVisible();
await expect(editor.getByRole("button", { name: "OK", exact: true })).toBeInViewport({ ratio: 0.98 });
const modifier = await page.evaluate(async () => {
const module = "/src/platform/keymap.ts";
const { isMacHost } = await import(/* @vite-ignore */ module);
return isMacHost() ? "Meta" : "Control";
});
await input.fill("src");
await input.press("End");
await input.press("Enter");
await expect(input).toHaveValue("src\n");
await input.fill("../outside");
await input.press(`${modifier}+Enter`);
await expect(editor.getByRole("alert")).toHaveText("Choose a path inside a repository.");
await input.fill("src\ndocs/guide.md\nsrc");
await input.press(`${modifier}+Enter`);
await expect(editor).toHaveCount(0);
const reopened = await openLogPathEditor(page);
await expect(input).toHaveValue("src\ndocs/guide.md");
await input.fill("discarded");
await page.mouse.click(4, 4);
await expect(reopened.editor).toHaveCount(0);
const again = await openLogPathEditor(page);
await expect(input).toHaveValue("src\ndocs/guide.md");
await again.anchor.click();
await expect(again.editor).toHaveCount(0);
});
test("Git Log separates commit message typography from compact metadata", async ({ workbench: page }) => {
await page.setViewportSize({ width: 860, height: 720 });
await page.evaluate(() => {
+44
View File
@@ -0,0 +1,44 @@
import { expect, openFromTree, test } from "./fixtures";
test("multiline editor search keeps three visible lines and replaces with the full text", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
await page.setViewportSize({ width: 540, height: 500 });
const content = editor.locator(".cm-content");
const query = "currency=EUR\nregion=eu-west\npipeline=clearing\nmode=batch\ntimeout=30\nretries=2";
const replacement = query.replace("clearing", "settlement").replace("timeout=30", "timeout=45");
await content.press("Meta+a");
await page.keyboard.insertText(`[ledger]\n${query}\n\n[reporting]\n${query}\n`);
await content.press("Escape");
await content.press("Meta+r");
const bar = page.getByRole("search", { name: "Replace in file" });
const find = bar.getByRole("textbox", { name: "Find", exact: true });
const replace = bar.getByRole("textbox", { name: "Replace", exact: true });
await find.fill(query);
await replace.fill(replacement);
for (const field of [find, replace]) {
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
expect(visibleLines).toBeCloseTo(3);
await field.press("Control+End");
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
}
await expect(find).toHaveValue(query);
await expect(replace).toHaveValue(replacement);
const count = bar.locator("[aria-live]");
await expect(count).toHaveText(/\/2$/);
const selected = await count.innerText();
const next = bar.getByRole("button", { name: /Next Occurrence/ });
await next.click();
await expect(count).toHaveText(/^[12]\/2$/);
await expect(count).not.toHaveText(selected);
await bar.getByRole("button", { name: "Replace All", exact: true }).click();
await expect(editor.locator(".cm-line", { hasText: "timeout=45" })).toHaveCount(2);
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(0);
await bar.getByRole("button", { name: "Close", exact: true }).click();
await expect(content).toBeFocused();
await content.press("Meta+z");
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(2);
});
+56
View File
@@ -0,0 +1,56 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function editMacros(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
if (!(await (await import(/* @vite-ignore */ actions)).executeAction("macro.edit"))) throw Error("Edit Macros");
});
}
test("Edit Macros keeps a balanced, resizable split for names and recorded steps", async ({ workbench: page }) => {
await page.evaluate(async () => {
const model = "/src/features/macros/model.ts";
const { saveMacro } = await import(/* @vite-ignore */ model);
saveMacro("Insert comment", [{ kind: "text", text: "Review this block" }]);
saveMacro("Wrap selection", [
{ kind: "key", key: "Home" },
{ kind: "text", text: "beginProcessingCurrentSelectionImmediately();".repeat(6) },
{ kind: "key", key: "End" },
]);
});
await editMacros(page);
const editor = page.getByRole("dialog", { name: "Edit Macros", exact: true });
const macros = editor.getByRole("listbox", { name: "Macros" });
const steps = editor.getByRole("list", { name: "Recorded steps" });
const options = editor.getByRole("toolbar", { name: "Macros" });
const divider = editor.getByRole("separator", { name: "Macros" });
const [initial, stepsWidth] = await editor.evaluate((dialog) => [
dialog.querySelector('[role="listbox"]')!.getBoundingClientRect().width,
dialog.querySelector("ol")!.getBoundingClientRect().width,
]);
expect(Math.abs(initial - stepsWidth)).toBeLessThanOrEqual(1);
await expect(macros).toBeFocused();
expect((await steps.boundingBox())!.height).toBeGreaterThan(260);
expect((await options.boundingBox())!.y).toBeLessThan((await macros.boundingBox())!.y);
await macros.getByRole("option", { name: "Wrap selection" }).click();
await expect(steps.getByText("Press Home")).toBeVisible();
await divider.press("ArrowRight");
await expect.poll(async () => (await macros.boundingBox())!.width).toBeGreaterThan(initial + 5);
const resized = (await macros.boundingBox())!.width;
await editor.locator("[data-dialog-footer]").getByRole("button", { name: "Close" }).click();
await editMacros(page);
await expect.poll(async () => (await macros.boundingBox())!.width).toBeCloseTo(resized, 0);
await page.setViewportSize({ width: 400, height: 620 });
await macros.getByRole("option", { name: "Wrap selection" }).click();
expect(await steps.evaluate((list) => list.scrollWidth - list.clientWidth)).toBeLessThanOrEqual(1);
await options.getByRole("button", { name: "Rename Macro" }).click();
const rename = page.getByRole("dialog", { name: "Rename Macro", exact: true });
await rename.getByRole("textbox").fill("Wrap text");
await rename.getByRole("button", { name: "Rename", exact: true }).click();
await expect(macros.getByRole("option", { name: "Wrap text" })).toBeVisible();
await expect(steps.getByText("Press Home")).toBeVisible();
});
+74
View File
@@ -0,0 +1,74 @@
import type { MavenModel } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const maven: MavenModel = {
projects: [
{
pom: "pom.xml",
dir: "",
groupId: "dev.acme",
artifactId: "billing",
version: "1.0.0",
packaging: "jar",
displayName: "Billing",
parent: null,
modules: [],
aggregated: false,
plugins: [
{
groupId: "org.apache.maven.plugins",
artifactId: "maven-surefire-plugin",
version: "3.2.5",
prefix: "surefire",
goals: ["test"],
},
],
dependencies: [],
profiles: [],
javaVersion: 21,
command: "mvn",
options: [],
env: {},
},
],
profiles: [],
syncedAt: 1,
stale: false,
syncError: null,
};
test("Maven plugin rows give the name priority over coordinates in narrow docks", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (maven) => {
window.__ipc.handlers.build_model = () => ({ maven, gradle: [] });
const buildModule = "/src/features/build-tools/store.ts";
const { loadModel, setExpanded } = await import(/* @vite-ignore */ buildModule);
await loadModel();
setExpanded("maven", new Set(["mvn:pom.xml", "mvn:pom.xml:plugins"]));
const dockModule = "/src/workbench/toolwindows/store.ts";
const { showToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ dockModule);
showToolWindow("maven", true);
setToolWindowSize("right", 190);
}, maven);
const tree = page.getByRole("tree", { name: "Maven projects" });
const coordinates = "(org.apache.maven.plugins:maven-surefire-plugin:3.2.5)";
const plugin = tree.getByRole("treeitem", { name: `surefire ${coordinates}`, exact: true });
const name = plugin.getByText("surefire", { exact: true });
const metadata = plugin.getByText(coordinates, { exact: true });
await expect(name).toBeVisible();
await expect(metadata).toHaveAttribute("title", coordinates);
const fit = (el: Element) => {
const range = document.createRange();
range.selectNodeContents(el);
return range.getBoundingClientRect().width <= el.getBoundingClientRect().width;
};
expect(await name.evaluate(fit)).toBe(true);
expect(await metadata.evaluate(fit)).toBe(false);
expect(await metadata.evaluate((el) => getComputedStyle(el).color)).not.toBe(
await name.evaluate((el) => getComputedStyle(el).color),
);
await plugin.locator("[data-tree-toggle]").click();
await expect(tree.getByRole("treeitem", { name: "surefire:test", exact: true })).toBeVisible();
});
+83
View File
@@ -0,0 +1,83 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("New Worktree keeps form fields aligned and creates the selected worktree in a short window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 740 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/acme-api";
const service = `${root}/service`;
window.__ipc.handlers.vcs_branches = () => [{ name: "main", current: true, remote: false }];
window.__ipc.handlers.vcs_tags = () => [];
window.__ipc.handlers.vcs_worktrees = ({ repo }) => [{ path: repo, branch: "main", main: true, submodule: false }];
window.__ipc.handlers.vcs_worktree_include = () => ({ exists: true });
window.__ipc.handlers.vcs_add_worktree = () => ({ copyWarning: null, setupWarning: null });
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ root, roots: [root, service], repo: root, available: true });
const context = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ context);
setContext("vcsAvailable", true);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("vcs.newWorktree");
});
const dialog = page.getByRole("dialog", { name: "New Worktree" });
const name = dialog.getByRole("textbox", { name: "Name:" });
const branch = dialog.getByRole("textbox", { name: "New branch name" });
const location = dialog.getByRole("textbox", { name: "Location:" });
const repository = dialog.getByRole("button", { name: "Repository", exact: true });
const checkout = dialog.getByRole("button", { name: "Check out", exact: true });
const setup = dialog.getByRole("checkbox", { name: "Run setup script" });
const script = dialog.getByRole("textbox", { name: "Setup script:" });
await expect(name).toHaveValue("acme-api-main-wt");
await branch.fill("review/ledger-batch");
await name.fill("ledger-review");
await location.fill("/dev/reviews");
await setup.check();
await script.fill("/dev/setup.sh");
const preview = dialog.getByText("Worktree location: /dev/reviews/ledger-review", { exact: true });
await expect(preview).toBeVisible();
for (const size of [
{ width: 1120, height: 740 },
{ width: 440, height: 520 },
]) {
await page.setViewportSize(size);
const column = (await name.boundingBox())!.x;
for (const [label, field] of [
["Name:", name],
["Location:", location],
["Repository:", repository],
["Check out:", checkout],
["Create a new branch", branch],
["Setup script:", script],
] as const) {
const caption = dialog.getByText(label, { exact: true });
await expect(caption).toBeVisible();
const captionBox = (await caption.boundingBox())!;
const fieldBox = (await field.boundingBox())!;
expect(fieldBox.x, label).toBeCloseTo(column, 0);
expect(captionBox.x + captionBox.width, label).toBeLessThanOrEqual(fieldBox.x);
expect(captionBox.y + captionBox.height / 2, label).toBeCloseTo(fieldBox.y + fieldBox.height / 2, 0);
}
expect((await preview.boundingBox())!.x).toBeCloseTo(column, 0);
}
await setup.uncheck();
await expect(script).toHaveCount(0);
await dialog.getByRole("button", { name: "Create", exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(await ipcCalls(page, "vcs_add_worktree")).toEqual([
{
repo: "/dev/acme-api",
path: "/dev/reviews/ledger-review",
commitish: "refs/heads/main",
newBranch: "review/ledger-batch",
copyConfig: true,
setup: null,
},
]);
});
+39 -6
View File
@@ -5,14 +5,29 @@ test.use({ video: "on" });
test("offers file templates for the selected workspace member", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const markers: Record<string, string> = {
"/work/api": "go.mod",
"/work/web": "pom.xml",
"/work/library": "pom.xml",
const markers: Record<string, string[]> = {
"/work/api": ["go.mod"],
"/work/web": ["pom.xml"],
"/work/library": ["pom.xml"],
"/work/tutor": ["package.json", "vite.config.ts"],
};
window.__ipc.handlers.fs_read_dir = ({ path }) => {
const name = markers[String(path)];
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
const files = (markers[String(path)] ?? []).map((name) => ({
name,
path: `${path}/${name}`,
kind: "file",
size: 0,
mtimeMs: 0,
}));
return path === "/work/tutor"
? [...files, { name: "src", path: "/work/tutor/src", kind: "dir", size: 0, mtimeMs: 0 }]
: files;
};
const backend = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backend);
window.__ipc.handlers.fs_create_file = ({ path }) => {
docBackend().files.set(String(path), "");
return null;
};
window.__ipc.handlers.run_configs = () => [
{
@@ -54,6 +69,7 @@ test("offers file templates for the selected workspace member", async ({ workben
await expect(page.getByRole("menuitem", { name: "Go Module", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "JSON File", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Svelte Component", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
@@ -73,6 +89,23 @@ test("offers file templates for the selected workspace member", async ({ workben
await expect(popup.getByText("Java Class", { exact: true })).toBeVisible();
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
const tutor = page.getByRole("treeitem", { name: "tutor /work/tutor", exact: true });
if ((await tutor.getAttribute("aria-expanded")) !== "true") await tutor.locator("[data-tree-toggle]").click();
await newMenu("/work/tutor/src");
const component = page.getByRole("menuitem", { name: "Svelte Component", exact: true });
await expect(component).toBeVisible();
await page.screenshot({ path: test.info().outputPath("svelte-new-menu.png"), animations: "disabled" });
await component.click();
const svelte = page.getByRole("dialog", { name: "New Svelte Component", exact: true });
const name = svelte.getByRole("textbox", { name: "Name", exact: true });
await name.fill("+page.svelte");
await name.press("Enter");
await expect(svelte).toBeHidden();
expect(await ipcCalls(page, "fs_create_file")).toEqual([{ path: "/work/tutor/src/+page.svelte" }]);
await expect(page.getByRole("tab", { name: "+page.svelte" })).toHaveAttribute("aria-selected", "true");
await expect(page.locator(".cm-content")).toContainText("<script>");
});
test("uses the single project's type in the keyboard New popup", async ({ workbench: page }) => {
+15 -2
View File
@@ -37,6 +37,15 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
test("a single click shows the file in the preview tab, which the next one reuses", async ({ workbench: page }) => {
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "README.md" })).toBeVisible();
await page.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "settings.gradle.kts" })).toBeVisible();
await expect(tabs.getByRole("tab", { name: "README.md" })).toHaveCount(0);
});
test("Rename targets a file or folder directly from its context menu", async ({ workbench: page }) => {
await page.setViewportSize({ width: 720, height: 480 });
const menu = page.getByRole("menu", { name: "Context menu" });
@@ -90,6 +99,7 @@ test("Git ignore submenu offers shared and local destinations for files and fold
});
test("keeps New open on a slow diagonal path across sibling items", async ({ workbench: page }) => {
await page.clock.install();
await page.getByRole("treeitem", { name: "README.md", exact: true }).click({ button: "right" });
const parent = page.getByRole("menuitem", { name: "New", exact: true });
const box = (await parent.boundingBox())!;
@@ -101,13 +111,16 @@ test("keeps New open on a slow diagonal path across sibling items", async ({ wor
.filter({ has: page.getByRole("menuitem", { name: "Directory", exact: true }) });
const target = (await submenu.getByRole("menuitem").last().boundingBox())!;
const end = { x: target.x + 20, y: target.y + target.height / 2 };
// Keep the gesture cadence independent of the runner's input and assertion round trips.
await page.clock.pauseAt(new Date(Date.now() + 1000));
for (let step = 1; step <= 10; step++) {
await page.mouse.move(start.x + ((end.x - start.x) * step) / 10, start.y + ((end.y - start.y) * step) / 10);
await page.waitForTimeout(75);
await page.clock.runFor(75);
await expect(parent).toHaveAttribute("aria-expanded", "true");
}
await page.waitForTimeout(350);
await page.clock.runFor(350);
await expect(parent).toHaveAttribute("aria-expanded", "true");
await page.clock.resume();
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
});
+1 -2
View File
@@ -12,9 +12,8 @@ test("the scratch language chooser fits short windows and keeps recents separate
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
const { rememberLanguage } = await import(/* @vite-ignore */ store);
setScratchBackend({
dataDir: async () => "/test-app-data",
scratchesDir: async () => "/test-app-data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
+5 -2
View File
@@ -14,7 +14,7 @@ test("double Shift opens Search Everywhere with its tabs; Escape closes it", asy
});
test("Search Everywhere finds and runs an action", async ({ workbench: page }) => {
await doubleShift(page);
await page.locator("header").getByRole("button", { name: "Search Everywhere", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Search Everywhere" });
await dialog.getByRole("combobox").fill("Language Servers");
const option = dialog.getByRole("option", { name: /Language Servers/ }).first();
@@ -122,7 +122,10 @@ test("Find in Files streams matches by file and opens the chosen one at its line
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const own = getComputedStyle(el);
return own.backgroundColor === expected && own.color === getComputedStyle(el.parentElement!).color;
return (
(own.backgroundColor === expected || own.backgroundImage.includes(expected)) &&
own.color === getComputedStyle(el.parentElement!).color
);
}),
).toBe(true);
const originalPreview = await preview.textContent();
+30 -1
View File
@@ -3,7 +3,7 @@
* header on screen: titles stay on one line and every header control lies inside the popup.
*/
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
@@ -118,6 +118,35 @@ test.describe("search popups at the minimum window width", () => {
await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true });
});
test("multi-line search and replacement leave room for matches and scroll inside their fields", async ({
workbench: page,
}) => {
await stubFindMatches(page);
await run(page, "find.replaceInPath");
const dialog = page.getByRole("dialog", { name: "Replace in Files" });
const search = dialog.getByRole("textbox", { name: "Text to find" });
const replacement = dialog.getByRole("textbox", { name: "Replace with" });
const query = "base=http://localhost:8080\nregion=eu-west\nmode=batch\nverify=true\nretry=2\ntimeout=30";
const changed = query.replace("localhost:8080", "localhost:9443").replace("retry=2", "retry=4");
await search.fill(query);
await replacement.fill(changed);
for (const field of [search, replacement]) {
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
expect(visibleLines).toBeCloseTo(3);
await field.press("Control+End");
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
}
await expect(search).toHaveValue(query);
await expect(replacement).toHaveValue(changed);
await expect(dialog.getByRole("listbox", { name: "Matches" }).getByRole("option").first()).toBeInViewport();
const calls = await ipcCalls(page, "search_start");
expect(calls.some(({ query: sent }) => (sent as { pattern: string }).pattern === query)).toBe(true);
await expect(dialog.getByRole("button", { name: "Replace All", exact: true })).toBeInViewport({ ratio: 1 });
await replacement.fill("updated");
await expect(replacement).toHaveAttribute("rows", "1");
});
test("Replace in Files keeps its footer actions together as the window narrows", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 750 });
await openFromTree(page, "settings.gradle.kts");
+8 -1
View File
@@ -29,7 +29,14 @@ test("Find in Files keeps the scope list and pattern editor usable in a narrow w
expect((await list.boundingBox())!.x).toBeLessThan((await name.boundingBox())!.x);
await page.setViewportSize({ width: 460, height: 530 });
const fields = (await pattern.boundingBox())!;
// The dialog relays out over a few frames after the resize; measure once it has settled.
let fields = (await pattern.boundingBox())!;
await expect(async () => {
const previous = fields.y;
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
fields = (await pattern.boundingBox())!;
expect(fields.y).toBe(previous);
}).toPass();
expect(fields.y).toBeGreaterThanOrEqual((await list.boundingBox())!.y + (await list.boundingBox())!.height);
expect(fields.width).toBeGreaterThan(250);
await list.evaluate((el) => (el.scrollTop = el.scrollHeight));
+439 -1
View File
@@ -1,5 +1,5 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
/** Supply detected configurations without launching desktop processes. */
async function configure(page: Page, extra = 0) {
@@ -241,3 +241,441 @@ test("the Services detail pane adds no second scrollbar over a console", async (
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
expect(result.scrollers.length).toBeGreaterThan(0);
});
test("Docker dashboard keeps multi-line container commands bounded and collapsible", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const script = Array.from({ length: 18 }, (_, i) => ` export STEP_${i}="/persist/slot-${i}"`).join("\n");
const inspectJson = JSON.stringify([
{
Created: "2026-11-22T01:41:28Z",
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
Config: {
Entrypoint: ["/bin/bash", "-ec", `set -euo pipefail\n${script}\nexec /entrypoint.sh "$@"\n`, "--"],
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
WorkingDir: "/actions-runner",
Env: [],
Labels: {},
},
Mounts: [],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
const containerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
const snapshot = {
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
executable: "/usr/local/bin/docker",
containers: [
{
id: containerId,
name: "runner-1",
image: "myoung34/github-runner:latest",
command: '"/bin/bash -ec \'set…"',
state: "running",
status: "Up 2 hours",
ports: "",
createdAt: "2026-11-22 01:41:28 +0000 UTC",
composeProject: "selfhost",
composeService: "github-runner",
composeWorkingDir: "/Users/dev/selfhost",
composeFiles: ["/Users/dev/selfhost/docker-compose.yml"],
},
],
images: [],
volumes: [],
networks: [],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_inspect = () => inspectJson;
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "1.20%",
memUsage: "256MiB / 8GiB",
memPerc: "3.12%",
netIo: "1MB / 1MB",
blockIo: "0B / 0B",
pids: "12",
});
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.cancel_request = () => null;
const storeModule = "/src/features/services/store.ts";
const treeModule = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeModule);
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
useServices.setState({
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { local: { snapshot, loading: false, error: null } },
detailTab: "dashboard",
});
useServicesTree.setState({
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
selectedKey: `docker:local:container:${containerId}`,
selectedKeys: new Set([`docker:local:container:${containerId}`]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
await expect(services.getByText("Container Overview")).toBeVisible();
const toggle = services.getByRole("button", { name: /^\d+ lines$/ });
await expect(toggle).toHaveAttribute("aria-expanded", "false");
const preview = services.locator("code[data-no-tooltip]");
await expect(preview).toContainText("↵");
// Hovering the truncated command preview must not spawn a giant auto-ellipsis tooltip.
await preview.hover();
await page.waitForTimeout(700);
await expect(page.getByRole("tooltip")).toHaveCount(0);
// Collapsed row stays strictly between Started and Working directory (no upward overlap).
const startedLabel = services.getByText("Started", { exact: true });
const commandLabel = services.getByText("Command", { exact: true });
const workingDirLabel = services.getByText("Working directory", { exact: true });
const collapsedStartedBox = (await startedLabel.boundingBox())!;
const collapsedPreviewBox = (await preview.boundingBox())!;
const collapsedWorkingBox = (await workingDirLabel.boundingBox())!;
expect(collapsedPreviewBox.y).toBeGreaterThan(collapsedStartedBox.y + collapsedStartedBox.height);
expect(collapsedWorkingBox.y).toBeGreaterThan(collapsedPreviewBox.y + collapsedPreviewBox.height);
// Expanding reveals Entrypoint + Command arguments inside a bounded scroll box growing downward.
await toggle.click();
const collapseBtn = services.getByRole("button", { name: "Collapse", exact: true });
await expect(collapseBtn).toHaveAttribute("aria-expanded", "true");
await expect(services.getByText("Entrypoint", { exact: true })).toBeVisible();
await expect(services.getByText("Command arguments", { exact: true })).toBeVisible();
const expandedStartedBox = (await startedLabel.boundingBox())!;
const expandedCommandLabelBox = (await commandLabel.boundingBox())!;
const entrypointPre = services.locator("pre").first();
const scrollContainer = entrypointPre.locator("xpath=ancestor::div[1]/parent::div");
const scrollBox = (await scrollContainer.boundingBox())!;
const expandedWorkingBox = (await workingDirLabel.boundingBox())!;
expect(expandedCommandLabelBox.y).toBeGreaterThan(expandedStartedBox.y + expandedStartedBox.height);
expect(scrollBox.y).toBeGreaterThan(expandedCommandLabelBox.y);
expect(scrollBox.height).toBeLessThanOrEqual(182);
expect(expandedWorkingBox.y).toBeGreaterThanOrEqual(scrollBox.y + scrollBox.height - 1);
await collapseBtn.click();
await expect(services.getByRole("button", { name: /^\d+ lines$/ })).toHaveAttribute("aria-expanded", "false");
});
test("Docker Compose container Jump to Source opens the Compose file at the command or the service", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const composePath = "/dev/acme-api/docker-compose.yml";
const composeYaml = [
"services:",
" postgres:",
" image: postgres:16",
" github-runner:",
" image: myoung34/github-runner:latest",
" entrypoint:",
" - /bin/bash",
" - -ec",
" - |",
" mkdir -p /persist/slots",
' exec /entrypoint.sh "$@"',
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
"",
].join("\n");
const backendModule = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
docBackend().files.set(composePath, composeYaml);
window.__ipc.handlers.fs_read_text = ({ path }) => {
if (path === composePath) return composeYaml;
throw { kind: "notFound", message: `not found: ${String(path)}`, detail: null };
};
const runnerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
const dbId = "98ab76cd54ef3210fedcba9876543210abcdef0123456789abcdef0123456789";
const snapshot = {
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
executable: "/usr/local/bin/docker",
containers: [
{
id: runnerId,
name: "selfhost-github-runner-1",
image: "myoung34/github-runner:latest",
command: '"/bin/bash -ec \'mkdir…"',
state: "running",
status: "Up 2 hours",
ports: "",
createdAt: "2026-11-22 01:41:28 +0000 UTC",
composeProject: "selfhost",
composeService: "github-runner",
composeWorkingDir: "/dev/acme-api",
composeFiles: [composePath],
},
{
id: dbId,
name: "selfhost-postgres-1",
image: "postgres:16",
command: "postgres",
state: "running",
status: "Up 2 hours",
ports: "",
createdAt: "2026-11-22 01:41:28 +0000 UTC",
composeProject: "selfhost",
composeService: "postgres",
composeWorkingDir: "/dev/acme-api",
composeFiles: [composePath],
},
],
images: [],
volumes: [],
networks: [],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_inspect = () =>
JSON.stringify([
{
Created: "2026-11-22T01:41:28Z",
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
Config: {
Entrypoint: ["/bin/bash", "-ec", 'mkdir -p /persist/slots\nexec /entrypoint.sh "$@"'],
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
WorkingDir: "/actions-runner",
Env: [],
Labels: {},
},
Mounts: [],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "0.50%",
memUsage: "128MiB / 8GiB",
memPerc: "1.56%",
netIo: "0B / 0B",
blockIo: "0B / 0B",
pids: "4",
});
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.cancel_request = () => null;
const storeModule = "/src/features/services/store.ts";
const treeModule = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeModule);
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
useServices.setState({
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { local: { snapshot, loading: false, error: null } },
detailTab: "dashboard",
});
useServicesTree.setState({
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
selectedKey: `docker:local:container:${runnerId}`,
selectedKeys: new Set([`docker:local:container:${runnerId}`]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
await expect(services.getByText("Container Overview")).toBeVisible();
// Clicking Jump to Source on the Command row opens docker-compose.yml with caret on `command:` value
await services.getByRole("button", { name: "Jump to Source", exact: true }).click();
const editor = page.locator(".cm-editor");
await expect(editor.locator(".cm-activeLine")).toHaveText(
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
);
const caret = await page.evaluate(async () => {
const api = await import(/* @vite-ignore */ "/src/editor/api.ts" as string);
const view = api.activeEditor()?.view;
if (!view) return null;
const head = view.state.selection.main.head;
const line = view.state.doc.lineAt(head);
return { line: line.number - 1, col: head - line.from };
});
expect(caret).toEqual({ line: 11, col: 13 });
// F4 on a Compose container node jumps to its service declaration
const tree = services.getByRole("tree", { name: "Services", exact: true });
await tree.getByRole("treeitem", { name: /github-runner/ }).click();
await page.keyboard.press("F4");
await expect(editor.locator(".cm-activeLine")).toHaveText(" github-runner:");
await tree.getByRole("treeitem", { name: /postgres/ }).click();
await page.keyboard.press("F4");
await expect(editor.locator(".cm-activeLine")).toHaveText(" postgres:");
});
test("Docker Compose dashboard shows per-service resource usage and named project volumes", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
(window as unknown as { __cpuPerc: string }).__cpuPerc = "6.25%";
const anonName = "37cc33a7d603260a82a378d7d3eeb835b748b5712614e2e5b4a3d6572f5e1e71";
const snapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: null },
executable: "/usr/bin/docker",
containers: [
{
id: "db-1",
name: "shop-db-1",
image: "postgres:16",
command: "postgres",
state: "running",
status: "Up 15 minutes",
ports: "127.0.0.1:5432->5432/tcp",
createdAt: "2026-04-20T05:00:00Z",
composeProject: "shop",
composeService: "db",
composeWorkingDir: "/work/shop",
composeFiles: ["/work/shop/docker-compose.yml"],
mounts: ["shop_pgdata"],
networks: ["shop_default"],
},
{
id: "api-1",
name: "shop-api-1",
image: "node:22",
command: "node server.js",
state: "exited",
status: "Exited (0) 2 minutes ago",
ports: "",
createdAt: "2026-04-20T05:00:00Z",
composeProject: "shop",
composeService: "api",
composeWorkingDir: "/work/shop",
composeFiles: ["/work/shop/docker-compose.yml"],
mounts: [],
networks: ["shop_default"],
},
],
images: [],
volumes: [
{
name: anonName,
driver: "local",
mountpoint: `/var/lib/docker/volumes/${anonName}/_data`,
composeProject: "shop",
scope: "local",
labels: { "com.docker.volume.anonymous": "" },
},
{
name: "shop_pgdata",
driver: "local",
mountpoint: "/var/lib/docker/volumes/shop_pgdata/_data",
composeProject: "shop",
scope: "local",
labels: {
"com.docker.compose.project": "shop",
"com.docker.compose.volume": "pgdata",
},
},
{
name: "other_cache",
driver: "local",
mountpoint: "/var/lib/docker/volumes/other_cache/_data",
composeProject: "other",
scope: "local",
labels: {
"com.docker.compose.project": "other",
"com.docker.compose.volume": "cache",
},
},
],
networks: [{ id: "net-1", name: "shop_default", driver: "bridge", scope: "local", composeProject: "shop" }],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.docker_inspect = () => "[]";
window.__ipc.handlers.docker_container_stats = ({ id }) => {
if (id !== "db-1") throw { kind: "notFound", message: "container not running", detail: null };
return {
cpuPerc: (window as unknown as { __cpuPerc: string }).__cpuPerc,
memUsage: "128MiB / 2GiB",
memPerc: "6.25%",
netIo: "2.4MB / 980kB",
blockIo: "12MB / 4.1MB",
pids: "17",
};
};
const storeMod = "/src/features/services/store.ts";
const treeMod = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeMod);
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
useServices.setState({
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { default: { snapshot, loading: false, error: null } },
});
useServicesTree.setState({
expanded: new Set(["docker:default"]),
selectedKey: "docker:default:compose:shop",
selectedKeys: new Set(["docker:default:compose:shop"]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
const detail = services.locator("[data-panel][id=services-detail]");
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
const dbRow = detail.locator("tr", { hasText: "shop-db-1" });
const apiRow = detail.locator("tr", { hasText: "shop-api-1" });
await expect(dbRow).toContainText("6.25%");
await expect(dbRow).toContainText("128MiB / 2GiB (6.25%)");
await expect(dbRow).toContainText("2.4MB / 980kB");
await expect(dbRow).toContainText("12MB / 4.1MB");
await expect(dbRow).toContainText("17");
await expect(apiRow).toContainText("Exited (0) 2 minutes ago");
// Stopped service container is never queried for live stats, and no manual Refresh button is shown.
const queriedIds = (await ipcCalls(page, "docker_container_stats")).map((c) => c.id);
expect(new Set(queriedIds)).toEqual(new Set(["db-1"]));
await expect(detail.getByRole("button", { name: "Refresh", exact: true })).toHaveCount(0);
// Running service metrics auto-refresh in place without user action.
await page.evaluate(() => {
(window as unknown as { __cpuPerc: string }).__cpuPerc = "18.50%";
});
await expect(dbRow).toContainText("18.50%", { timeout: 5000 });
// Named Compose volume appears with logical name + driver; anonymous and other-project volumes do not.
const volumeButton = detail.getByRole("button", { name: /shop_pgdata/ });
await expect(volumeButton).toContainText("pgdata · local");
await expect(detail.getByText("other_cache")).toHaveCount(0);
await expect(detail.getByText(/37cc33a7/)).toHaveCount(0);
// Clicking the named volume opens its Volume dashboard and links back to the Compose project.
await volumeButton.click();
await expect(detail.getByText("Volume Overview")).toBeVisible();
await detail.getByRole("button", { name: "shop", exact: true }).click();
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
// Clicking a service in the table navigates to its Container dashboard, which auto-refreshes live stats.
await detail.getByRole("button", { name: "shop-db-1", exact: true }).click();
await expect(detail.getByText("Container Overview")).toBeVisible();
await expect(detail).toContainText("18.50%");
await page.evaluate(() => {
(window as unknown as { __cpuPerc: string }).__cpuPerc = "27.40%";
});
await expect(detail).toContainText("27.40%", { timeout: 5000 });
});
+26 -1
View File
@@ -75,7 +75,7 @@ for (const locale of ["en", "zh"]) {
const path = "/src/platform/i18n.ts";
await (await import(/* @vite-ignore */ path)).setLocale(locale);
}, locale);
for (const id of ["appearance", "editor.font", "general", "general.httpProxy"]) {
for (const id of ["appearance", "editor.font", "general", "general.httpProxy", "vcs.log"]) {
await selectPage(page, id);
const body = page.locator("[class*='pageBody']");
for (const width of [1000, 784, 640, 520]) {
@@ -108,6 +108,31 @@ test("keeps Open project in options within narrow System Settings", async ({ wor
expect(overflow).toBeLessThanOrEqual(1);
});
test("Git Log settings group display and column options with aligned checkboxes", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await selectPage(page, "vcs.log");
const view = dialog.getByRole("region", { name: "View Options" });
const columns = dialog.getByRole("region", { name: "Visible columns" });
const tagNames = view.getByRole("checkbox", { name: "Show tag names" });
const hash = columns.getByRole("checkbox", { name: "Hash" });
await expect(view.getByRole("checkbox")).toHaveCount(5);
await expect(columns.getByRole("checkbox")).toHaveCount(4);
for (const width of [1000, 520]) {
await page.setViewportSize({ width, height: 760 });
// Read both rows together once the dialog has finished opening and relaid out.
await expect
.poll(async () => Math.abs((await tagNames.boundingBox())!.x - (await hash.boundingBox())!.x))
.toBeLessThan(0.5);
}
await expect(hash).not.toBeChecked();
await hash.focus();
await page.keyboard.press("Space");
await expect(hash).toBeChecked();
});
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+2
View File
@@ -385,6 +385,8 @@ test("edits and stages from the index in unified diffs of read-only files", asyn
const index = modal.locator('.cm-content[aria-label="Staged (index)"]');
await expect(index).toBeEditable();
await expect(index).toHaveText(/val alpha = "index"\s+val alpha = "local"/, { useInnerText: true });
await expect(modal.locator(".cm-diffNumbers-modified .cm-diffWidgetNumber")).toHaveText(["1", "3"]);
await expect(modal.locator(".cm-diffNumbers-original .cm-diffWidgetNumber")).toHaveCount(0);
const setReadOnly = (readOnly: boolean) =>
page.evaluate((readOnly) => window.__ipc.handlers.test_set_readonly?.({ readOnly }), readOnly);
await setReadOnly(false);
+79
View File
@@ -0,0 +1,79 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("groups stashes by repository and keeps the selected stash actions scoped", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(async () => {
const main = "/dev/acme-api";
const service = `${main}/warehouse-api`;
const stash = (index: number, id: string, title: string) => ({
index,
id,
message: `On main: ${title}`,
base: "base",
timeMs: new Date(2025, 4, 14, 10, 30).getTime(),
});
const handlers = window.__ipc.handlers;
handlers.vcs_stashes = ({ repo }) =>
repo === service
? [stash(0, "warehouse-stash", "Review warehouse routing")]
: [stash(0, "ledger-stash", "Check totals"), stash(1, "invoice-stash", "Match invoice balances")];
handlers.vcs_commit_files = ({ repo }) => [
{ path: repo === service ? "routing.txt" : "totals.txt", kind: "modified", oldPath: null },
];
const store = "/src/features/vcs/store.ts";
const context = "/src/platform/context.ts";
const actions = "/src/platform/actions.ts";
const toolWindows = "/src/workbench/toolwindows/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
const { setContext } = await import(/* @vite-ignore */ context);
const { executeAction } = await import(/* @vite-ignore */ actions);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ toolWindows);
useVcs.setState({ available: true, root: main, repo: main, roots: [main, service] });
setContext("vcsAvailable", true);
moveToolWindow("commit", "bottom");
await executeAction("vcs.showStashes");
setToolWindowSize("bottom", 310);
});
const tree = page.getByRole("tree", { name: "Stashes", exact: true });
const main = tree.getByRole("treeitem").filter({ has: page.getByText("acme-api", { exact: true }) });
const service = tree.getByRole("treeitem", { name: /warehouse-api/ });
const apply = page
.getByRole("toolbar", { name: "Stashes", exact: true })
.getByRole("button", { name: "Apply Stash" });
const first = tree.getByRole("treeitem", { name: /Check totals/ });
await expect(service, "repository group starts expanded").toHaveAttribute("aria-expanded", "true");
await expect(main).toHaveAccessibleName(/acme-api\s*2/);
await expect(first).toHaveAttribute("aria-level", "2");
await expect(first).toHaveAttribute("aria-selected", "true");
for (const width of [1100, 440]) {
await page.setViewportSize({ width, height: 720 });
const subject = first.getByText("Check totals", { exact: true });
const date = subject.locator("xpath=following-sibling::*[1]");
await expect(date).toHaveText(/2025/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(date).toHaveCSS("font-size", await subject.evaluate((el) => getComputedStyle(el).fontSize));
const titleBox = (await subject.boundingBox())!;
const dateBox = (await date.boundingBox())!;
expect(dateBox.x - titleBox.x - titleBox.width).toBeCloseTo(6, 0);
}
await tree.focus();
await tree.press("Home");
await tree.press("ArrowLeft");
await expect(main).toHaveAttribute("aria-expanded", "false");
await expect(first).toHaveCount(0);
await expect(apply).toBeDisabled();
await expect(page.getByText("Select a stash to view its changes.")).toBeVisible();
await tree.press("ArrowRight");
await expect(first).toBeVisible();
await tree.getByText("Review warehouse routing", { exact: true }).click();
await expect(apply).toBeEnabled();
await expect(page.getByRole("tree", { name: "Changed files" }).getByText("routing.txt")).toBeVisible();
expect((await ipcCalls(page, "vcs_commit_files")).at(-1)).toEqual({
repo: "/dev/acme-api/warehouse-api",
commit: "warehouse-stash",
});
});
+81
View File
@@ -0,0 +1,81 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openDialog(page: Page, id: "find.structural" | "find.replaceStructural") {
await stubDesktop(page);
await page.evaluate(async (id) => {
window.__ipc.handlers.structural_languages = () => [
{ id: "java", name: "Java" },
{ id: "typescript", name: "TypeScript" },
];
window.__ipc.handlers.structural_validate = () => null;
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction(id);
}, id);
}
test("Structural Search puts language selection beside the taller template editor", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1080, height: 720 });
await openDialog(page, "find.structural");
const dialog = page.getByRole("dialog", { name: "Structural Search" });
const editor = dialog.getByRole("textbox", { name: "Search template" });
const label = dialog.locator("label").filter({ hasText: /^Search template$/ });
const language = dialog.getByRole("button", { name: "Language", exact: true });
await expect(editor).toBeFocused();
await expect(language).toHaveText("Java");
const { x, y, width, height } = (await editor.boundingBox())!;
const caption = (await label.boundingBox())!;
const picker = (await language.boundingBox())!;
expect(Math.abs(caption.y + caption.height / 2 - (picker.y + picker.height / 2))).toBeLessThanOrEqual(1);
expect(Math.abs(caption.x - x)).toBeLessThanOrEqual(1);
expect(Math.abs(picker.x + picker.width - (x + width))).toBeLessThanOrEqual(1);
expect(y - (picker.y + picker.height)).toBeLessThanOrEqual(6);
expect(Math.abs(height - 150)).toBeLessThanOrEqual(1);
await language.click();
await page.getByRole("option", { name: "TypeScript" }).click();
await editor.fill("console.log($value$)");
await expect
.poll(() => ipcCalls(page, "structural_validate"))
.toContainEqual({
query: { language: "typescript", pattern: "console.log($value$)", replacement: null, maxMatches: 0 },
});
await expect(dialog.getByRole("button", { name: "Find", exact: true })).toBeEnabled();
});
test("Structural Replace uses editor typography and fits the template controls in a narrow window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 400, height: 620 });
await openDialog(page, "find.replaceStructural");
const dialog = page.getByRole("dialog", { name: "Structural Replace" });
const search = dialog.getByRole("textbox", { name: "Search template" });
const replacement = dialog.getByRole("textbox", { name: "Replace template" });
await expect(search).toBeFocused();
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { settings, project } = useProject.getState();
const current = settings ?? project?.settings;
if (!current) throw new Error("Expected project settings");
useProject.setState({
settings: { ...current, editor: { ...current.editor, fontFamily: "Consolas", fontSize: 17, lineHeight: 26 } },
});
});
for (const template of [search, replacement]) {
await expect(template).toHaveCSS("font-family", /^Consolas,/);
await expect(template).toHaveCSS("font-size", "17px");
await expect(template).toHaveCSS("line-height", "26px");
const box = (await template.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(400);
expect(Math.abs(box.height - 105)).toBeLessThanOrEqual(1);
}
await expect(dialog.getByRole("radio", { name: "Whole project" })).toBeInViewport();
await replacement.fill("Objects.equals($a$, $b$)");
await expect(replacement).toHaveValue("Objects.equals($a$, $b$)");
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport();
});
+123
View File
@@ -0,0 +1,123 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function seedReview(page: Page) {
await stubDesktop(page);
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const context = "/src/platform/context.ts";
const repositoryStore = "/src/features/github/data/repository.ts";
const pullRequests = "/src/features/github/data/pullRequest.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { setContext } = await import(/* @vite-ignore */ context);
const { useGhRepository } = await import(/* @vite-ignore */ repositoryStore);
const { setPullRequestData } = await import(/* @vite-ignore */ pullRequests);
useProject.setState((s: { settings: { editor: unknown } }) => ({
settings: {
...s.settings,
editor: { ...(s.settings?.editor as object), fontFamily: "Courier New", fontSize: 17, lineHeight: 25 },
},
}));
const coordinates = { owner: "sample", name: "settlement" };
useGhRepository.setState({
connection: {
coordinates,
repository: { id: "repository", nameWithOwner: "sample/settlement" },
currentUser: { id: "reviewer", login: "reviewer" },
root: null,
remotes: [],
},
});
setContext("githubConnected", true);
setContext("githubCurrentBranchPullRequest", true);
setPullRequestData(7, "details", () => ({ number: 7, viewerDidAuthor: false }));
setPullRequestData(7, "pendingReview", () => ({ id: "draft-seven", state: "PENDING", commentsCount: 12 }));
});
}
async function openReview(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("github.pullRequest.submitReview", 7);
});
}
test("centers the unanchored composer, follows the editor font and reflows its review actions", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 840 });
await seedReview(page);
await openReview(page);
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const verticalCenter = () =>
popup.evaluate((el) => {
const { top, height } = el.getBoundingClientRect();
return Math.abs(top + height / 2 - innerHeight / 2);
});
await expect.poll(verticalCenter, { message: "verticalCenter at standard size" }).toBeLessThan(1);
await expect(editor).toBeFocused();
await expect(editor).toHaveCSS("font-size", "17px");
await expect(editor).toHaveCSS("line-height", "25px");
await expect(editor).toHaveCSS("font-family", /Courier New/);
await editor.fill("Please double-check the rounding step.");
const grip = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 56, grip.y + grip.height / 2 + 32);
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(540);
await page.setViewportSize({ width: 300, height: 400 });
await expect.poll(verticalCenter, { message: "verticalCenter after shrinking" }).toBeLessThan(1);
const approve = (await popup.getByRole("button", { name: "Approve", exact: true }).boundingBox())!;
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
expect(comment.y).toBeGreaterThan(approve.y);
expect(comment.x + comment.width).toBeLessThan(300);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await editor.press("Escape");
await expect(popup).toHaveCount(0);
await openReview(page);
await expect(editor).toHaveValue("Please double-check the rounding step.");
});
test("keeps anchored review controls and the comment visible after a long submission error", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 355, height: 390 });
await seedReview(page);
await page.evaluate(async () => {
const path = "/src/features/github/details/SubmitReviewPopup.tsx";
const { showSubmitReview } = await import(/* @vite-ignore */ path);
const anchor = document.createElement("button");
anchor.style.cssText = "position:fixed;top:350px;left:275px;";
anchor.textContent = "Review anchor";
document.body.append(anchor);
window.__ipc.handlers.gh_api = ({ request }) => {
const { query } = JSON.parse((request as { body: string }).body);
if (!query.includes("submitPullRequestReview")) throw Error("Unexpected GitHub request");
return JSON.stringify({ errors: [{ message: "Review request failed. " + "outdated-reference-".repeat(35) }] });
};
void showSubmitReview(7, anchor);
});
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const button = popup.getByRole("button", { name: "Comment", exact: true });
await editor.fill("Check the batch limit.");
await button.click();
const error = popup.getByRole("alert");
await expect(error).toContainText("Review request failed.");
await expect(button).toBeEnabled();
await expect(editor).toHaveValue("Check the batch limit.");
const box = (await popup.boundingBox())!;
const buttonBox = (await button.boundingBox())!;
expect(box.y + box.height).toBeLessThan(350);
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(box.y + box.height);
expect(box.x + box.width).toBeLessThanOrEqual(355);
await expect.poll(() => error.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
const calls = await ipcCalls(page, "gh_api");
expect(calls).toHaveLength(1);
const { variables } = JSON.parse((calls[0]!.request as { body: string }).body);
expect(variables).toEqual({ reviewId: "draft-seven", event: "COMMENT", body: "Check the batch limit." });
});
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openDiff(page: Page, left: string, right: string, options: Record<string, unknown> = {}) {
await page.evaluate(
async ({ left, right, options }) => {
localStorage.setItem(
"openidea.vcs.diffOptions",
JSON.stringify({ mode: "unified", collapse: false, ...options }),
);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("diff.compareTexts", {
path: "SettlementRules.txt",
left: { text: left, label: "Original" },
right: { text: right, label: "Modified" },
});
},
{ left, right, options },
);
return page.getByRole("toolbar", { name: "Diff" });
}
async function rowNumbers(page: Page, text: string, deleted = false) {
return page
.locator(deleted ? ".cm-deletedLine" : ".cm-line")
.filter({ hasText: text })
.evaluate((row) => {
const top = row.getBoundingClientRect().top;
const editor = row.closest(".cm-editor")!;
const read = (side: string) =>
[...editor.querySelectorAll(`.cm-diffNumbers-${side} :is(.cm-gutterElement, .cm-diffWidgetNumber)`)].find(
(number) =>
getComputedStyle(number).visibility === "visible" && Math.abs(number.getBoundingClientRect().top - top) < 1,
)?.textContent ?? null;
return [read("original"), read("modified")];
});
}
test("Unified Diff keeps original and modified numbers aligned with wrapped and removed lines", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1000, height: 640 });
const oldRule = "Obsolete settlement rule " + "requires review for each exceptional invoice. ".repeat(3);
const toolbar = await openDiff(
page,
["Settlement rules", oldRule, "Retire legacy routing", "Report totals", "Finish batch"].join("\n"),
["Settlement rules", "Validate settlement currency", "Report totals", "Finish batch"].join("\n"),
{ softWrap: true },
);
await expect(toolbar).toContainText("1 difference");
for (const width of [1000, 440]) {
await page.setViewportSize({ width, height: 640 });
await expect.poll(() => rowNumbers(page, "Obsolete settlement rule", true)).toEqual(["2", null]);
await expect.poll(() => rowNumbers(page, "Retire legacy routing", true)).toEqual(["3", null]);
await expect.poll(() => rowNumbers(page, "Validate settlement currency")).toEqual([null, "2"]);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["4", "3"]);
}
const removed = page.locator(".cm-deletedLine").filter({ hasText: "Obsolete settlement rule" });
const lineHeight = await removed.evaluate((el) => parseFloat(getComputedStyle(el).lineHeight));
expect((await removed.boundingBox())!.height).toBeGreaterThan(lineHeight * 2);
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(toolbar).toContainText("1 of 1 differences");
});
test("Unified Diff numbers account for ignored empty lines and a removal at EOF without a newline", async ({
workbench: page,
}) => {
await openDiff(
page,
"Settlement rules\n\nReport totals\nFinish batch\nRemove final rule",
"Settlement rules\nReport totals\nFinish batch",
{ ignore: "whitespaceAndLines" },
);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["3", "2"]);
await expect.poll(() => rowNumbers(page, "Finish batch")).toEqual(["4", "3"]);
await expect.poll(() => rowNumbers(page, "Remove final rule", true)).toEqual(["5", null]);
});
test("Unified Diff follows vertical scrolling inside one large removal", async ({ workbench: page }) => {
const removed = Array.from({ length: 250 }, (_, i) => `Retired workflow ${i + 1}.`);
await openDiff(page, ["Start batch", ...removed, "Finish batch"].join("\n"), "Start batch\nFinish batch");
const target = page.locator(".cm-deletedLine").filter({ hasText: "Retired workflow 229." });
await target.scrollIntoViewIfNeeded();
await expect.poll(() => rowNumbers(page, "Retired workflow 229.", true)).toEqual(["230", null]);
});
+1 -1
View File
@@ -67,7 +67,7 @@
"@floating-ui/react-dom": "^2.1.9",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lezer/common": "^1.5.3",
"@lezer/common": "^1.5.6",
"@lezer/highlight": "^1.2.5",
"@lezer/lr": "^1.4.11",
"@mathjax/mathjax-tex-font": "4.1.3",
Loaded 100 of 341 files, more files were not shown because too many files have changed in this diff. Show more