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
143 changed files with 4743 additions and 788 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 138 KiB

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",
+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
+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();
+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 }))
}
+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)]
+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);
+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,
+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();
+2
View File
@@ -1587,11 +1587,13 @@ mod tests {
}
/// 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)?;
+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();
+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.
+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 });
});
+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();
});
}
+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);
});
+39
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");
+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);
});
+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) => {
+1 -1
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();
+73 -7
View File
@@ -155,6 +155,23 @@ fn flash_taskbar_unless_focused(app: &AppHandle) {
});
}
/// Sends `event` to `peers` (failures ignored: a window may be closing) and then to `owner`,
/// whose result is returned. The event is serialised once; `send` gets each window's copy of the
/// JSON, which Tauri's `emit_to` would otherwise re-serialise per window (large for
/// diagnostics of a big file).
fn fan_out<T: serde::Serialize>(
event: &T,
peers: &[String],
owner: &str,
mut send: impl FnMut(&str, String) -> tauri::Result<()>,
) -> tauri::Result<()> {
let json = serde_json::to_string(event)?;
for peer in peers {
let _ = send(peer, json.clone());
}
send(owner, json)
}
impl EventSink for TauriSink {
fn emit(&self, event: IdeEvent) {
if matches!(
@@ -180,13 +197,12 @@ impl EventSink for TauriSink {
}
let result = match &self.window {
Some(label) => {
for target in crate::windows::document_windows(&self.app, label)
.into_iter()
.filter(|_| !matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }))
{
let _ = self.app.emit_to(target.as_str(), IDE_EVENT, &event);
}
self.app.emit_to(label.as_str(), IDE_EVENT, &event)
let peers = if matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }) {
Vec::new()
} else {
crate::windows::document_windows(&self.app, label)
};
fan_out(&event, &peers, label, |window, json| self.app.emit_str_to(window, IDE_EVENT, json))
}
None => self.app.emit(IDE_EVENT, &event),
};
@@ -240,6 +256,56 @@ mod tests {
}
}
/// Counts how often it is serialised.
struct CountingEvent<'a> {
event: &'a IdeEvent,
serialised: AtomicUsize,
}
impl serde::Serialize for CountingEvent<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.serialised.fetch_add(1, Ordering::Relaxed);
self.event.serialize(serializer)
}
}
#[test]
fn fan_out_serialises_once_for_every_window() {
let event = diagnostics("/p/a.rs", "rust-analyzer", "unused");
let counting = CountingEvent { event: &event, serialised: AtomicUsize::new(0) };
let peers: Vec<String> = (1..=7).map(|n| format!("comparison-project-1-{n}")).collect();
let mut sent = Vec::new();
fan_out(&counting, &peers, "project-1", |window, json| {
sent.push((window.to_owned(), json));
Ok(())
})
.unwrap();
assert_eq!(counting.serialised.load(Ordering::Relaxed), 1);
let expected = serde_json::to_string(&event).unwrap();
let windows: Vec<&str> = sent.iter().map(|(window, _)| window.as_str()).collect();
assert_eq!(windows.len(), 8);
assert_eq!(windows.last(), Some(&"project-1"));
assert_eq!(windows[..7], peers.iter().map(String::as_str).collect::<Vec<_>>()[..]);
assert!(sent.iter().all(|(_, json)| json == &expected));
}
#[test]
fn fan_out_ignores_peer_failures_and_returns_the_owners_result() {
let event = task("indexing", false);
let peers = vec!["comparison-project-1-1".to_owned(), "comparison-project-1-2".to_owned()];
let mut reached = Vec::new();
let result = fan_out(&event, &peers, "project-1", |window, _| {
reached.push(window.to_owned());
if window == "project-1" { Err(tauri::Error::WebviewNotFound) } else { Err(tauri::Error::WindowNotFound) }
});
assert!(matches!(result, Err(tauri::Error::WebviewNotFound)));
assert_eq!(reached, ["comparison-project-1-1", "comparison-project-1-2", "project-1"]);
}
#[tokio::test]
async fn coalesces_diagnostics_by_path_and_source() {
let (sink, events) = setup();
+1
View File
@@ -286,6 +286,7 @@ fs_read_range always project_host bin
fs_read_text always project_host bindings async
fs_rename always project_host bindings async
fs_resolve_reference always project_host bindings async
fs_scratches_dir always project_host bindings sync
fs_set_writable always project_host bindings sync
fs_synchronize_directories always project_host bindings async
fs_undo_delete always project_host bindings async
+7
View File
@@ -707,6 +707,11 @@ export const commands = {
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/**
* 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.
*/
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
/**
* Toggle Read-only Attribute: sets the writable bit (and the open document's
* state). Returns whether the file is read-only now.
@@ -2529,6 +2534,8 @@ chosen: string | null } | { type: "thought"; text: string;
startedMs?: number | null } | { type: "tool"; id: string; title: string;
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
kind: string; status: AgentToolStatus; locations: IpcPath[];
/** Images returned by the tool, kept separately from its truncated text. */
images?: AgentImage[];
/** Text the tool reported (command output…), truncated. */
output: string | null; diffs: AgentToolDiff[];
/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */
+10 -2
View File
@@ -238,11 +238,13 @@ function buildDecorations(state: EditorState): DecorationSet {
const lensTheme = EditorView.theme({
// IDEA paints code vision with the colour scheme's Inline hints attribute.
// At least 16px, and taller when the hint font needs it: the row grows with its items, so a
// large editor font or a fallback font that inks below the baseline (CJK) is never cut off.
".cm-openidea-lens": {
display: "flex",
alignItems: "center",
gap: "12px",
height: "16px",
minHeight: "16px",
color: "var(--fg-inlay, var(--fg-muted))",
WebkitUserSelect: "none",
userSelect: "none",
@@ -276,7 +278,10 @@ const lensTheme = EditorView.theme({
// Pinned to the line, the hint may run past the editor's edge (IDEA clips it there); cap it so a
// long one cannot stretch across the whole window first.
maxWidth: "min(60ch, 50vw)",
overflow: "hidden",
// The box is 1em tall (the anchor's `lineHeight: 1`): clip only past the side, so a glyph that
// inks above or below its em box (CJK fallback fonts) still shows whole.
overflowX: "clip",
overflowY: "visible",
pointerEvents: "auto",
},
".cm-openidea-lensItem": {
@@ -293,6 +298,9 @@ const lensTheme = EditorView.theme({
fontFamily: "var(--font-ui)",
fontSize: "calc(1em - 1px)",
},
// The row's items size to the fonts their text is drawn with (fallback fonts included), not to the
// editor's line height, which `font: inherit` brings along.
".cm-openidea-lens > .cm-openidea-lensItem": { lineHeight: "normal" },
".cm-openidea-lensAction": { cursor: "pointer" },
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
".cm-openidea-lensIcon-run": { color: "var(--success)" },
+74
View File
@@ -417,6 +417,79 @@ function leadingCommentStart(state: EditorState, a: number): number {
export type StatementMove = { spec: TransactionSpec } | "noop" | "line";
/** A `case` / `default` label whose branch body follows as its siblings (Go, JavaScript, Java). */
const CASE_LABEL = /^(Case|CaseLabel|DefaultLabel|SwitchLabel)$/;
/**
* Move Statement on a `case` label of a switch whose branches are flat
* (label, then the body as siblings): the branch, from its first stacked
* label to its last non-blank line, swaps with the neighbouring branch, as
* IDEA's case block mover does. `noop` at the first / last branch.
*/
function planCaseMove(state: EditorState, label: Node, up: boolean): StatementMove {
const doc = state.doc;
const block = label.parent!;
const close = doc.lineAt(block.to).number;
const isLabel = (l: number) => {
const n = statementStartingAt(state, l);
return !!n && CASE_LABEL.test(n.type.name) && n.parent?.from === block.from && n.parent.to === block.to;
};
const start = (l: number) => {
while (l > 1 && isLabel(l - 1)) l--;
return l;
};
// The line where the branch starting at `l` ends: its last non-blank line before the next branch or the closing brace.
const end = (l: number) => {
let k = l + 1;
while (k < close && isLabel(k)) k++;
while (k < close && !isLabel(k)) k++;
k--;
while (k > l && firstToken(state, k) === null) k--;
return k;
};
const a = start(doc.lineAt(label.from).number);
const b = end(a);
let s: number;
let e: number;
if (up) {
let p = a - 1;
while (p > 0 && doc.line(p).from > block.from && !isLabel(p)) p--;
if (p < 1 || doc.line(p).from <= block.from || !isLabel(p)) return "noop";
s = start(p);
e = end(s);
} else {
let n = b + 1;
while (n < close && !isLabel(n)) n++;
if (n >= close) return "noop";
s = n;
e = end(n);
}
const [first, second] = up
? [
{ s, e },
{ s: a, e: b },
]
: [
{ s: a, e: b },
{ s, e },
];
const from = doc.line(first.s).from;
const to = doc.line(second.e).to;
const textFirst = state.sliceDoc(from, doc.line(first.e).to);
const textSecond = state.sliceDoc(doc.line(second.s).from, to);
const between = state.sliceDoc(doc.line(first.e).to, doc.line(second.s).from);
const head = state.selection.main.head;
const movedFrom = up ? from : from + textSecond.length + between.length;
return {
spec: {
changes: { from, to, insert: textSecond + between + textFirst },
selection: EditorSelection.cursor(movedFrom + (head - doc.line(a).from)),
scrollIntoView: true,
userEvent: "move.line",
},
};
}
/**
* Move Statement as in IDEA: the statement around the caret (whole lines)
* moves past the next statement; into a block when the neighbour is a block
@@ -429,6 +502,7 @@ export function planStatementMove(state: EditorState, up: boolean): StatementMov
const head = state.selection.main.head;
const cur = statementAround(state, head);
if (!cur) return "line";
if (CASE_LABEL.test(cur.type.name) && cur.parent) return planCaseMove(state, cur, up);
const doc = state.doc;
if (/^[{}]$/.test(cur.type.name)) {
for (let g: Node | null = cur.parent; g; g = g.parent)
+29
View File
@@ -67,6 +67,7 @@ function show(view: EditorView): string {
const javascript = await languages.find((l) => l.name === "JavaScript")!.load();
const yaml = await languages.find((l) => l.name === "YAML")!.load();
const goLang = await languages.find((l) => l.name === "Go")!.load();
describe("Move Statement", () => {
it("moves a multi-line statement as a whole, never one of its lines", () => {
@@ -94,6 +95,34 @@ describe("Move Statement", () => {
expect(v.state.doc.toString()).toBe("function f() {\n a();\n}\nb();");
});
it("moves a Go switch case with its whole body past the neighbouring case", () => {
const go = make(
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tdefault:\n\t\treturn -1\n\t}\n}",
goLang,
);
moveStatementUp(go);
expect(show(go)).toBe(
"func f(n int) int {\n\tswitch n {\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\t}\n}",
);
moveStatementUp(go);
expect(go.state.doc.toString()).toContain("switch n {\n\tcase 1:\n\t\tv := 1");
moveStatementDown(go);
moveStatementDown(go);
expect(show(go)).toBe(
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\t}\n}",
);
moveStatementDown(go);
expect(go.state.doc.toString()).toContain("\t\treturn v\n\t}\n}");
});
it("moves a JavaScript case with its stacked labels and blank line kept between branches", () => {
const v = make("switch (x) {\n case 1:\n a();\n break;\n\n case 2:\n |case 3:\n b();\n}", javascript);
moveStatementUp(v);
expect(v.state.doc.toString()).toBe(
"switch (x) {\n case 2:\n case 3:\n b();\n\n case 1:\n a();\n break;\n}",
);
});
it("passes a neighbouring function as a whole", () => {
const v = make("|a();\nfunction f() {\n b();\n}", javascript);
moveStatementDown(v);
+82
View File
@@ -0,0 +1,82 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { applySnippet, hasLinkedSnippetField } from "./linkedSnippet";
let view: EditorView;
afterEach(() => view.destroy());
function expand(snippet: string) {
view = new EditorView({
state: EditorState.create({ extensions: [EditorState.allowMultipleSelections.of(true)] }),
parent: document.body,
});
applySnippet(view, [{ from: 0, to: 0, snippet }]);
}
const selected = () => view.state.selection.ranges.map(({ from, to }) => view.state.sliceDoc(from, to));
const doc = () => view.state.doc.toString();
const type = (text: string) => view.dispatch(view.state.replaceSelection(text));
const press = (key: string) => runScopeHandlers(view, new KeyboardEvent("keydown", { key }), "editor");
describe("linked snippets", () => {
it("selects the first occurrence of each variable and mirrors edits within its group", () => {
expand("${1:x}/${1:x} ${2:y}/${2:y}${0}");
expect(selected()).toEqual(["x"]);
expect(view.state.selection.main.from).toBe(0);
type("name");
expect(doc()).toBe("name/name y/y");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["y"]);
expect(view.state.selection.main.from).toBe("name/name ".length);
type("label");
expect(doc()).toBe("name/name label/label");
});
it("tracks adjacent empty occurrences and the next variable independently", () => {
expand("${1}${1}${2:end}${0}");
expect(selected()).toEqual([""]);
type("x");
type("y");
expect(doc()).toBe("xyxyend");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["end"]);
type("!");
expect(doc()).toBe("xyxy!");
});
it.each(["Escape", "Tab"])("ends mirroring on %s", (key) => {
expand("${1:x}/${1:x}${0}");
if (key === "Escape") {
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(true);
}
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(false);
const { head } = view.state.selection.main;
expect(head).toBe(key === "Escape" ? 1 : doc().length);
view.dispatch({ changes: { from: 0, to: 1, insert: "changed" } });
expect(doc()).toBe("changed/x");
});
it("keeps a repeated last placeholder active until the end of the snippet", () => {
expand("${1:one} ${2:two}/${2:two}");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["two"]);
type("new");
expect(doc()).toBe("one new/new");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
it("keeps fields linked after a separate edit before the snippet", () => {
expand("call(${1:arg}, ${1:arg})${0}");
const prefix = "import call;\n";
view.dispatch({ changes: { from: 0, insert: prefix }, userEvent: "input.complete" });
expect(selected()).toEqual(["arg"]);
type("value");
expect(doc()).toBe(prefix + "call(value, value)");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
});
+346
View File
@@ -0,0 +1,346 @@
import {
clearSnippet,
closeCompletion,
completionStatus,
pickedCompletion,
snippet,
type Completion,
} from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
ChangeSet,
EditorSelection,
EditorState,
MapMode,
Prec,
StateEffect,
StateField,
Text,
type ChangeSpec,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, keymap, WidgetType, type Command } from "@codemirror/view";
import { isExternalChange } from "@/editor/api";
interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface SnippetRange {
from: number;
to: number;
field: number;
}
interface Segment extends SnippetRange {
site: number;
primary: boolean;
}
interface ActiveSnippet {
segments: readonly Segment[];
active: number;
last: number;
mainSite: number;
completion: boolean;
}
const setSnippet = StateEffect.define<ActiveSnippet | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
function primarySegments(value: ActiveSnippet, field = value.active) {
return value.segments.filter((segment) => segment.field === field && segment.primary);
}
function contains(range: SnippetRange, from: number, to: number): boolean {
return range.from <= from && to <= range.to;
}
function selectionInField(value: ActiveSnippet, selection: EditorSelection): boolean {
const primaries = primarySegments(value);
return selection.ranges.every(({ from, to }) => primaries.some((segment) => contains(segment, from, to)));
}
const fields = StateField.define<ActiveSnippet | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((effect) => effect.is(setSnippet));
if (next) return next.value;
if (!value) return null;
if (tr.docChanged) {
const segments: Segment[] = [];
for (const segment of value.segments) {
const from = tr.changes.mapPos(segment.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(segment.to, 1, MapMode.TrackDel);
if (from === null || to === null || from < (segments.at(-1)?.to ?? 0)) return null;
segments.push({ ...segment, from, to });
}
value = { ...value, segments };
}
return tr.selection && !selectionInField(value, tr.selection) ? null : value;
},
provide: (field) =>
EditorView.decorations.from(field, (value) =>
value
? Decoration.set(
value.segments.map(({ from, to }) => (from === to ? fieldCursor : fieldMark).range(from, to)),
true,
)
: Decoration.none,
),
});
// Keep the edit and its mirrors in one history entry.
const mirrorEdits = EditorState.transactionFilter.of((tr) => {
const value = tr.startState.field(fields, false);
if (
!value ||
!tr.docChanged ||
isExternalChange(tr) ||
tr.isUserEvent("undo") ||
tr.isUserEvent("redo") ||
tr.effects.some((effect) => effect.is(setSnippet))
)
return tr;
const primaries = primarySegments(value);
const edited = new Map<Segment, number>();
let outside = false;
let touchesOtherSegment = false;
tr.changes.iterChangedRanges((from, to, newFrom, newTo) => {
const segment = primaries.find((range) => contains(range, from, to));
if (segment) edited.set(segment, (edited.get(segment) ?? 0) + (newTo - newFrom) - (to - from));
else {
outside = true;
touchesOtherSegment ||= value.segments.some((range) => from <= range.to && to >= range.from);
}
}, true);
if (outside) return edited.size || touchesOtherSegment ? [tr, { effects: setSnippet.of(null) }] : tr;
const changes: ChangeSpec[] = [];
const replacements = new Map<number, Text>();
let typedOffset = 0;
let mirrorOffset = 0;
// Map in source order so neighboring stops keep their own boundaries even when they touch.
const segments = value.segments.map((segment) => {
const start = segment.from + typedOffset;
const from = start + mirrorOffset;
let length = segment.to - segment.from;
const delta = edited.get(segment);
if (delta !== undefined) {
length += delta;
replacements.set(segment.site, tr.newDoc.slice(start, start + length));
typedOffset += delta;
} else if (segment.field === value.active && !segment.primary) {
const insert = replacements.get(segment.site);
if (insert && !insert.eq(tr.newDoc.slice(start, start + length))) {
changes.push({ from: start, to: start + length, insert });
mirrorOffset += insert.length - length;
length = insert.length;
}
}
return { ...segment, from, to: from + length };
});
const mirrors = ChangeSet.of(changes, tr.newDoc.length);
const next = { ...value, segments };
const staysInField = selectionInField(next, tr.newSelection.map(mirrors));
return [tr, { changes: mirrors, effects: setSnippet.of(staysInField ? next : null), sequential: true }];
});
function clearLinkedSnippet(view: EditorView): boolean {
if (!view.state.field(fields, false)) return false;
view.dispatch({ effects: setSnippet.of(null) });
return true;
}
export const escapeSnippet: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearLinkedSnippet(view) || clearSnippet(view);
};
function fieldSelection(value: ActiveSnippet, field: number): EditorSelection {
return EditorSelection.create(
primarySegments(value, field).map(({ from, to }) => EditorSelection.range(from, to)),
value.mainSite,
);
}
function selectField(view: EditorView, value: ActiveSnippet, active: number): boolean {
if (active < 0 || active > value.last) return false;
view.dispatch({
selection: fieldSelection(value, active),
effects: setSnippet.of(active === value.last ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export function hasLinkedSnippetField(state: EditorState, direction: 1 | -1): boolean {
const value = state.field(fields, false);
return !!value && (direction === 1 ? value.active < value.last : value.active > 0);
}
export const nextLiveSnippetField: Command = (view) => {
const value = view.state.field(fields, false);
return !!value && !value.completion && selectField(view, value, value.active + 1);
};
const linkedSnippetExtension = [
fields,
mirrorEdits,
Prec.highest(
keymap.of([
{
key: "Tab",
run: (view) => {
const value = view.state.field(fields);
return (
!!value &&
!view.state.readOnly &&
completionStatus(view.state) !== "active" &&
selectField(view, value, value.active + 1)
);
},
shift: (view) => {
const value = view.state.field(fields);
return !!value && selectField(view, value, value.active - 1);
},
},
{ key: "Escape", run: (view) => !!view.state.field(fields) && escapeSnippet(view) },
]),
),
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const segment = value.segments.find((range) => contains(range, pos, pos));
return !!segment && segment.field !== value.active && selectField(view, value, segment.field);
},
}),
];
function codeMirrorSnippet(tr: Transaction): { active: number; ranges: SnippetRange[] } | undefined {
// CodeMirror exposes the native snippet's unmerged ranges through its state effect.
return tr.effects
.map(({ value }) => value)
.find((value) => {
return value && typeof value.active === "number" && Array.isArray(value.ranges);
});
}
export function snippetFieldMoved(tr: Transaction): number | undefined {
const linked = tr.effects.find((effect) => effect.is(setSnippet));
if (linked) return linked.value?.completion ? undefined : linked.value?.active;
return codeMirrorSnippet(tr)?.active;
}
/** Render with CodeMirror to keep its snippet syntax and indentation. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
const state = EditorState.create({
doc: source.doc.slice(line.from, source.doc.lineAt(site.to).to),
selection: EditorSelection.cursor(to),
extensions: [indentUnit.of(source.facet(indentUnit))],
});
let insert = Text.empty;
let ranges: SnippetRange[] = [];
// An extra anonymous stop exposes the range effect even when a snippet has only one field.
snippet(site.snippet + "#{}")(
{
state,
dispatch(tr) {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
ranges = codeMirrorSnippet(tr)?.ranges ?? [];
},
},
null,
from,
to,
);
const end = ranges.at(-1);
const seen = new Set<number>();
const segments = ranges.slice(0, -1).map((range) => {
const primary = !seen.has(range.field);
seen.add(range.field);
return { ...range, primary };
});
return { ...site, offset: from, insert, segments, end };
}
export function applySnippet(view: EditorView, sites: readonly SnippetSite[], completion: Completion | null = null) {
const { state } = view;
const { main } = state.selection;
const entries = sites.map((site) =>
instantiate(state, { ...site, to: sites.length === 1 && site.to === main.from ? main.to : site.to }),
);
if (entries.length === 1 && entries[0]!.segments.every((segment) => segment.primary)) {
const { snippet: source, from, to } = sites[0]!;
clearLinkedSnippet(view);
snippet(source)(view, completion, from, to);
return;
}
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
let last = Math.max(...entries[0]!.segments.map(({ field }) => field));
const needsEnd = entries.some(({ segments }) =>
segments.some((segment) => segment.field === last && !segment.primary),
);
if (needsEnd) last++;
const segments = entries.flatMap((entry, site) => {
const offset = changes.mapPos(entry.from, -1) - entry.offset;
const ranges = [...entry.segments];
if (needsEnd && entry.end) ranges.push({ ...entry.end, primary: true });
return ranges.map((segment) => ({ ...segment, site, from: segment.from + offset, to: segment.to + offset }));
});
const value = {
segments,
active: 0,
last,
mainSite: sites.length === 1 ? 0 : state.selection.mainIndex,
completion: !!completion,
};
clearSnippet(view);
view.dispatch({
changes,
selection: fieldSelection(value, 0),
effects: [
setSnippet.of(last > 0 ? value : null),
...(state.field(fields, false) === undefined ? [StateEffect.appendConfig.of(linkedSnippetExtension)] : []),
],
annotations: completion ? pickedCompletion.of(completion) : isolateHistory.of("full"),
userEvent: completion ? "input.complete" : undefined,
scrollIntoView: true,
});
}
+113 -5
View File
@@ -68,18 +68,30 @@ function type(view: EditorView, text: string) {
);
}
/** One Backspace before every caret. */
/** One Backspace at every caret, or over every selection. */
function backspace(view: EditorView) {
const { state } = view;
view.dispatch(
state.changeByRange((r) => ({
changes: { from: Math.max(0, r.head - 1), to: r.head },
range: EditorSelection.cursor(Math.max(0, r.head - 1)),
})),
state.changeByRange((r) => {
const from = r.empty ? Math.max(0, r.head - 1) : r.from;
return { changes: { from, to: r.to }, range: EditorSelection.cursor(from) };
}),
{ userEvent: "delete.backward" },
);
}
/** One Delete after every caret. */
function deleteForward(view: EditorView) {
const { state } = view;
view.dispatch(
state.changeByRange((r) => ({
changes: { from: r.head, to: Math.min(state.doc.length, r.head + 1) },
range: EditorSelection.cursor(r.head),
})),
{ userEvent: "delete.forward" },
);
}
describe("linked html tags", () => {
it("renames the closing tag while the opening one is typed", () => {
const v = make('<div| class="container">\n Content\n</div>');
@@ -192,6 +204,84 @@ describe("linked html tags", () => {
expect(closing.state.doc.toString()).toBe("<div>content</di>v>");
});
// #5314: removing a tag piece by piece is a deletion, not a rename. Once its `>` (or `</`)
// is gone the tag is incomplete, and the name edits after that must not follow.
describe("deleting a whole tag", () => {
it("leaves the opening tag alone while the closing tag is backspaced away", () => {
const v = make("<div>x</div>|");
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(show(v)).toBe("<div>x|");
});
it("leaves the closing tag alone while the opening tag is backspaced away", () => {
const v = make("<div>|x</div>");
for (let i = 0; i < "<div>".length; i++) backspace(v);
expect(show(v)).toBe("|x</div>");
});
it("leaves the opening tag alone when the closing tag is deleted forwards", () => {
const v = make("<div>x|</div>\n<p>y</p>");
for (let i = 0; i < "</div>".length; i++) deleteForward(v);
expect(v.state.doc.toString()).toBe("<div>x\n<p>y</p>");
});
it("leaves the closing tag alone while an opening tag followed by children is backspaced away", () => {
const v = make("<div>|\n <span>y</span>\n</div>");
for (let i = 0; i < "<div>".length; i++) backspace(v);
expect(show(v)).toBe("|\n <span>y</span>\n</div>");
const inline = make("<div>|<span>y</span></div>");
for (let i = 0; i < "<div>".length; i++) backspace(inline);
expect(show(inline)).toBe("|<span>y</span></div>");
});
it("leaves the other tag alone when a selection covering a tag is deleted", () => {
const v = make("<div>x[</div>]");
backspace(v);
expect(show(v)).toBe("<div>x|");
const open = make("[<div>]x</div>");
backspace(open);
expect(show(open)).toBe("|x</div>");
});
it("leaves the other tag alone when a cut runs from inside the name past the tag", () => {
const v = make("<div>x</d[iv>\n]<p>y</p>");
backspace(v);
expect(v.state.doc.toString()).toBe("<div>x</d<p>y</p>");
});
it("does not rename into or out of a tag that lost its `>`", () => {
const v = make("<div|>x</div");
type(v, "s");
expect(v.state.doc.toString()).toBe("<divs>x</div");
const open = make("<div\n x</di|v>");
backspace(open);
expect(open.state.doc.toString()).toBe("<div\n x</dv>");
});
it("deletes the closing tags at every caret, leaving the opening tags alone", () => {
const v = make("<p>a</p>|\n<b>c</b>|");
for (let i = 0; i < "</p>".length; i++) backspace(v);
expect(show(v)).toBe("<p>a|\n<b>c|");
});
it("undo brings back the deleted closing tag and keeps the opening one", () => {
const v = make("<div>x[</div>]", history());
backspace(v);
expect(v.state.doc.toString()).toBe("<div>x");
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe("<div>x</div>");
});
it("still renames after the `>` is typed back", () => {
const v = make("<div>x</div|");
type(v, ">");
expect(v.state.doc.toString()).toBe("<div>x</div>");
v.dispatch({ selection: { anchor: "<div".length } });
type(v, "s");
expect(v.state.doc.toString()).toBe("<divs>x</divs>");
});
});
it("undoes the pair as one step and redoes it", () => {
const v = make("<div|></div>", history());
type(v, "x");
@@ -219,6 +309,12 @@ describe("linked html tags", () => {
type(v, "s");
expect(v.state.doc.toString()).toBe('<divs class="a">x</divs>');
});
it(`leaves the opening tag alone while the closing tag is backspaced away in ${name}`, () => {
const v = makeWith([language(), linkedTags], '<div class="a">x</div>|');
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(v.state.doc.toString()).toBe('<div class="a">x');
});
}
});
@@ -261,6 +357,18 @@ describe("linked html tags", () => {
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
});
it("leaves the other tag alone while a tag is backspaced away", () => {
const v = tsx("const a = <div>x</div>|;");
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(v.state.doc.toString()).toBe("const a = <div>x;");
const m = tsx("const a = (\n <div>|\n <span>y</span>\n </div>\n);");
for (let i = 0; i < "<div>".length; i++) backspace(m);
expect(m.state.doc.toString()).toBe("const a = (\n \n <span>y</span>\n </div>\n);");
const w = tsx("const a = <Foo>|x</Foo>;");
for (let i = 0; i < "<Foo>".length; i++) backspace(w);
expect(w.state.doc.toString()).toBe("const a = x</Foo>;");
});
it("undoes both tags in one step", () => {
const v = tsx("const a = <div|></div>;");
type(v, "x");
+17 -7
View File
@@ -10,9 +10,9 @@
* A transaction whose change lies inside one tag's name is extended with
* the same edit at the same offset in the counterpart's name — one
* transaction, so undo takes both back together. Without a matching tag (void
* and self-closing tags, unclosed elements, a stray close tag) or with the two
* names already different (malformed markup) nothing follows: the tags stay as
* they are.
* and self-closing tags, unclosed elements, a stray close tag), with either tag
* missing its `>` (a tag being deleted piece by piece), or with the two names
* already different (malformed markup) nothing follows: the tags stay as they are.
*/
import { EditorState, type Extension, type Transaction } from "@codemirror/state";
import { syntaxTree } from "@codemirror/language";
@@ -39,21 +39,31 @@ function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null
return null;
}
/** The matching tag's name of the same element, or null without one. */
/**
* Whether a tag still ends in its `>`. A tag that lost it — `</div` while Backspace
* works through `</div>` — is being deleted, not renamed.
*/
function isComplete(tag: SyntaxNode | null): tag is SyntaxNode {
const last = tag?.lastChild?.name;
return last === "EndTag" || last === "JSXEndTag";
}
/** The matching tag's name of the same element, or null without one or while either tag is incomplete. */
function counterpartName(name: SyntaxNode): SyntaxNode | null {
const tag = name.parent;
const element = tag?.parent;
if (!tag || !element) return null;
if (!isComplete(tag) || !element) return null;
if (element.name === "JSXElement") {
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
if (!isComplete(other)) return null;
for (let c = other.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
return null;
}
if (element.name !== "Element") return null;
const other = element.getChild(
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
);
return other?.getChild("TagName") ?? null;
return isComplete(other) ? other.getChild("TagName") : null;
}
/** Insertions at a name's edge must extend the name; structural characters end it. */
+41
View File
@@ -8,6 +8,7 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
import * as contributions from "@/workbench/contributions";
import {
registerEditorKind,
registerMenuGroup,
registerTextEditorWrapper,
setProjectViewLead,
useProjectViewLead,
@@ -579,6 +580,46 @@ describe("EditorController", () => {
useProject.setState({ project: null, settings: null });
});
it("offers contributed Copy Path links in the tab menu like the other copy menus", async () => {
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
const dispose = registerActions(
["project.copyAbsolutePath", "project.copyFileName", "project.copyRelativePath"].map((id) => ({
id,
title: id,
run: () => undefined,
})),
);
const links = registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: () => [{ id: "test.copyLink", label: "GitHub Link", verbatim: true, run: () => undefined }],
});
try {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const s = useTabs.getState();
const pane = s.panes[s.activePane]!;
const submenu = resolveMenuItems(ctrl.tabMenu(pane.id, pane.tabs[0]!)).find(
(i) => i.label === "Copy Path/Reference…",
)!.submenu!;
expect(resolveMenuItems(submenu).map((i) => (i.kind === "separator" ? "-" : i.label))).toEqual([
"Absolute Path",
"File Name",
"Path From Content Root",
"-",
"GitHub Link",
]);
} finally {
dispose();
links();
useProject.setState({ project: null, settings: null });
}
});
it.each(["editor", "tab"])(
"offers grouped Git actions in the %s menu and preserves action enablement",
async (menu) => {
+3
View File
@@ -2324,6 +2324,9 @@ export class EditorController implements SlotHost {
},
] as MenuItem[])
: []),
// The links the project view and the editor chooser offer (features/vcs: GitHub Link).
{ kind: "separator" },
...menuGroupItems("copyPath", { paths: [path] }),
],
},
{ kind: "separator" },
+8 -2
View File
@@ -507,7 +507,13 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
)}
<FindBar paneId={paneId} />
{crumbs && (
<PaneBreadcrumbs key={wrapper?.id} wrapper={wrapper} path={tab.input.path!} tabId={tab.id} position="top" />
<PaneBreadcrumbs
key={`top:${wrapper?.id}`}
wrapper={wrapper}
path={tab.input.path!}
tabId={tab.id}
position="top"
/>
)}
{wrapper ? (
<wrapper.component
@@ -523,7 +529,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
)}
{crumbs && (
<PaneBreadcrumbs
key={wrapper?.id}
key={`bottom:${wrapper?.id}`}
wrapper={wrapper}
path={tab.input.path!}
tabId={tab.id}
+17
View File
@@ -297,6 +297,23 @@ describe("applying completions", () => {
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
});
it("edits repeated LSP placeholders from one selection", () => {
const { view, req } = setup("lo|", "", [EditorState.allowMultipleSelections.of(true)]);
const completion = makeCompletion(
item({ kind: "snippet", insertText: "log(${1:value}, $1, ${2:label})$0", isSnippet: true }),
req,
);
apply(view, completion, 0);
expect(view.state.selection.ranges).toHaveLength(1);
expect(view.state.doc.toString()).toBe("log(value, value, label)");
view.dispatch(view.state.replaceSelection("name"));
expect(view.state.doc.toString()).toBe("log(name, name, label)");
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Enter" }), "editor")).toBe(false);
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
const { from, to } = view.state.selection.main;
expect(view.state.sliceDoc(from, to)).toBe("label");
});
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
const executed: string[] = [];
setInvokeRoute((cmd) => {
+3 -2
View File
@@ -16,7 +16,6 @@ import {
moveCompletionSelection,
pickedCompletion,
selectedCompletion,
snippet,
startCompletion,
type Completion,
type CompletionContext,
@@ -53,6 +52,7 @@ import {
typeColumnText,
withoutDuplicates,
} from "./completionItems";
import { applySnippet } from "@/editor/core/cm/linkedSnippet";
import { lspSnippetToCm, lspSnippetToPlainWithCaret, snippetVariables } from "./snippet";
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, posToOffset, textEditsToChanges } from "./positions";
@@ -296,7 +296,8 @@ export function applyLspCompletion(
start = tr.changes.mapPos(start, 1);
end = tr.changes.mapPos(end, 1);
}
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
// signature help says there is nothing to pass.
const head = view.state.selection.main.head;
+3 -1
View File
@@ -4,6 +4,7 @@
* it follows the caret and closes when the server reports no signature;
* ⇥ / ⇧⇥ move to the next / previous argument.
*/
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import {
@@ -289,7 +290,8 @@ function moveToArgument(view: EditorView, dir: 1 | -1): boolean {
if (!state.field(signatureField, false) || state.readOnly) return false;
if (state.selection.ranges.length > 1 || completionStatus(state) === "active") return false;
// Snippet / template fields and the in-place rename own ⇥.
if (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)) return false;
if (hasLinkedSnippetField(state, dir) || (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)))
return false;
if (inplaceRenameActive(state)) return false;
const head = state.selection.main.head;
const to = argumentStop(state.doc.toString(), head, dir);
+8 -2
View File
@@ -193,11 +193,17 @@ export function lspSnippetToCm(snippet: string, vars: SnippetVariables = {}): st
const hasField = nodes.some(
(n) => n.t === "tab" || n.t === "choice" || (n.t === "var" && vars[n.name] === undefined && !n.children),
);
const defaults = new Map<number, string>();
for (const node of nodes) {
if (node.t === "text" || node.t === "var" || node.n === 0 || defaults.has(node.n)) continue;
if (node.t === "choice") defaults.set(node.n, node.options[0] ?? "");
else if (node.children) defaults.set(node.n, flatten(node.children, vars));
}
let out = "";
for (const n of nodes) {
if (n.t === "text") out += escapeText(n.v);
else if (n.t === "tab") out += field(n.n, n.children ? flatten(n.children, vars) : "");
else if (n.t === "choice") out += field(n.n, n.options[0] ?? "");
else if (n.t === "tab") out += field(n.n, defaults.get(n.n) ?? (n.children ? flatten(n.children, vars) : ""));
else if (n.t === "choice") out += field(n.n, defaults.get(n.n) ?? n.options[0] ?? "");
else {
const v = vars[n.name];
if (v !== undefined) out += escapeText(v);
-1
View File
@@ -201,7 +201,6 @@ export const lspTheme = EditorView.theme({
flex: "0 1 auto",
minWidth: "0",
marginLeft: "auto",
paddingLeft: "16px",
textAlign: "right",
color: "var(--fg-subtle)",
overflow: "hidden",
+65 -32
View File
@@ -25,6 +25,7 @@ import { isNavigating, onNavigation } from "@/editor/lsp/foreground";
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
import { openPopup } from "@/editor/lsp/popupStore";
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
import {
commands,
isCancelled,
@@ -542,13 +543,32 @@ async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Loc
}
}
/** Opens the single target, or the chooser over several. */
/** Resolves each declaration's targets before opening the shared chooser. */
export async function openMarkerTargets(
marker: LineMarker,
markers: readonly [LineMarker, ...LineMarker[]],
anchor: { x: number; y: number },
doc: DocId | null = null,
) {
const targets = await markerTargets(marker, doc);
const [first] = markers;
const merged = markers.length > 1;
let targets: DeclarationTarget[] = (
await Promise.all(
markers.map(async (marker) => {
const locations = await markerTargets(marker, doc);
// Generated methods can share a source location. Keep their names visible in the chooser.
return merged && marker.method ? locations.map((target) => ({ ...target, name: marker.name })) : locations;
}),
)
).flat();
if (merged) {
const seen = new Set<string>();
targets = targets.filter(({ path, range, name }) => {
const key = JSON.stringify([path, range.start.line, range.start.col, name]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
if (targets.length === 1) {
await navigateTo(targets[0]!);
return;
@@ -556,9 +576,9 @@ export async function openMarkerTargets(
openPopup({
kind: "list",
anchor,
title: marker.chooserTitle,
title: merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle,
items: await locationItems(targets),
pin: pinToFind(marker.name, targets),
pin: pinToFind([...new Set(markers.map((m) => m.name))].join(", "), targets),
});
}
@@ -587,41 +607,50 @@ function place(doc: Text, markers: readonly LineMarker[]): PlacedMarker[] {
}
const sameMarkers = (a: readonly PlacedMarker[], b: readonly PlacedMarker[]) =>
a.length === b.length &&
a.every(
(m, i) => m.pos === b[i]!.pos && m.marker.kind === b[i]!.marker.kind && m.marker.tooltip === b[i]!.marker.tooltip,
);
a.length === b.length && a.every((m, i) => m.pos === b[i]!.pos && m.marker === b[i]!.marker);
class InheritanceMarker extends GutterMarker {
constructor(readonly marker: LineMarker) {
readonly kind: LineMarker["kind"];
readonly tooltip: string;
constructor(readonly markers: readonly [LineMarker, ...LineMarker[]]) {
super();
const [first] = markers;
this.kind = first.kind;
this.tooltip =
markers.length === 1 ? first.tooltip : [...new Set(markers.map((m) => `${m.name} — ${m.tooltip}`))].join("\n");
}
override eq(other: GutterMarker): boolean {
return (
other instanceof InheritanceMarker &&
other.marker.kind === this.marker.kind &&
other.marker.tooltip === this.marker.tooltip
);
return other instanceof InheritanceMarker && other.kind === this.kind && other.tooltip === this.tooltip;
}
override toDOM(): Node {
const el = document.createElement("div");
el.className = `${styles.marker} cm-openidea-lineMarker-${this.marker.kind}`;
el.dataset.kind = this.marker.kind;
el.title = this.marker.tooltip;
el.className = `${styles.marker} cm-openidea-lineMarker-${this.kind}`;
el.dataset.kind = this.kind;
el.title = this.tooltip;
el.setAttribute("role", "button");
el.setAttribute("aria-label", this.marker.tooltip);
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.marker.kind]) ?? "";
el.setAttribute("aria-label", this.tooltip);
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.kind]) ?? "";
return el;
}
}
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<GutterMarker>>();
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<InheritanceMarker>>();
function markerSet(placed: readonly PlacedMarker[]): RangeSet<GutterMarker> {
function markerSet(placed: readonly PlacedMarker[]): RangeSet<InheritanceMarker> {
let set = gutterMarkers.get(placed);
if (!set) {
const groups = new Map<string, { pos: number; markers: [LineMarker, ...LineMarker[]] }>();
for (const { pos, marker } of placed) {
const key = `${pos}:${marker.kind}`;
const group = groups.get(key);
if (group) group.markers.push(marker);
else groups.set(key, { pos, markers: [marker] });
}
set = RangeSet.of(
placed.map((m) => new InheritanceMarker(m.marker).range(m.pos)),
[...groups.values()].map(({ pos, markers }) => new InheritanceMarker(markers).range(pos)),
true,
);
gutterMarkers.set(placed, set);
@@ -829,10 +858,14 @@ export function markerDeps(
};
}
function markerAt(view: EditorView, lineFrom: number, el: Element | null): LineMarker | null {
const onLine = view.state.field(markersField).filter((m) => m.pos === lineFrom);
const kind = (el?.closest(`.${styles.marker}`) as HTMLElement | null)?.dataset.kind;
return (onLine.find((m) => m.marker.kind === kind) ?? (onLine.length === 1 ? onLine[0] : null))?.marker ?? null;
function markerAt(view: EditorView, lineFrom: number, kind: string | undefined): InheritanceMarker | undefined {
let match: InheritanceMarker | undefined;
markerSet(view.state.field(markersField)).between(lineFrom, lineFrom, (pos, _to, marker) => {
if (pos !== lineFrom || marker.kind !== kind) return;
match = marker;
return false;
});
return match;
}
export function implementationGutter(ctx: EditorDocContext): Extension {
@@ -846,13 +879,13 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
markers: (view) => markerSet(view.state.field(markersField)),
mousedown: (view, block, e) => {
if (e.button !== 0) return false;
const target = e.target instanceof Element ? e.target : null;
if (!target?.closest(`.${styles.marker}`)) return false;
const marker = markerAt(view, block.from, target);
const target = e.target instanceof Element ? e.target.closest<HTMLElement>(`.${styles.marker}`) : null;
if (!target) return false;
const marker = markerAt(view, block.from, target.dataset.kind);
if (!marker) return false;
e.preventDefault();
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
const rect = target.getBoundingClientRect();
void openMarkerTargets(marker.markers, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
return true;
},
}),
+137 -32
View File
@@ -1,4 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import { lspDoc } from "@/editor/lsp/lsp";
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
import {
IpcError,
commands,
@@ -14,14 +19,15 @@ const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi
vi.mock("@/editor/lsp/navigation", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
locationItems: async (locs: Location[]) => locs.map((l, i) => ({ id: `${i}`, label: l.path, run: () => {} })),
locationItems: async (locs: DeclarationTarget[]) =>
locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path, run: () => {} })),
}));
vi.mock("@/editor/lsp/popupStore", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/popupStore")>()),
openPopup: nav.openPopup,
}));
import { candidateKey, markerCandidates, type MarkerCandidate } from "./lineMarkers";
import { candidateKey, markerCandidates, type LineMarker, type MarkerCandidate } from "./lineMarkers";
import { Text } from "@codemirror/state";
import {
affectsMarkers,
@@ -29,6 +35,7 @@ import {
emptyCache,
enabledGroups,
fillMarkers,
implementationGutter,
libraryCandidates,
markerBatches,
markerDeps,
@@ -539,16 +546,18 @@ describe("clicking a marker", () => {
it("navigates to a single target", async () => {
const target = loc("/p/Circle.java", 0, 13);
await openMarkerTargets(
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
[
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
],
{ x: 1, y: 2 },
);
expect(nav.navigateTo).toHaveBeenCalledWith(target);
@@ -562,16 +571,18 @@ describe("clicking a marker", () => {
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
await openMarkerTargets(
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
[
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
],
{ x: 1, y: 2 },
7,
);
@@ -585,16 +596,18 @@ describe("clicking a marker", () => {
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
expect(candidateKey(candidate())).toBe("0:17:Shape");
await openMarkerTargets(
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
chooserTitle: "Choose Implementation of Shape (2 found)",
},
[
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
chooserTitle: "Choose Implementation of Shape (2 found)",
},
],
{ x: 1, y: 2 },
);
expect(nav.navigateTo).not.toHaveBeenCalled();
@@ -609,6 +622,98 @@ describe("clicking a marker", () => {
});
});
describe("inheritance gutter", () => {
it.each([
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
{ kind: "overridden", language: "java", declaration: "@Data" },
{ kind: "implementing", language: "go", declaration: "type Square struct{}" },
{ kind: "implemented", language: "rust", declaration: "trait Shape { fn area(); fn label(); }" },
] as const)("merges $language $kind markers by line and kind", async ({ kind, language, declaration }) => {
vi.useFakeTimers();
nav.navigateTo.mockClear();
nav.openPopup.mockClear();
const ctx = { doc: 1, path: `/p/gutter-${kind}`, language, uiMode: null, readOnly: false };
const doc = Text.of([declaration, "another declaration"]);
const markers = markersOf(ctx.path, doc);
const otherKind = kind === "overridden" ? "overriding" : "overridden";
const inputs = [
{ kind, name: "build", line: 0 },
{ kind: otherKind, name: "other", line: 0 },
{ kind, name: "self", line: 0 },
{ kind, name: "build", line: 0 },
{ kind, name: "later", line: 1 },
] as const;
const candidates = inputs.map(({ name, line }, i): MarkerCandidate => ({
name,
line,
symbol: `${name}(${i})`,
col: 0,
method: true,
abstract: false,
inheritable: false,
overriding: false,
owner: null,
}));
markers.outline = { items: [], candidates };
inputs.forEach((input, i) => {
const marker: LineMarker = {
...input,
col: 0,
method: true,
targets: [
loc(
language === "java" && input.kind === kind && input.line === 0 ? "/p/BaseOrder.java" : `/p/${input.name}`,
2,
),
],
tooltip: `Target for ${input.name}`,
chooserTitle: input.name,
};
const group = marker.kind === "implemented" || marker.kind === "overridden" ? "inheritors" : "supers";
markers.cache.entries.set(candidateKey(candidates[i]!), { [group]: marker });
});
const view = new EditorView({
doc,
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
try {
await vi.advanceTimersByTimeAsync(500);
const icons = [...view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`)];
expect(icons).toHaveLength(2);
expect(icons[0]!.title).toContain("Target for build");
expect(icons[0]!.title).toContain("Target for self");
expect(icons[0]!.title).not.toContain("Target for later");
expect(icons[0]!.parentElement!.querySelector(`.cm-openidea-lineMarker-${otherKind}`)).not.toBeNull();
fireEvent.mouseDown(icons[0]!, { button: 0 });
await vi.advanceTimersByTimeAsync(0);
expect(nav.navigateTo).not.toHaveBeenCalled();
expect(nav.openPopup.mock.calls[0]![0].items.map((item: { label: string }) => item.label)).toEqual([
"build",
"self",
]);
// CodeMirror finds the clicked line by the gutter row's screen position.
const block = view.lineBlockAt(doc.line(2).from);
vi.spyOn(icons[1]!.parentElement!, "getBoundingClientRect").mockReturnValue(
new DOMRect(0, view.documentTop + block.top, 10, block.height),
);
fireEvent.mouseDown(icons[1]!, { button: 0 });
await vi.advanceTimersByTimeAsync(0);
expect(nav.navigateTo).toHaveBeenCalledWith(loc("/p/later", 2));
view.dispatch({ changes: { from: doc.line(1).to, to: doc.line(2).from, insert: " " } });
const joined = view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`);
expect(joined).toHaveLength(1);
expect(joined[0]!.title).toContain("Target for later");
} finally {
view.destroy();
vi.useRealTimers();
}
});
});
describe("overriders of a type's methods from its subtypes", () => {
// Shapes and names as jdtls answers them (outline names carry the signature).
const REPO = [
+2
View File
@@ -36,7 +36,9 @@
outline: none;
}
.field :global(.cm-scroller) {
height: auto;
max-height: 280px;
overflow-x: hidden;
overflow-y: auto;
font-family: inherit;
line-height: 1.5;
+40
View File
@@ -0,0 +1,40 @@
import { useState } from "react";
import type { AgentImage } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { IconButton } from "@/ui";
import { ImagePreview, imageSrc } from "./ImagePreview";
import styles from "./Session.module.css";
/** Image thumbnails; a click opens the full image, `onRemove` adds a remove button to each. */
export function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (index: number) => void }) {
const tx = useTx();
const [open, setOpen] = useState<AgentImage | null>(null);
if (images.length === 0) return null;
return (
<div className={styles.images}>
{images.map((img, i) => (
<span key={i} className={styles.imageItem}>
<button
type="button"
className={styles.imageButton}
title={img.name ?? undefined}
onClick={() => setOpen(img)}
>
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
)}
</span>
))}
<ImagePreview image={open} onClose={() => setOpen(null)} />
</div>
);
}
+10 -1
View File
@@ -231,7 +231,7 @@
content-visibility: auto;
}
/* WebKit leaves a stale selection highlight on rows that skipped rendering (`useOffscreenRows`). */
.stream[data-selection] > .conversationRow[data-measured] {
.conversationRow[data-measured][data-selection] {
content-visibility: visible;
}
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
@@ -1197,6 +1197,15 @@
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.toolImages,
.toolImages .imageItem,
.toolImages .imageButton {
max-width: 100%;
}
.toolImages .image {
max-width: min(100%, 640px);
max-height: 320px;
}
.removeImage {
position: absolute;
top: 4px;
+58 -30
View File
@@ -1,4 +1,4 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import {
@@ -27,6 +27,7 @@ import {
type RefObject,
} from "react";
import { useAgentSettings } from "../agentSettings";
import { ImageStrip } from "../ImageStrip";
import {
entriesKey,
isBusy,
@@ -147,7 +148,14 @@ function useOffscreenRows(
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
// Keep independent of `visible`: when a kept-alive tab hides, `data-selection` must stay until
// the selection leaves and WebKit clears off-screen rows' highlights before skipping again.
useSelectionVisibility(ref, enabled);
useSelectionVisibility(ref, enabled, `.${styles.conversationRow}`);
}
/** Images remain visible beside the work's folded summary, without duplicating them when it opens. */
function toolImages(row: ConversationRow): AgentImage[] {
if (row.kind === "turn") return row.rows.flatMap(toolImages);
const entries = row.kind === "process" ? row.entries.map(({ entry }) => entry) : [row.entry];
return entries.flatMap((entry) => (entry.type === "tool" ? (entry.images ?? []) : []));
}
interface StreamProps {
@@ -215,7 +223,7 @@ export function Stream({
const restored = useRef(false);
const previousLength = useRef(entries?.length ?? 0);
/** Scrolled away from the end: offer one click back to the latest message. */
const [away, setAway] = useState(() => positions.get(key)?.stick === false);
const [away, setAway] = useState(false);
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
@@ -244,10 +252,17 @@ export function Stream({
if (!position.current.stick) return;
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
},
[key, positions],
);
const updateJumpVisibility = useCallback((el: HTMLElement) => {
// An upward gesture releases following before anything moves. Only offer a jump
// when there is actual content below the viewport, excluding the fold spacer.
setAway(
!position.current.stick &&
el.scrollHeight - el.clientHeight - el.scrollTop > (parseFloat(getComputedStyle(el).paddingBottom) || 0) + 1,
);
}, []);
// Earlier entries are prepended above the view: remember where the first painted row is
// so the content stays put and the scrollbar doesn't jump under the pointer.
const anchor = useRef<{ el: Element; top: number } | null>(null);
@@ -322,8 +337,10 @@ export function Stream({
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
if (el && position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
}, []);
if (!el) return;
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
}, [updateJumpVisibility]);
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
@@ -353,6 +370,7 @@ export function Stream({
if (!dragging.current) el.scrollTop = el.scrollHeight;
} else if (!restored.current) el.scrollTop = position.current.top;
restored.current = true;
updateJumpVisibility(el);
});
useLayoutEffect(() => {
// Prepending earlier entries moved the first painted row down: follow it, so the same
@@ -363,6 +381,7 @@ export function Stream({
anchor.current = null;
if (position.current.stick || !from.el.isConnected) return;
scroller.scrollTop += from.el.getBoundingClientRect().top - from.top;
updateJumpVisibility(scroller);
});
useLayoutEffect(() => {
const el = ref.current;
@@ -370,13 +389,14 @@ export function Stream({
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
});
observer.observe(el);
return () => {
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack]);
}, [key, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container
@@ -431,10 +451,10 @@ export function Stream({
if (position.current.stick && el.scrollHeight - el.scrollTop - el.clientHeight >= 1) {
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
}
updateJumpVisibility(el);
},
[key, positions, setSlack, trimSlack],
[key, positions, setSlack, trimSlack, updateJumpVisibility],
);
/** Back to the end of the stream; following resumes from there. */
const jumpToLatest = useCallback(() => {
@@ -569,7 +589,7 @@ export function Stream({
if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight;
position.current = { top: el.scrollTop, stick };
positions.set(key, position.current);
setAway(!position.current.stick);
updateJumpVisibility(el);
// Reached the top of what is painted: fetch the earlier entries, but only
// once the drag has settled.
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
@@ -616,27 +636,35 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
rows.map((row) => (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
</div>
</div>
)}
{renderConversationRow(row)}
</div>
))
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
+1 -35
View File
@@ -7,7 +7,7 @@ import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { ImagePreview, imageSrc } from "../ImagePreview";
import { ImageStrip } from "../ImageStrip";
import { ReferencedText } from "../ReferenceChip";
import styles from "../Session.module.css";
import { SubmitButton } from "../SubmitButton";
@@ -425,37 +425,3 @@ function MessageEditor({
</div>
);
}
/** Image thumbnails; a click opens the full image, `onRemove` adds a remove button to each. */
function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (index: number) => void }) {
const tx = useTx();
const [open, setOpen] = useState<AgentImage | null>(null);
if (images.length === 0) return null;
return (
<div className={styles.images}>
{images.map((img, i) => (
<span key={i} className={styles.imageItem}>
<button
type="button"
className={styles.imageButton}
title={img.name ?? undefined}
onClick={() => setOpen(img)}
>
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
)}
</span>
))}
<ImagePreview image={open} onClose={() => setOpen(null)} />
</div>
);
}
+56
View File
@@ -459,6 +459,37 @@ describe("process folding", () => {
});
});
describe("tool result images", () => {
it.each([
["grouped", true],
["grouped", false],
["each", true],
["each", false],
] as const)("keeps tool images visible with %s tools and folded turns=%s", async (toolCalls, foldTurns) => {
useProject.setState({ settings: { agents: { toolCalls, foldTurns } } as never });
const image = { mimeType: "image/png", data: "aW1hZ2U=", name: null };
backend.entries.set("A", [
{ type: "user", text: "Render a preview", attachments: [], steered: false, sentMs: 1000, doneMs: 2000 },
{ type: "thought", text: "Rendering" },
tool("preview", { images: [image] }),
tool("inspect", { output: "Preview ready" }),
{ type: "agent", text: "Here is the result." },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Here is the result.");
const preview = screen.getByRole("img", { name: "Image" });
expect(preview).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
expect(preview.closest("details")).toBeNull();
fireEvent.click(preview.closest("button")!);
const dialog = await screen.findByRole("dialog", { name: "Image" });
expect(within(dialog).getByRole("img")).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
fireEvent.click(within(dialog).getByText("Close", { selector: "button" }));
expect(screen.queryByRole("dialog")).toBeNull();
expect(screen.getAllByRole("img", { name: "Image" })).toHaveLength(1);
});
});
describe("turn folding", () => {
it("folds a finished turn's work under its message and keeps the reply", async () => {
backend.entries.set("A", [
@@ -738,6 +769,31 @@ describe("the conversation selection", () => {
});
describe("scrolling", () => {
it("hides Jump to Latest while the end is visible even when following has stopped", async () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
let height = 1000;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.style.paddingBottom = "12px";
el.scrollTop = 599.75;
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -2 });
const jump = () => screen.queryByRole("button", { name: "Jump to Latest" });
expect(jump()).toBeNull();
el.scrollTop = 594;
fireEvent.scroll(el);
expect(jump()).toBeNull();
el.scrollTop = 580;
fireEvent.scroll(el);
expect(jump()).toBeInTheDocument();
// The end moves into view when content shrinks, without a downward gesture.
height = 980;
fireEvent.scroll(el);
expect(jump()).toBeNull();
});
it("returns to the end when the user sends a message while scrolled up", async () => {
const reply = { type: "agent", text: "Initial reply" } as AgentEntry;
useAgents.setState({ entries: new Map([["A", [reply]]]) });
@@ -78,7 +78,7 @@
}
.row {
display: grid;
grid-template-columns: min(34%, 176px) 5ch minmax(0, 1fr);
grid-template-columns: min(38%, 176px) 5ch minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
min-width: 0;
@@ -365,3 +365,29 @@ it("prefers the same configuration over another selected tab with the same name"
expect(tabIds()).toEqual([1, 3]);
expect(useDebug.getState().sessions[3]?.runConfig?.id).toBe("b");
});
it("keeps a rerun tab in place and selected while its adapter starts", async () => {
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 }).mockResolvedValueOnce({ status: "ok", data: 2 });
await startSession({ ...config("launch"), name: "main.c" });
await startSession({ ...config("launch"), name: "layout.c" });
useDebug.setState({ active: 1 });
let respond!: (r: { status: "ok"; data: number }) => void;
ipc.debugStart.mockImplementationOnce(() => new Promise((resolve) => (respond = resolve)) as never);
const rerun = rerunSession(1);
await vi.advanceTimersByTimeAsync(0);
handleDebugEvent(1, { kind: "terminated" });
// Stopped, the old tab still holds its place and the selection.
expect(tabIds()).toEqual([1, 2]);
expect(useDebug.getState().active).toBe(1);
// The adapter announces the new session before `debugStart` returns: it takes the tab at once.
handleDebugEvent(3, { kind: "started", name: "main.c", adapter: "lldb", parent: null } as never);
expect(tabIds()).toEqual([3, 2]);
expect(useDebug.getState().active).toBe(3);
respond({ status: "ok", data: 3 });
await rerun;
expect(tabIds()).toEqual([3, 2]);
expect(useDebug.getState().active).toBe(3);
});
+1 -1
View File
@@ -140,7 +140,6 @@ export async function javaLaunchConfig(
root: string,
preparation?: JavaPreparation,
): Promise<LaunchConfig> {
const cwd = rc.cwd ? join(root, rc.cwd) : root;
rc = await withEnvFiles(rc, root);
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
@@ -155,6 +154,7 @@ export async function javaLaunchConfig(
},
},
);
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
if (info.errorCount > 0 && !preparation?.report)
notifications().notify({
group: "run",
+48 -9
View File
@@ -348,7 +348,19 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null
}
if (pendingStarts === 0) return null;
provisional.add(id);
return event.kind === "started" ? adoptSession(id, { name: event.name, adapter: event.adapter }) : adoptSession(id);
// The new root session takes the tab it replaces now, not once `debugStart` returns.
const replaced = pendingReplacements[0];
const slot = replaced ? { tabOrder: replaced.tabOrder, pinned: replaced.pinned } : {};
const s =
event.kind === "started"
? adoptSession(id, { name: event.name, adapter: event.adapter, ...slot })
: adoptSession(id, slot);
if (replaced) {
takeReplacement(replaced);
useDebug.setState({ active: id });
publishContext();
}
return s;
}
/**
@@ -380,10 +392,26 @@ function settleStart(id: DebugSessionId | null, discard = false) {
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
let rerunOf: DebugSessionId | null = null;
/** Sessions whose Rerun is in progress: their tab stays selected when they terminate. */
const rerunning = new Set<DebugSessionId>();
interface ReplacedTab {
pinned?: boolean;
tabOrder?: number;
/** The finished tab, kept until the new session takes its place (`defer`). */
session?: DebugSessionId;
}
/** Finished tabs whose starting replacements have no session yet, oldest start first. */
const pendingReplacements: ReplacedTab[] = [];
/** The new session is shown: the finished tab it replaces gives way. */
function takeReplacement(r: ReplacedTab | undefined) {
if (!r) return;
const i = pendingReplacements.indexOf(r);
if (i >= 0) pendingReplacements.splice(i, 1);
if (r.session != null && useDebug.getState().sessions[r.session]) removeSession(r.session);
r.session = undefined;
}
/**
@@ -392,17 +420,20 @@ interface ReplacedTab {
* then the selected one; other finished tabs stay. The returned slot lets the new backend
* session keep the tab where the replaced one was.
*/
function replaceFinished(name: string, configId?: string): ReplacedTab {
function replaceFinished(name: string, configId?: string, defer = false): ReplacedTab {
const { sessions, active } = useDebug.getState();
const own = rerunOf != null ? sessions[rerunOf] : undefined;
rerunOf = null;
// Rerun's Stop waits for the adapter, even if this window has not handled its terminated event yet.
if (own) {
const tabOrder = tabOrderOf(own);
if (defer) return { pinned: own.pinned, tabOrder, session: own.id };
removeSession(own.id);
return { pinned: own.pinned, tabOrder };
}
const finished = sessionsInTabOrder(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
const finished = sessionsInTabOrder(sessions).filter(
(s) => s.parent == null && !isLive(s) && !s.pinned && !pendingReplacements.some((r) => r.session === s.id),
);
const selected = active != null ? sessions[active] : undefined;
const ordered =
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
@@ -413,6 +444,7 @@ function replaceFinished(name: string, configId?: string): ReplacedTab {
const pinned = workflowSettings().run.pinTabs || undefined;
if (!reused) return { pinned };
const tabOrder = tabOrderOf(reused);
if (defer) return { pinned, tabOrder, session: reused.id };
removeSession(reused.id);
return { pinned, tabOrder };
}
@@ -856,7 +888,10 @@ export async function startSession(
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
const afterDetach = justDetached(options.process);
const previousActive = useDebug.getState().active;
let replaced = !afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id) : undefined;
// The finished tab stays in place until the new session appears there.
let replaced =
!afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id, true) : undefined;
if (replaced?.session != null) pendingReplacements.push(replaced);
try {
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
@@ -879,6 +914,7 @@ export async function startSession(
return null;
}
flushConsoleOutput();
takeReplacement(replaced);
const preparation = options.preparation && useDebug.getState().sessions[options.preparation.id];
useDebug.setState((s) => {
const cur = s.sessions[id] ?? blank(id, { status: "running" });
@@ -922,6 +958,7 @@ export async function startSession(
void syncSpecial();
return id;
} catch (e) {
takeReplacement(replaced);
settleStart(null, afterDetach);
if (afterDetach) {
// The JVM that announced the port ended as its previous debugger detached.
@@ -1077,16 +1114,18 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
const root = rootOf(s);
const launch = root.launch;
if (!root.runConfig && !launch) return;
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
rerunning.add(root.id);
try {
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
if (root.runConfig)
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
else await startSession(launch!, { show });
} finally {
rerunOf = null;
rerunning.delete(root.id);
}
}
@@ -1135,7 +1174,7 @@ function markTerminated(id: DebugSessionId) {
if (serverPages.delete(id) && page != null) void stopSession(page);
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
const st = useDebug.getState();
if (st.active === id) {
if (st.active === id && !rerunning.has(id)) {
// Prefer another live session (e.g. the parent of a finished child).
const other = sessionsInTabOrder(st.sessions).find(isLive);
if (other) useDebug.setState({ active: other.id });
@@ -2,22 +2,17 @@ import { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { scratchesDir } from "@/platform/scratchesDir";
import { editorService } from "@/workbench/contributions";
import { appendRequests } from "./spring/request";
export const GENERATED_REQUESTS = "generated-requests.http";
async function scratchFile(): Promise<{ path: string; created: boolean }> {
const dir = `${await appDataDir()}/scratches`;
const ignoreExisting = (e: unknown) => {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
};
await call(commands.fsCreateDir(dir)).catch(ignoreExisting);
const path = `${dir}/${GENERATED_REQUESTS}`;
const path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
let created = true;
await call(commands.fsCreateFile(path)).catch((e) => {
ignoreExisting(e);
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
created = false;
});
return { path, created };
+8 -6
View File
@@ -8,8 +8,8 @@
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { scratchesDir } from "@/platform/scratchesDir";
import {
editorService,
notifications,
@@ -116,11 +116,13 @@ function directoryArg(arg: unknown): string | null {
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
async function newRequest(directory?: string) {
try {
const dir = directory ?? `${await appDataDir()}/scratches`;
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
const dir = directory ?? (await scratchesDir());
if (directory) {
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
}
const names = new Set((await call(commands.fsReadDir(dir))).map((e) => e.name.toLowerCase()));
let name = "requests.http";
@@ -4,12 +4,6 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co
import { springControllers } from "./endpoints";
import { generateRequests } from "./editor";
// The backend reports the user data directory `/`-separated on every OS.
vi.mock("@/platform/platformInfo", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/platformInfo")>()),
appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea",
}));
// No backend here: the file commands answer like a project without Spring
// configuration files (empty configs, the files the body lookup probes missing).
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -19,7 +13,8 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
call: async (p: Promise<unknown>) => await p,
commands: {
...m.commands,
fsCreateDir: async () => null,
// The backend reports the scratches folder `/`-separated on every OS.
fsScratchesDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches",
fsCreateFile: async () => null,
fsReadText: async () => "",
},
+72 -20
View File
@@ -17,14 +17,40 @@ import {
isLibraryPath,
registerEditorContribution,
setLibraryRoots,
useEditorRegistry,
} from "@/editor/api";
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { libraryArchiveRoot } from "@/platform/virtualDocs";
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
import { goModNavigationExtension } from "./goModNavigation";
export const EXTERNAL_LIBRARIES_LABEL = "External Libraries";
/** A jdtls URI's `maven.*` attributes, as the group label used by build dependencies. */
function archiveGroupName(uri: string, fallback: string): string {
let query = uri.split("?")[1] ?? "";
try {
query = decodeURIComponent(query);
} catch {
return fallback;
}
const field = (name: string) => new RegExp(`maven\\.${name}=/([^=]+)=`).exec(query)?.[1];
const [group, artifact, version] = [field("groupId"), field("artifactId"), field("version")];
if (!group || !artifact || !version) return fallback;
const classifier = field("classifier");
return `Maven: ${group}:${artifact}:${version}${classifier ? `:${classifier}` : ""}`;
}
/** A class opened from a jar the build model has not listed yet; show its exact archive. */
export function openedLibraryGroup(uri: string, groups: readonly LibraryGroup[]): LibraryGroup | null {
const archive = libraryArchiveRoot(uri);
if (!archive || groups.some((group) => group.roots.some((root) => root.path === archive))) return null;
const separator = Math.max(archive.lastIndexOf("/"), archive.lastIndexOf("\\"));
const name = archive.slice(separator + 1, -1) || archive;
return { name: archiveGroupName(uri, name), kind: "classpath", roots: [{ name, path: archive }] };
}
const GROUP_ICONS: Record<string, string> = {
python: "file-python",
jdk: "file-java",
@@ -174,6 +200,10 @@ export function activate(): () => void {
let shown = "";
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
let settled: LibraryGroup[] = [];
/** The last build/SDK result, before archives opened from the editor are added. */
let backendGroups: LibraryGroup[] = [];
/** One group per opened archive, so the build model can replace each archive independently. */
let openedGroups: LibraryGroup[] = [];
let request: RequestId | undefined;
/** The project whose libraries are shown (and `settled`). */
let shownFor: string | null = null;
@@ -184,8 +214,36 @@ export function activate(): () => void {
shown = "";
shownGroups = [];
settled = [];
backendGroups = [];
openedGroups = [];
shownFor = null;
};
const render = (groups: LibraryGroup[]) => {
backendGroups = groups;
const covered = new Set(groups.flatMap((g) => g.roots.map((r) => r.path)));
openedGroups = openedGroups.filter((g) => !g.roots.some((r) => covered.has(r.path)));
const all = mergeLibraryGroups([...groups, ...openedGroups]);
const key = JSON.stringify(all);
if (key === shown) return;
// The new node replaces the old one in place: removing it first would drop it from the tree
// until the new one renders, and collapse it.
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(all) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = all;
const root = librariesRoot(all);
if (root) {
disposeReadOnly = setLibraryRoots(
"externalLibraries",
all.flatMap((g) => g.roots.map((r) => r.path)),
);
disposeRoot = registerProjectViewRoot(root);
}
oldRoot();
oldReadOnly();
};
const refresh = () => {
const id = ++seq;
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
@@ -200,26 +258,7 @@ export function activate(): () => void {
let collected: LibraryGroup[] = [];
const show = (groups: LibraryGroup[]) => {
if (id !== seq) return;
const key = JSON.stringify(groups);
if (key === shown) return;
// The new node replaces the old one in place: removing it first would drop it from the tree
// until the new one renders, and collapse it.
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(groups) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = groups;
const root = librariesRoot(groups);
if (root) {
disposeReadOnly = setLibraryRoots(
"externalLibraries",
groups.flatMap((g) => g.roots.map((r) => r.path)),
);
disposeRoot = registerProjectViewRoot(root);
}
oldRoot();
oldReadOnly();
render(groups);
};
const channel = new Channel<LibraryGroup[]>();
channel.onmessage = (groups) => {
@@ -242,6 +281,13 @@ export function activate(): () => void {
});
};
refresh();
const showOpenedLibrary = (path: string | null) => {
if (!path || !shownFor) return;
const group = openedLibraryGroup(path, shownGroups);
if (!group) return;
openedGroups.push(group);
render(backendGroups);
};
const disposeGoMod = registerEditorContribution({
id: "libraries.goModNavigation",
extensions: goModNavigationExtension((path, version) => goModuleRoot(shownGroups, path, version), isLibraryPath),
@@ -252,6 +298,11 @@ export function activate(): () => void {
const unsub = useProject.subscribe((s, prev) => {
if (sdkKey(s) !== sdkKey(prev)) refresh();
});
const unsubEditor = useEditorRegistry.subscribe((s, prev) => {
const path = s.active?.ctx.path ?? null;
if (path !== (prev.active?.ctx.path ?? null)) showOpenedLibrary(path);
});
showOpenedLibrary(useEditorRegistry.getState().active?.ctx.path ?? null);
let timer: ReturnType<typeof setTimeout> | undefined;
const unsubFs = onIdeEvent("fsChanged", (e) => {
if (!touchesManifest([...e.created, ...e.modified, ...e.removed])) return;
@@ -268,6 +319,7 @@ export function activate(): () => void {
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
clearTimeout(timer);
unsub();
unsubEditor();
unsubFs();
unsubRoots();
disposeActions();
+22 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { isLibraryPath, setLibraryRoots } from "@/editor/api";
import { librariesRoot, touchesManifest } from "./index";
import { librariesRoot, openedLibraryGroup, touchesManifest } from "./index";
import { mergeLibraryGroups } from "@/platform/libraries";
describe("External Libraries", () => {
@@ -116,6 +116,27 @@ describe("External Libraries", () => {
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
});
it("adds the classifier jar opened from a library class when the build model omits it", () => {
const uri =
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.groupId=/com.example=/=/maven.artifactId=/demo-lib=/=/maven.version=/1.0=/=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
expect(openedLibraryGroup(uri, [])).toEqual({
name: "Maven: com.example:demo-lib:1.0:jdk21",
kind: "classpath",
roots: [
{
name: "demo-lib-1.0-jdk21.jar",
path: "/m2/com/example/demo-lib/1.0/demo-lib-1.0-jdk21.jar!",
},
],
});
});
it("does not duplicate an archive the build model already lists", () => {
const uri = "jdt://contents/a.jar/p/C.class?=demo/%5C/m2%5C/a.jar%3Cp%28C.class";
const group = { name: "a.jar", kind: "maven", roots: [{ name: "a.jar", path: "/m2/a.jar!" }] };
expect(openedLibraryGroup(uri, [group])).toBeNull();
});
it("refreshes on manifest changes outside node_modules", () => {
expect(touchesManifest(["/p/src/main.rs", "/p/Cargo.toml"])).toBe(true);
expect(touchesManifest(["C:\\p\\go.mod"])).toBe(true);
+59 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { LibraryGroup } from "@/bindings";
const results: LibraryGroup[][] = [];
@@ -31,6 +31,7 @@ vi.mock("@/platform/ipc", () => ({
}));
const { activate } = await import("./index");
const { useEditorRegistry } = await import("@/editor/api");
const { useProject } = await import("@/platform/project");
const { useProjectViewRoots } = await import("@/workbench/contributions");
const { executeAction } = await import("@/platform/actions");
@@ -42,6 +43,13 @@ const rust = (version: string): LibraryGroup => ({
});
describe("External Libraries refresh", () => {
afterEach(() => {
results.length = 0;
streamed.length = 0;
hang = false;
useEditorRegistry.setState({ active: null });
});
it("replaces the node in place when the libraries change", async () => {
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
@@ -86,4 +94,54 @@ describe("External Libraries refresh", () => {
dispose();
}
});
it("keeps other opened archives with the same name when the build lists one of them", async () => {
const first = "/first/library.jar!";
const second = "/second/library.jar!";
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
});
const dispose = activate();
const paths = () =>
useProjectViewRoots
.getState()
.roots.get("externalLibraries")
?.children?.flatMap((group) => group.children?.map((root) => root.path) ?? [])
.sort();
try {
for (const archive of [first, second]) {
useEditorRegistry.setState({ active: { ctx: { path: `jar:file://${archive}/p/Example.class` } } as never });
}
await vi.waitFor(() => expect(paths()).toEqual([first, second]));
results.push([{ name: "Build dependency", kind: "gradle", roots: [{ name: "library.jar", path: first }] }]);
await executeAction("libraries.reload");
await vi.waitFor(() =>
expect(useProjectViewRoots.getState().roots.get("externalLibraries")?.children?.[0]?.label).toBe(
"Build dependency",
),
);
expect(paths()).toEqual([first, second]);
} finally {
dispose();
}
});
it("shows the exact classifier jar of the library class opened in the editor", async () => {
const uri =
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
});
useEditorRegistry.setState({ active: { ctx: { path: uri } } as never });
results.push([]);
const dispose = activate();
const labels = () =>
useProjectViewRoots
.getState()
.roots.get("externalLibraries")
?.children?.[0]?.children?.map((g) => g.label);
await vi.waitFor(() => expect(labels()).toContain("demo-lib-1.0-jdk21.jar"));
dispose();
});
});
+36 -13
View File
@@ -2,7 +2,17 @@ import { shortcutLabel } from "@/platform/keymap";
import { IconButton, type MenuItem } from "@/ui";
import { useProject } from "@/platform/project";
import { userScopes } from "@/platform/scopes";
import { VIEW_MODES, setScopeView, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
import { useEditorPrefs } from "@/platform/editorSettings";
import {
VIEW_MODES,
previewTabEnabled,
setPreviewTabEnabled,
setScopeView,
setViewMode,
setViewOption,
useProjectTree,
type ViewOptions,
} from "./store";
import type { SortKey } from "./model";
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
@@ -35,9 +45,22 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
}
/** The on / off view options. */
export type ToggleOption = {
type ViewToggle = {
[K in keyof ViewOptions]-?: ViewOptions[K] extends boolean ? K : never;
}[keyof ViewOptions];
/** The view's switches, plus the editor's preview tab setting it shares (as in IDEA). */
export type ToggleOption = ViewToggle | "previewTab";
const toggleState = (key: ToggleOption, options: ViewOptions, preview: boolean) =>
key === "previewTab" ? preview : options[key];
export const isToggled = (key: ToggleOption) =>
toggleState(key, useProjectTree.getState().options, previewTabEnabled());
export function flipToggle(key: ToggleOption) {
if (key === "previewTab") void setPreviewTabEnabled(!previewTabEnabled());
else setViewOption(key, !useProjectTree.getState().options[key]);
}
const APPEARANCE_OPTIONS: Array<[ToggleOption, string]> = [
["showHidden", "Show Hidden Files"],
@@ -90,22 +113,26 @@ export const SORT_LABELS: Array<[key: SortKey, actionLabel: string, menuLabel: s
/** Project view options in the header's "⋮" menu. */
export function useProjectHeaderMenu(): MenuItem[] {
const options = useProjectTree((s) => s.options);
const preview = useEditorPrefs().tabs.previewTab;
const option = (key: ToggleOption, label: string): MenuItem => ({
id: key,
label,
checked: toggleState(key, options, preview),
run: () => flipToggle(key),
});
const unity = useProjectTree((s) => s.mode === "unity");
return [
{
label: "Behavior",
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label, options)),
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label)),
},
{
label: "Appearance",
submenu: [
...(unity
? [
option("showUnityMeta", "Show Meta Files", options),
option("showUnityGenerated", "Show Generated Files", options),
]
? [option("showUnityMeta", "Show Meta Files"), option("showUnityGenerated", "Show Generated Files")]
: []),
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label, options)),
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label)),
],
},
{
@@ -118,12 +145,8 @@ export function useProjectHeaderMenu(): MenuItem[] {
run: () => setViewOption("sortBy", sortBy),
})),
{ kind: "separator" },
option(...FOLDERS_FIRST, options),
option(...FOLDERS_FIRST),
],
},
];
}
function option(key: ToggleOption, label: string, options: ViewOptions): MenuItem {
return { id: key, label, checked: options[key], run: () => setViewOption(key, !options[key]) };
}
+87 -14
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { installRepeatedDoubleClick } from "@/platform/doubleClick";
import { getContext, setContext } from "@/platform/context";
@@ -22,13 +22,17 @@ import { beginNew, canPaste } from "./operations";
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
import type { OutlineItem } from "@/bindings";
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
import { ProjectHeaderActions } from "./HeaderActions";
import { ProjectHeaderActions, useProjectHeaderMenu } from "./HeaderActions";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { loadOutline } from "./store";
const ipc = vi.hoisted(() => ({
docOpen: vi.fn(),
docClose: vi.fn(),
docOutline: vi.fn(),
settingsSet: vi.fn(),
}));
vi.mock("@/bindings", async (orig) => {
const real = await orig<typeof import("@/bindings")>();
@@ -58,6 +62,11 @@ const deferred = <T,>() => {
};
const ROOT = "/w/acme";
const initialSettings = useProject.getState().settings;
/** Settings › Editor › General › Editor Tabs › Enable preview tab. */
const previewTabSettings = (on: boolean) => ({ editor: { tabs: { previewTab: on } } });
const setPreviewTabSetting = (on: boolean) => act(() => useProject.setState({ settings: previewTabSettings(on) }));
let fs: MemoryFs;
let openFile: ReturnType<typeof vi.fn>;
let dispose: () => void;
@@ -98,6 +107,7 @@ beforeEach(() => {
afterEach(() => {
dispose();
useProject.setState({ settings: initialSettings });
setProjectFsForTests(null);
uninstallDispatcher?.();
uninstallDispatcher = null;
@@ -222,6 +232,42 @@ describe("ProjectView", () => {
}
});
it("pastes a copied keyword into the tree's speed search instead of pasting files", async () => {
dispatchViaKeymap();
// Explorer holds a file, and the user wants to paste a word they copied from somewhere else
// into the search they just opened with ⌘F.
fs.nodes.set("/elsewhere/Photo.png", { kind: "file", size: 3 });
setOsClipboardForTests({
files: async () => ["/elsewhere/Photo.png"],
hasFiles: async () => true,
setFiles: async () => false,
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "f", code: "KeyF", metaKey: true });
fireEvent.paste(tree, {
clipboardData: { getData: () => "Read" },
} as unknown as ClipboardEventInit);
expect(within(tree.parentElement!).getByRole("status")).toHaveTextContent("Read");
// The file Paste never ran: give a wrong one the time to land, then check the project.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toEqual([]);
// Closed, ⌘V is the view's file Paste again.
fireEvent.keyDown(tree, { key: "Escape", code: "Escape" });
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
await waitFor(() =>
expect([...fs.nodes.keys()].some((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toBe(true),
);
} finally {
setOsClipboardForTests(null);
}
});
it("clears cut dimming and disables Paste on focus after the OS clipboard becomes text", async () => {
dispatchViaKeymap();
let files: string[] = [];
@@ -257,21 +303,48 @@ describe("ProjectView", () => {
}
});
it("opens files on double click and previews on single click only when enabled", async () => {
it("opens files on double click and previews on single click while the editor's preview tab is on", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
const content = row("README.md").querySelector("[data-project-path]")!;
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
act(() => setViewOption("previewTab", true));
// Settings › Editor › General › Editor Tabs › Enable preview tab is on by default.
fireEvent.click(content, { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
openFile.mockClear();
fireEvent.click(content, { detail: 3 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", false));
setPreviewTabSetting(false);
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
});
it("toggles the editor's preview tab setting from the Behavior menu and its action", async () => {
ipc.settingsSet.mockImplementation(async (_scope: string, _key: string, value: string) =>
ok(previewTabSettings(JSON.parse(value) as boolean)),
);
const { result } = renderHook(() => useProjectHeaderMenu());
type Item = Extract<MenuItem, { id?: string }>;
const behavior = () => (result.current[0] as Item).submenu as Item[];
const item = () => behavior().find((i) => i.id === "previewTab")!;
expect(item().checked).toBe(true);
act(() => item().run!());
await waitFor(() => expect(item().checked).toBe(false));
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.tabs.previewTab", "false");
const action = getAction("project.option.previewTab")!;
expect(action.toggled!()).toBe(false);
act(() => void executeAction(action.id));
await waitFor(() => expect(item().checked).toBe(true));
});
it("drops the former view-only preview tab option from saved view options", () => {
localStorage.setItem("openidea.projectTree.options", JSON.stringify({ previewTab: true, singleClickOpen: true }));
vi.resetModules();
return import("./store").then(({ useProjectTree: fresh }) => {
expect(fresh.getState().options).not.toHaveProperty("previewTab");
expect(fresh.getState().options.singleClickOpen).toBe(true);
});
});
it("follows tab switches with Always Select Opened File, hiding Select Opened File", async () => {
@@ -701,17 +774,17 @@ describe("Show Members", () => {
},
);
it("autoscrolls to source without handing files to another application", async () => {
it.each([true, false])("autoscrolls to source with preview tabs set to %s", async (preview) => {
const { rows, row } = setup();
setPreviewTabSetting(preview);
act(() => {
setViewOption("autoscrollToSource", true);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
});
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", expect.objectContaining({ external: false })),
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview, focus: false, external: false }),
);
});
@@ -724,14 +797,14 @@ describe("Show Members", () => {
setViewOption("showMembers", true);
setViewOption("autoscrollToSource", false);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
useProject.setState({ settings: previewTabSettings(false) });
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
});
await waitFor(() => expect(rows()).toContain("main"));
const content = () => row("main").querySelector("[data-project-key]")!;
fireEvent.click(content(), { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", true));
setPreviewTabSetting(true);
fireEvent.click(content(), { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith(
APP,
+5 -7
View File
@@ -91,6 +91,7 @@ import {
explainHiddenPath,
loadDir,
loadOutline,
previewTabEnabled,
revealPath,
selectModel,
setDropTarget,
@@ -584,13 +585,10 @@ export function ProjectView() {
setSelection(next, lead?.key ?? null);
const { options: o } = useProjectTree.getState();
if (revealing.current || !o.autoscrollToSource || !lead || lead.dir || lead.placeholder || next.size !== 1) return;
const opts = { preview: previewTabEnabled(), focus: false, external: false };
if (lead.member) {
void revealRange(
lead.path,
{ start: lead.member.selection_range.start },
{ preview: o.previewTab, focus: false, external: false },
);
} else void openFile(lead.path, { preview: o.previewTab, focus: false, external: false });
void revealRange(lead.path, { start: lead.member.selection_range.start }, opts);
} else void openFile(lead.path, opts);
}, []);
const onActivate = useCallback((node: ProjectNode) => {
@@ -633,7 +631,7 @@ export function ProjectView() {
if (o.singleClickExpand) toggleExpanded(node);
return;
}
if (!o.singleClickOpen && !o.previewTab) return;
if (!o.singleClickOpen && !previewTabEnabled()) return;
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
else void openFile(node.path, opts);
+3 -3
View File
@@ -6,7 +6,7 @@ import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fil
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
import { OPTION_LABELS, SORT_LABELS } from "./HeaderActions";
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
import { openNewPopup } from "./newPopupModel";
import type { ProjectNode } from "./model";
@@ -191,8 +191,8 @@ export function registerProjectActions(): () => void {
category: "View",
// IDEA's former name of Always Select Opened File.
keywords: ["project", "tree", "toggle", ...(key === "autoscrollFromSource" ? ["autoscroll from source"] : [])],
toggled: () => useProjectTree.getState().options[key],
run: () => setViewOption(key, !useProjectTree.getState().options[key]),
toggled: () => isToggled(key),
run: () => flipToggle(key),
}));
const modes: Action[] = VIEW_MODES.map(([mode, label]) => ({
@@ -145,6 +145,22 @@ describe("project view context menu", () => {
]);
});
it("lists contributed links in Copy Path/Reference… of library files too", () => {
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
}),
);
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
"Absolute Path",
"File Name",
"-",
"Link /root/.m2/lib.jar",
]);
});
it("groups clipboard, search, file changes, formatting and history actions for a file", () => {
const items = contextMenuItems([node(`${ROOT}/src/a.py`)]);
expect(labels(items)).toEqual([
+2
View File
@@ -512,6 +512,8 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
run: () => void copyPaths("absolute", nodes),
},
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
{ kind: "separator" },
...menuGroupItems("copyPath", menuGroupContext(nodes)),
],
},
{ kind: "separator" },
+20 -4
View File
@@ -13,6 +13,8 @@ import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx, txPart } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { ipcPath } from "@/platform/paths";
import {
DEFAULT_TREE_OPTIONS,
@@ -57,8 +59,6 @@ export interface ViewOptions extends TreeOptions {
singleClickOpen: boolean;
/** Single click on a folder row expands / collapses it. */
singleClickExpand: boolean;
/** Single click shows files in the preview tab (IDEA's "Enable Preview Tab"). */
previewTab: boolean;
/** Show a file's declarations as expandable rows below it. */
showMembers: boolean;
/** Show the location of each project root beside its name. */
@@ -73,8 +73,6 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
autoscrollToSource: false,
singleClickOpen: false,
singleClickExpand: false,
// IDEA's "Enable Preview Tab" is off by default.
previewTab: false,
showMembers: false,
showRootPaths: true,
horizontalScroll: true,
@@ -82,6 +80,8 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
function storedOptions(): ViewOptions {
const options = { ...DEFAULT_VIEW_OPTIONS, ...readJson<Partial<ViewOptions>>(OPTIONS_KEY) };
// Former view-only switch, now the editor's preview tab setting (`previewTabEnabled`).
delete (options as { previewTab?: unknown }).previewTab;
if (!["name", "type", "modified"].includes(options.sortBy)) options.sortBy = "name";
return options;
}
@@ -502,6 +502,22 @@ export function setViewOption<K extends keyof ViewOptions>(key: K, value: ViewOp
writeJson(OPTIONS_KEY, options);
}
/** Single click shows files in the preview tab: IDEA's "Enable Preview Tab" is the editor's own setting. */
export const previewTabEnabled = () => editorPrefs().tabs.previewTab;
export async function setPreviewTabEnabled(on: boolean): Promise<void> {
try {
const settings = await call(commands.settingsSet("global", "editor.tabs.previewTab", JSON.stringify(on)));
useProject.setState({ settings });
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot change the setting",
body: e instanceof Error ? e.message : String(e),
});
}
}
// ---------------------------------------------------------------------------
// Loading
+8
View File
@@ -487,9 +487,17 @@
padding: 6px 8px;
border-bottom: 1px solid var(--border-popup);
}
/* The list fills what is left of the viewport once the popup is capped by the window, not its full height. */
.chooserViewport {
display: flex;
flex-direction: column;
min-height: 0;
}
.chooserViewport > .chooserList {
flex: 1 1 auto;
min-height: 0;
height: auto;
}
.chooserList {
height: 100%;
overflow-x: hidden;
+49 -2
View File
@@ -3,8 +3,8 @@ import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun";
import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers";
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems, projectContext } from "./contextRun";
import { OPTIMISTIC, produceContext, produceContextChoices, type ToolEnv } from "./producers";
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
import { useRun } from "./store";
import type { RunTarget } from "./targets";
@@ -115,6 +115,53 @@ describe("run context menu group", () => {
expect(contextMenuItems("projectView", { paths: [`${ROOT}/src/components`], dirs: [true] })).toEqual([]);
});
it("routes an attached Spring Boot main and its tests through the member's Maven build", () => {
const member = "/work/spring";
const project = useProject.getState().project!;
useProject.setState({ project: { ...project, workspace: { version: 1, name: "app", projects: [ROOT, member] } } });
const maven: RunConfig = { ...npmTest, kind: "maven", command: "mvn", args: ["test"], debugAdapter: null };
useRun.setState({
configs: [
{ ...maven, id: "maven:test" },
{ ...maven, id: "member:test", cwd: member },
],
});
const content = [
"package demo;",
"import org.springframework.boot.SpringApplication;",
"import org.springframework.boot.autoconfigure.SpringBootApplication;",
"@SpringBootApplication",
"public class App {",
" public static void main(String[] args) { SpringApplication.run(App.class, args); }",
"}",
].join("\n");
const main = { ...projectContext(), path: `${member}/src/main/java/demo/App.java`, content, line: 5 };
expect(produceContext(main, OPTIMISTIC)?.config).toMatchObject({
kind: "spring-boot",
module: member,
args: ["-cp", "${classpath}", "demo.App"],
});
expect(
produceContext(
{
...main,
path: `${member}/src/test/java/demo/AppTest.java`,
content: "package demo;\nclass AppTest {\n @Test\n void starts() {}\n}",
line: 3,
},
OPTIMISTIC,
)?.config,
).toMatchObject({
kind: "maven",
cwd: member,
args: ["test", "-Dtest=demo.AppTest#starts", "-Dsurefire.failIfNoSpecifiedTests=false"],
});
expect(produceContext({ ...main, path: `${ROOT}/src/main/java/demo/App.java` }, OPTIMISTIC)?.config).toMatchObject({
kind: "spring-boot",
module: "",
});
});
it("shows nothing when no producer matches or for several paths", () => {
expect(contextMenuItems("editor", { paths: [`${ROOT}/README.md`], text: "# hi", line: 0 })).toEqual([]);
expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual(
+4 -3
View File
@@ -50,15 +50,16 @@ async function ensureConfigs() {
}
/** The focused editor's file, text and caret line. */
/** Project folders outside its root: Project Structure content roots and Gradle modules (as of the last sync). */
/** Attached projects, Project Structure content roots and external Gradle modules. */
export function projectContentRoots(): string[] {
const own = effectiveContentRoots(validateProjectStructure(useProject.getState().settings?.projectStructure));
const { project, settings } = useProject.getState();
const own = effectiveContentRoots(validateProjectStructure(settings?.projectStructure));
// The build model keeps the folders of modules outside the project absolute.
const gradle = (useBuildModel.getState().model?.gradle ?? [])
.flatMap((g) => g.projects)
.map((p) => p.dir)
.filter((d) => isAbsolute(d));
return [...new Set([...own, ...gradle])];
return [...new Set([...(project?.workspace?.projects ?? []), ...own, ...gradle])];
}
const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p);
+84
View File
@@ -0,0 +1,84 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { DEFAULT_EXTERNAL_TOOL } from "@/platform/workflowSettings";
import { clearProjectViewLead, setProjectViewLead } from "@/workbench/contributions";
import { externalToolConfig } from "./externalTools";
const editor = vi.hoisted(() => ({ current: null as unknown }));
vi.mock("@/editor/api", () => ({ activeEditor: () => editor.current }));
// Editor on A.java, caret on line 2 with "two" selected.
function openA() {
const doc = "one\ntwo\n";
const state = EditorState.create({ doc, selection: EditorSelection.single(4, 7) });
editor.current = { ctx: { path: "/p/src/A.java" }, view: { state } };
}
const tool = {
...DEFAULT_EXTERNAL_TOOL,
id: "t",
name: "Echo",
program: "echo",
arguments:
"$FilePath$ $FileDir$ $FileName$ $FileNameWithoutExtension$ $FileExt$ $FileRelativePath$ " +
"$FileDirRelativeToProjectRoot$ L$LineNumber$ C$ColumnNumber$ S$SelectedText$",
};
const argsFor = async () => (await externalToolConfig(tool))?.args;
describe("external tool macros", () => {
beforeEach(() => {
useProject.setState({ project: { root: "/p", name: "demo" } as never });
setContext("editorFocus", false);
openA();
});
afterEach(() => {
clearProjectViewLead();
editor.current = null;
useProject.setState({ project: null });
});
it("uses the file selected in the Project view over the open editor (#5402)", async () => {
setProjectViewLead({ path: "/p/lib/B.kt", dir: false });
expect(await argsFor()).toEqual(["/p/lib/B.kt", "/p/lib", "B.kt", "B", "kt", "lib/B.kt", "lib", "L", "C", "S"]);
});
it("uses the editor's file and caret when the editor is the context", async () => {
expect(await argsFor()).toEqual([
"/p/src/A.java",
"/p/src",
"A.java",
"A",
"java",
"src/A.java",
"src",
"L2",
"C4",
"Stwo",
]);
});
it("keeps the caret macros when the Project view selects the editor's file", async () => {
setProjectViewLead({ path: "/p/src/A.java", dir: false });
expect((await argsFor())?.slice(-3)).toEqual(["L2", "C4", "Stwo"]);
});
it("falls back to the editor for a selected directory", async () => {
setProjectViewLead({ path: "/p/lib", dir: true });
expect((await argsFor())?.[0]).toBe("/p/src/A.java");
});
it("lets the focused editor win over a stale tree selection", async () => {
setProjectViewLead({ path: "/p/lib/B.kt", dir: false });
setContext("editorFocus", true);
expect((await argsFor())?.[0]).toBe("/p/src/A.java");
});
it("uses the tree selection with no editor open", async () => {
editor.current = null;
setProjectViewLead({ path: "/p/lib/B.kt", dir: false });
expect((await argsFor())?.[0]).toBe("/p/lib/B.kt");
});
});
+17 -3
View File
@@ -9,7 +9,8 @@ import { splitCommandLine } from "@/platform/commandLine";
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { onWorkflowSettingsChange, workflowSettings, type ExternalToolValid } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { isVirtualUri } from "@/platform/virtualDocs";
import { notifications, projectViewContextLead } from "@/workbench/contributions";
import { promptValue } from "./dialogs";
import { startRun, useRun } from "./store";
@@ -73,14 +74,27 @@ export function expandMacros(text: string, ctx: MacroContext, prompt = ""): stri
return text.replace(MACRO_RE, (all, name: string) => (name === "Prompt" ? prompt : (macroValue(name, ctx) ?? all)));
}
/**
* The file macros resolve against, as IDEA's data context: the Project view's file while the
* tree is the user's context (it hands the context back on editor focus or a tab switch), else
* the editor's file.
*/
function contextFile(editorPath: string | null): string | null {
const lead = projectViewContextLead();
if (lead && !lead.dir && !isVirtualUri(lead.path)) return lead.path;
return editorPath;
}
function currentContext(): MacroContext | null {
const project = useProject.getState().project;
if (!project) return null;
const ed = activeEditor();
const filePath = contextFile(ed?.ctx.path ?? null);
let line: number | null = null;
let column: number | null = null;
let selectedText = "";
if (ed) {
// The caret macros describe the editor, so only when it shows the file the macros use.
if (ed && ed.ctx.path === filePath) {
const state = ed.view.state;
const sel = state.selection.main;
const l = state.doc.lineAt(sel.head);
@@ -91,7 +105,7 @@ function currentContext(): MacroContext | null {
return {
projectRoot: project.root,
projectName: project.name,
filePath: ed?.ctx.path ?? null,
filePath,
line,
column,
selectedText,
+22
View File
@@ -68,6 +68,7 @@ beforeEach(() => {
afterEach(() => {
resetRuns();
_resetI18nForTests();
useProject.setState({ project: null });
});
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
@@ -142,6 +143,27 @@ it("finds the source module for an old saved configuration without a module", as
);
});
it.each([null, "/elsewhere"])("recovers an attached module from its indexed path with cwd %s", async (cwd) => {
const root = "/p";
const member = "/other/spring";
const module = `${member}/web`;
useProject.setState({
project: { root, workspace: { version: 1, name: "demo", projects: [root, member] } } as never,
});
ipc.findFiles.mockResolvedValueOnce({
status: "ok",
data: [{ path: `${module}/src/main/java/a/Main.java`, relPath: "spring/web/src/main/java/a/Main.java" }],
});
const session = await startRun({ ...config, cwd });
expect(session?.status).toBe("running");
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number));
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ cwd: cwd ?? module, module }),
expect.anything(),
expect.any(Number),
);
});
it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath resolution (%j)", async (...classpath) => {
const args = ["-Xmx256m", ...classpath, "a.Main", "--spring.profiles.active=dev"];
const boot = { ...config, kind: "spring-boot", args };
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { getAction } from "@/platform/actions";
import { onIdeEvent } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { useProjectViewRoots } from "@/workbench/contributions";
import {
chooserRows,
@@ -102,9 +103,8 @@ describe("creating scratch files", () => {
opened = [];
carets = [];
backend = {
dataDir: async () => "/data/",
scratchesDir: async () => "/data/scratches/",
listNames: async (dir) => [...files].filter((f) => f.startsWith(dir + "/")).map((f) => f.slice(dir.length + 1)),
createDir: async () => {},
createFile: async (p, text) => {
files.add(p);
contents.set(p, text);
@@ -177,14 +177,43 @@ describe("creating scratch files", () => {
});
});
describe("scratches of a remote window", () => {
afterEach(() => {
useRemote.setState({ session: null });
setScratchBackend(tauriScratchBackend);
});
it("moves the Scratches root to the server's folder when the window attaches to it in place", async () => {
const remote = () => useRemote.getState().session !== null;
setScratchBackend({
scratchesDir: async () => (remote() ? "/home/me/.openidea/data/scratches" : "C:/Users/me/AppData/scratches"),
listNames: async () => [],
createFile: async () => {},
languages: async () => [],
open: async () => {},
});
const root = () => useProjectViewRoots.getState().roots.get("scratches")?.path;
const dispose = activate();
try {
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
useRemote.setState({ session: { root: "/home/me/project" } as never });
await vi.waitFor(() => expect(root()).toBe("/home/me/.openidea/data/scratches"));
useRemote.setState({ session: null });
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
} finally {
dispose();
}
expect(root()).toBeUndefined();
});
});
describe("deleting scratch files", () => {
afterEach(() => setScratchBackend(tauriScratchBackend));
it("reports deletions inside the scratches folder as file system changes", async () => {
setScratchBackend({
dataDir: async () => "/data",
scratchesDir: async () => "/data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [],
open: async () => {},
+14 -2
View File
@@ -5,6 +5,7 @@
import { registerActions } from "@/platform/actions";
import { onFileOperation } from "@/platform/fileOps";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { registerMenuGroup, registerOverlay, registerProjectViewRoot } from "@/workbench/contributions";
import { ScratchChooserHost } from "./ScratchChooser";
import { openChooser } from "./store";
@@ -20,10 +21,15 @@ export function activate(): () => void {
let disposed = false;
let unregisterRoot = () => {};
let dir: string | null = null;
if (scratchesAvailable())
let generation = 0;
const registerRoot = () => {
const current = ++generation;
unregisterRoot();
unregisterRoot = () => {};
dir = null;
void scratchesDir()
.then((path) => {
if (disposed) return;
if (disposed || current !== generation) return;
dir = path;
unregisterRoot = registerProjectViewRoot({
id: "scratches",
@@ -35,7 +41,13 @@ export function activate(): () => void {
});
})
.catch((e: unknown) => console.warn("scratch files: no scratches folder", e));
};
if (scratchesAvailable()) registerRoot();
const disposers = [
// Attaching to (or leaving) a remote server moves the scratches to that host.
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session && scratchesAvailable()) registerRoot();
}),
// The file watcher covers the project only: deleted scratches close their editors like watched files.
onFileOperation((op) => {
const removed = dir && op.kind === "deleted" ? op.paths.filter((p) => p === dir || p.startsWith(`${dir}/`)) : [];
+12 -30
View File
@@ -1,27 +1,26 @@
/**
* Scratch files live in the app data dir (`<appData>/scratches`), not in the
* project, like IDEA's config-dir scratches. Creating one picks the next free
* `scratch[_n].<ext>` name and opens it as a normal document.
* Scratch files live in the user data dir (`<data>/scratches`) of the host that runs the
* window's file commands (the server in a remote window), not in the project, like IDEA's
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
* it as a normal document.
*/
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { scratchesDir as hostScratchesDir } from "@/platform/scratchesDir";
import { editorService, notifications } from "@/workbench/contributions";
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
export interface ScratchBackend {
/** Absolute app data dir. */
dataDir(): Promise<string>;
/** Absolute scratches folder, created. */
scratchesDir(): Promise<string>;
listNames(dir: string): Promise<string[]>;
createDir(dir: string): Promise<void>;
createFile(path: string, text: string): Promise<void>;
languages(): Promise<ScratchLanguage[]>;
open(path: string, caret: { line: number; col: number } | null): Promise<void>;
}
export const tauriScratchBackend: ScratchBackend = {
dataDir: appDataDir,
scratchesDir: hostScratchesDir,
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
createFile: async (path, text) =>
void (await call(
text ? commands.fsCreateFileBytes(path, [...new TextEncoder().encode(text)]) : commands.fsCreateFile(path),
@@ -35,30 +34,13 @@ let backend: ScratchBackend = tauriScratchBackend;
/** Tests swap the backend. */
export function setScratchBackend(b: ScratchBackend) {
backend = b;
dirPromise = null;
}
export const scratchBackend = () => backend;
let dirPromise: Promise<string> | null = null;
/** `<appData>/scratches`, created on first use. */
export function scratchesDir(): Promise<string> {
if (!dirPromise) {
dirPromise = (async () => {
const dir = `${(await backend.dataDir()).replace(/\/+$/, "")}/scratches`;
try {
await backend.createDir(dir);
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
return dir;
})();
dirPromise.catch(() => {
dirPromise = null;
});
}
return dirPromise;
/** The scratches folder, created if needed. */
export async function scratchesDir(): Promise<string> {
return (await backend.scratchesDir()).replace(/\/+$/, "");
}
export const scratchesAvailable = () => isTauri() || backend !== tauriScratchBackend;
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const extensions = [
const projectExtensions = [
{ extension: "rs", files: 40 },
{ extension: "md", files: 12 },
{ extension: "lock", files: 9 },
@@ -10,6 +10,7 @@ const extensions = [
{ extension: "yml", files: 2 },
{ extension: "sh", files: 1 },
];
let extensions = projectExtensions;
const languages = [
{ id: "rust", extensions: ["rs"] },
{ id: "markdown", extensions: ["md", "markdown"] },
@@ -17,6 +18,7 @@ const languages = [
{ id: "json", extensions: ["json"] },
{ id: "yaml", extensions: ["yml", "yaml"] },
{ id: "shell", extensions: ["sh"] },
{ id: "properties", extensions: ["properties", "prefs"] },
];
vi.mock("@/platform/ipc", async (orig) => ({
@@ -31,16 +33,30 @@ vi.mock("@/platform/ipc", async (orig) => ({
const { recentMasks, refreshProjectMasks, rememberMask, useProjectMasks } = await import("../find/store");
beforeEach(() => {
extensions = projectExtensions;
localStorage.clear();
useProjectMasks.setState({ masks: [] });
});
describe("file mask suggestions", () => {
it("are the project's most common language file types, recent masks first", async () => {
it("are every language file type in the project, most common first, recent masks first", async () => {
await refreshProjectMasks();
expect(useProjectMasks.getState().masks).toEqual(["*.rs", "*.md", "*.toml", "*.json", "*.yml"]);
expect(useProjectMasks.getState().masks).toEqual(["*.rs", "*.md", "*.toml", "*.json", "*.yml", "*.sh"]);
rememberMask("*.toml");
rememberMask("!*Test*");
expect(recentMasks()).toEqual(["!*Test*", "*.toml", "*.rs", "*.md", "*.json", "*.yml"]);
expect(recentMasks()).toEqual(["!*Test*", "*.toml", "*.rs", "*.md", "*.json", "*.yml", "*.sh"]);
});
it("keep the least common of six file types (#5398)", async () => {
extensions = [
{ extension: "rs", files: 120 },
{ extension: "md", files: 30 },
{ extension: "json", files: 12 },
{ extension: "toml", files: 8 },
{ extension: "yml", files: 4 },
{ extension: "properties", files: 1 },
];
await refreshProjectMasks();
expect(recentMasks()).toEqual(["*.rs", "*.md", "*.json", "*.toml", "*.yml", "*.properties"]);
});
});
+3 -7
View File
@@ -164,11 +164,10 @@ export function hideFindPopup() {
}
const MASKS_KEY = "openidea.search.fileMasks.v1";
const PROJECT_MASKS = 5;
/**
* `*.ext` masks of the project's most common language file types. IDEA seeds its
* mask list with the IDE's languages; a multi-language IDE takes the project's.
* `*.ext` masks of every language file type in the project, most common first. IDEA
* seeds its mask list with the IDE's languages; a multi-language IDE takes the project's.
*/
export const useProjectMasks = create<{ masks: string[] }>(() => ({ masks: [] }));
@@ -176,10 +175,7 @@ export async function refreshProjectMasks() {
try {
const [counts, languages] = await Promise.all([call(commands.indexFileExtensions()), commands.languages()]);
const known = new Set(languages.flatMap((l) => l.extensions.map((e) => e.toLowerCase())));
const masks = counts
.filter((c) => known.has(c.extension))
.slice(0, PROJECT_MASKS)
.map((c) => `*.${c.extension}`);
const masks = counts.filter((c) => known.has(c.extension)).map((c) => `*.${c.extension}`);
useProjectMasks.setState({ masks });
} catch {
/* no project index (welcome screen, tests) */
+2 -2
View File
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTx } from "@/platform/i18n";
import { Checkbox, Dialog, Input } from "@/ui";
import { answerAskpass, askpassAnswer, useAskpass, type AskpassPrompt } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, useAskpass, type AskpassPrompt } from "./askpass";
import styles from "./Ssh.module.css";
export function AskpassHost() {
@@ -39,7 +39,7 @@ function AskpassDialog({ prompt: p }: { prompt: AskpassPrompt }) {
return (
<Dialog
open
title={tx(p.kind === "secret" ? "SSH Password" : "SSH")}
title={tx(askpassTitle(p))}
onClose={cancel}
width={440}
buttons={[
+9
View File
@@ -45,3 +45,12 @@ export function answerAskpass(
// on success and drops it again when authentication fails.
void send(p.id, answer, remember).catch(() => {});
}
/** The dialog title: git asks for HTTPS credentials (any host, e.g. a token as the password) as well as ssh. */
export function askpassTitle(
p: Pick<AskpassPrompt, "kind" | "prompt">,
): "Password" | "Username" | "SSH Password" | "SSH" {
const https = /\bhttps?:\/\//i.test(p.prompt);
if (p.kind === "secret") return https ? "Password" : "SSH Password";
return https ? "Username" : "SSH";
}
+13 -1
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SSH_CONFIG, type SshConfigValid } from "@/platform/remoteSettings";
import { answerAskpass, askpassAnswer, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
describe("askpass queue", () => {
@@ -40,6 +40,18 @@ describe("askpass queue", () => {
});
});
describe("askpass title", () => {
it("names git HTTPS credentials without calling them SSH", () => {
expect(askpassTitle({ kind: "secret", prompt: "Password for 'https://[email protected]': " })).toBe("Password");
expect(askpassTitle({ kind: "text", prompt: "Username for 'https://cnb.cool': " })).toBe("Username");
});
it("keeps the SSH titles for ssh prompts", () => {
expect(askpassTitle({ kind: "secret", prompt: "dev@host's password: " })).toBe("SSH Password");
expect(askpassTitle({ kind: "text", prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': " })).toBe("SSH");
});
});
describe("Start SSH Session chooser", () => {
const config = (patch: Partial<SshConfigValid>): SshConfigValid => ({ ...DEFAULT_SSH_CONFIG, ...patch });
@@ -1,9 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerAction } from "@/platform/actions";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { cursorCharRight, history, undo } from "@codemirror/commands";
import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
import { cursorCharRight, history, redo, standardKeymap, undo } from "@codemirror/commands";
import { nextOccurrence, occurrenceSearch } from "@/editor/core/cm/editing";
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { completedSyntaxState } from "@/test/syntax";
import { languages } from "@codemirror/language-data";
import {
@@ -284,14 +285,55 @@ describe("surround with", () => {
describe("template fields", () => {
const selected = (v: EditorView) => v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to);
it("edits the Java fori index from a single caret and lets the initializer be edited separately", async () => {
const doc = "class Main {\n void f() {\n fori\n }\n}";
const v = await editor("java", doc, doc.indexOf("fori") + 4, [history(), keymap.of(standardKeymap)]);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges).toHaveLength(1);
expect(selected(v)).toBe("i");
expect(v.state.selection.main.from).toBe(v.state.doc.toString().indexOf("int i") + "int ".length);
const expanded = v.state.doc.toString();
v.dispatch(v.state.replaceSelection("index"));
const renamed = expanded.replace(/\bi\b/g, "index");
expect(v.state.doc.toString()).toBe(renamed);
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe(expanded);
expect(redo(v)).toBe(true);
expect(v.state.doc.toString()).toBe(renamed);
const afterZero = renamed.indexOf(" = 0") + " = 0".length;
while (v.state.selection.main.head < afterZero) expect(press(v, "ArrowRight")).toBe(true);
expect(v.state.selection.main.head).toBe(afterZero);
expect(v.state.selection.ranges).toHaveLength(1);
expect(press(v, "Backspace")).toBe(true);
v.dispatch(v.state.replaceSelection("1"));
expect(v.state.doc.toString()).toBe(renamed.replace(" = 0", " = 1"));
});
it("keeps one index caret per Java fori expansion", async () => {
const doc = "class Main {\n void f() {\n fori\n fori\n }\n}";
const v = await editor("java", doc);
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges).toHaveLength(2);
expect(v.state.selection.mainIndex).toBe(1);
v.dispatch(v.state.replaceSelection("index"));
expect(v.state.doc.toString().match(/\bindex\b/g)).toHaveLength(6);
expect(press(v, "Enter")).toBe(true);
expect(v.state.selection.ranges.every((range) => range.empty)).toBe(true);
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["index", "index"]);
});
it("links fields and advances all carets through separately indented expansions", async () => {
const doc = "function first() {\n fori\n}\nfunction second() {\n fori\n}";
const v = await editor("typescript", doc, undefined, [history()]);
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
const before = v.state.selection;
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(Array(6).fill("i"));
expect(v.state.selection.mainIndex).toBe(3);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["i", "i"]);
expect(v.state.selection.mainIndex).toBe(1);
expect(v.state.doc.line(3).text).toBe(" ");
expect(v.state.doc.line(8).text).toBe(" ");
@@ -301,7 +343,7 @@ describe("template fields", () => {
expect(v.state.selection.ranges).toHaveLength(2);
expect(v.state.selection.ranges.every((r) => v.state.sliceDoc(r.head, r.head + 7) === ".length")).toBe(true);
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
expect(v.state.selection.ranges).toHaveLength(6);
expect(v.state.selection.ranges).toHaveLength(2);
expect(tab(v)).toBe(true);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges.map((r) => r.head)).toEqual([v.state.doc.line(3).to, v.state.doc.line(8).to]);
@@ -365,15 +407,36 @@ describe("template fields", () => {
await tick();
expect(press(v, "Escape")).toBe(true);
expect(v.state.selection.main.empty).toBe(true);
expect(hasNextSnippetField(v.state)).toBe(true);
expect(hasLinkedSnippetField(v.state, 1)).toBe(true);
expect(press(v, "Escape")).toBe(true);
expect(hasNextSnippetField(v.state)).toBe(false);
expect(hasLinkedSnippetField(v.state, 1)).toBe(false);
// Outside a template Enter and Esc are left to the editor.
expect(press(v, "Escape")).toBe(false);
});
});
describe("⌘J Insert Live Template", () => {
it.each([
{ label: "sout", insert: "System.out.println();" },
{ label: "fori", insert: "for (int i = 0; i < ; i++) {" },
])("replaces a backward selection when picking $label", async ({ label, insert }) => {
const text = "class Main {\n void f() {\n payload\n leftover\n return;\n }\n}";
const from = text.indexOf("payload");
const to = text.indexOf("leftover") + "leftover".length;
const v = await editor("java", text, from, [autocompletion()]);
v.dispatch({ selection: { anchor: to, head: from } });
insertLiveTemplate(v);
const result = await templateCompletionSource(new CompletionContext(v.state, from, true));
const option = result?.options.find((candidate) => candidate.label === label);
if (typeof option?.apply !== "function") throw new Error("Expected a live template completion");
option.apply(v, option, result!.from, from);
expect(v.state.doc.line(3).text.trim()).toBe(insert);
expect(v.state.doc.toString()).not.toMatch(/payload|leftover/);
expect(v.state.doc.toString()).toContain("return;");
expect(v.state.selection.ranges).toHaveLength(1);
});
it("opens a lookup restricted to live templates and ends with it", async () => {
const v = await editor("typescript", "function f() {\n ", undefined, [autocompletion()]);
const exclusive = () =>
+11 -71
View File
@@ -4,13 +4,11 @@
* application / field navigation.
*/
import {
clearSnippet,
closeCompletion,
completionStatus,
nextSnippetField,
pickedCompletion,
prevSnippetField,
snippet,
snippetKeymap,
startCompletion,
type Completion,
@@ -18,16 +16,7 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import {
EditorSelection,
EditorState,
Facet,
Prec,
StateEffect,
StateField,
type Extension,
type Transaction,
} from "@codemirror/state";
import { EditorSelection, EditorState, Facet, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, keymap, type Command } from "@codemirror/view";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
@@ -50,14 +39,7 @@ import { showChooser, type ChooserItem } from "./popup/store";
import { expandEmmetAtCaret } from "./emmet/editor";
import { hasEmmet, loadEmmet } from "./emmet/model";
import { readClipboardPlainText } from "@/platform/clipboard";
import {
applyMulticaretSnippet,
clearMulticaretSnippet,
hasMulticaretSnippet,
moveMulticaretField,
multicaretFieldMoved,
multicaretSnippetExtension,
} from "./multicaretSnippet";
import { applySnippet, escapeSnippet, nextLiveSnippetField, snippetFieldMoved } from "@/editor/core/cm/linkedSnippet";
export interface TemplateDocInfo {
path: string;
@@ -149,23 +131,19 @@ async function expandAtSites(
const clipboard = needsClipboard(t) ? await readClipboard() : "";
if (view.state.doc !== state.doc || !view.state.selection.eq(state.selection) || view.state.readOnly) return;
let expansions = sites.map(({ from }) => expansionAt(state, t, from, clipboard, opts));
if (sites.length === 1) {
const { from, to } = sites[0]!;
clearMulticaretSnippet(view);
snippet(expansions[0]!.snippet)(view, null, from, to);
} else {
if (sites.length > 1) {
// A variable stays editable everywhere if any caret needs it as a tab stop.
const editable = new Set(expansions.flatMap((e) => e.fields));
if (expansions.some((e) => e.fields.length !== editable.size)) {
const variables = t.variables?.map((v) => (editable.has(v.name) ? { ...v, skipIfDefined: false } : v));
expansions = sites.map(({ from }) => expansionAt(state, { ...t, variables }, from, clipboard, opts));
}
applyMulticaretSnippet(
view,
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
);
}
const exp = expansions[0]!;
applySnippet(
view,
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
);
if (view.state.field(fieldCompletion, false) !== undefined)
view.dispatch({ effects: setFieldCompletion.of(exp.completing) });
if (exp.completeFirst) setTimeout(() => startCompletion(view), 0);
@@ -189,63 +167,29 @@ const fieldCompletion = StateField.define<readonly boolean[]>({
update: (value, tr) => tr.effects.find((e) => e.is(setFieldCompletion))?.value ?? value,
});
/**
* The snippet field a transaction moves to. CodeMirror doesn't expose it; its
* snippet-state effect carries the active snippet (`{ ranges, active }`).
*/
function movedToField(tr: Transaction): number | null {
for (const e of tr.effects) {
const v = e.value as { active?: unknown; ranges?: unknown } | null;
if (v && typeof v === "object" && typeof v.active === "number" && Array.isArray(v.ranges)) return v.active;
}
return null;
}
/** Moving to a field that asks for completion opens it, as IDEA does. */
const completeOnFieldMove = EditorView.updateListener.of((u) => {
if (u.docChanged) return;
const flags = u.state.field(fieldCompletion);
const field = u.transactions.map((tr) => multicaretFieldMoved(tr) ?? movedToField(tr)).findLast((i) => i !== null);
const field = u.transactions.map((tr) => snippetFieldMoved(tr)).findLast((i) => i !== undefined);
if (field == null || !flags[field]) return;
setTimeout(() => {
if (u.view.state.selection === u.state.selection) startCompletion(u.view);
}, 0);
});
/**
* Esc in a template, as in IDEA: first drops the selection (closing the lookup)
* or closes the lookup; only with neither does it leave the template.
*/
export const escapeTemplate: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearMulticaretSnippet(view) || clearSnippet(view);
};
const unlessLookup =
(cmd: Command): Command =>
(view) =>
completionStatus(view.state) === "active" ? false : cmd(view);
const nextMulticaretField = moveMulticaretField(1);
/**
* Whether the active snippet came from a live template or Emmet, where Enter moves to the
* next field. A completion's snippet (an LSP `<tag>$1</tag>$0`) keeps Enter for new lines.
*/
const templateSnippet = StateField.define<boolean>({
create: () => false,
update: (value, tr) => (movedToField(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
update: (value, tr) => (snippetFieldMoved(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
});
/** Tab moves to the next field; Enter too in templates (the lookup's while it is open). */
@@ -255,7 +199,7 @@ const templateFieldKeys = snippetKeymap.of([
key: "Enter",
run: unlessLookup((view) => view.state.field(templateSnippet, false) === true && nextSnippetField(view)),
},
{ key: "Escape", run: escapeTemplate },
{ key: "Escape", run: escapeSnippet },
]);
// ---------------------------------------------------------------------------
@@ -672,7 +616,6 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
fieldCompletion,
templateSnippet,
completeOnFieldMove,
multicaretSnippetExtension,
templateFieldKeys,
templateLookup,
endTemplateLookup,
@@ -685,14 +628,11 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
]),
Prec.high(
keymap.of([
{ key: "Enter", run: unlessLookup(nextMulticaretField) },
{ key: "Escape", run: (view) => hasMulticaretSnippet(view.state) && escapeTemplate(view) },
{ key: "Enter", run: unlessLookup(nextLiveSnippetField) },
{
key: "Tab",
shift: moveMulticaretField(-1),
run: (view) => {
if (view.state.readOnly || completionStatus(view.state) === "active") return false;
if (nextMulticaretField(view)) return true;
if (expandPostfixAtCaret(view)) return true;
if (useLiveTemplateOptions.getState().expandWithTab && expandLiveTemplateAtCaret(view)) return true;
return expandEmmetAtCaret(view, ctx.language);
+8
View File
@@ -153,6 +153,14 @@ export const BUILTIN_FILE_TEMPLATES: readonly FileTemplate[] = [
},
],
},
{
id: "svelte",
name: "Svelte Component",
icon: "file-svelte",
extension: "svelte",
nameStyle: "asis",
kinds: [{ id: "component", label: "Svelte Component", body: "<script>\n $END$\n</script>\n" }],
},
{
id: "javascript",
name: "JavaScript File",
+3 -2
View File
@@ -93,9 +93,10 @@ function newFileAction(t: FileTemplate): Action {
};
}
// Generic templates and user or plugin templates have no project type restriction; nor do the web
// ones (JavaScript, TypeScript), which IntelliJ IDEA Ultimate offers in every project.
// Generic templates (including JavaScript and TypeScript) and user or plugin templates
// have no project type restriction.
const templateProjectTypes: Partial<Record<string, readonly ProjectType[]>> = {
svelte: ["vite", "node"],
rust: ["cargo"],
python: ["python"],
jupyter: ["python"],
-180
View File
@@ -1,180 +0,0 @@
import { clearSnippet, nextSnippetField, snippet } from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
EditorSelection,
EditorState,
MapMode,
StateEffect,
StateField,
Text,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type Command } from "@codemirror/view";
export interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface ActiveFields {
groups: readonly EditorSelection[];
active: number;
}
const setFields = StateEffect.define<ActiveFields | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
const fields = StateField.define<ActiveFields | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((e) => e.is(setFields));
if (next) return next.value;
if (!value) return null;
const { active } = value;
let { groups } = value;
if (tr.docChanged) {
const mapped: EditorSelection[] = [];
for (const group of groups) {
const ranges = [];
for (const range of group.ranges) {
const from = tr.changes.mapPos(range.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(range.to, 1, MapMode.TrackDel);
if (from === null || to === null) return null;
ranges.push(EditorSelection.range(from, to));
}
mapped.push(EditorSelection.create(ranges, group.mainIndex));
}
groups = mapped;
}
const current = groups[active]!.ranges;
if (tr.selection && !tr.selection.ranges.every((r) => current.some((f) => f.from <= r.from && r.to <= f.to)))
return null;
return groups === value.groups ? value : { groups, active };
},
provide: (field) =>
EditorView.decorations.from(field, (v) =>
v
? Decoration.set(
v.groups.flatMap((g) => g.ranges.map((r) => (r.empty ? fieldCursor : fieldMark).range(r.from, r.to))),
true,
)
: Decoration.none,
),
});
export const hasMulticaretSnippet = (state: EditorState) => !!state.field(fields, false);
export function multicaretFieldMoved(tr: Transaction): number | undefined {
return tr.effects.find((e) => e.is(setFields))?.value?.active;
}
export const clearMulticaretSnippet: Command = (view) => {
if (!hasMulticaretSnippet(view.state)) return false;
view.dispatch({ effects: setFields.of(null) });
return true;
};
function selectField(view: EditorView, value: ActiveFields, active: number): boolean {
const selection = value.groups[active];
if (!selection) return false;
view.dispatch({
selection,
effects: setFields.of(active === value.groups.length - 1 ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export const moveMulticaretField =
(direction: 1 | -1): Command =>
(view) => {
const value = view.state.field(fields, false);
return value ? selectField(view, value, value.active + direction) : false;
};
export const multicaretSnippetExtension = [
fields,
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const index = value.groups.findIndex((g) => g.ranges.some((r) => r.from <= pos && pos <= r.to));
return index !== value.active && selectField(view, value, index);
},
}),
];
/** Ask CodeMirror to render each snippet in its line's indentation and expose its tab stops. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
let state = EditorState.create({
doc: line.text,
selection: EditorSelection.cursor(to),
extensions: [EditorState.allowMultipleSelections.of(true), indentUnit.of(source.facet(indentUnit))],
});
const dispatch = (tr: Transaction) => {
state = tr.state;
};
let insert = Text.empty;
snippet(site.snippet)(
{
state,
dispatch: (tr) => {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
dispatch(tr);
},
},
null,
from,
to,
);
const groups = [];
do {
groups.push(state.selection);
} while (nextSnippetField({ state, dispatch }));
return { from: site.from, to: site.to, offset: from, insert, groups };
}
export function applyMulticaretSnippet(view: EditorView, sites: readonly SnippetSite[]) {
const { state } = view;
const entries = sites.map((site) => instantiate(state, site));
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
const groups = entries[0]!.groups.map((_, field) => {
let main = 0;
const ranges = entries.flatMap((entry, i) => {
const group = entry.groups[field]!;
const offset = changes.mapPos(entry.from, -1) - entry.offset;
if (i < state.selection.mainIndex) main += group.ranges.length;
return group.ranges.map((r) => EditorSelection.range(r.from + offset, r.to + offset));
});
return EditorSelection.create(ranges, main);
});
clearSnippet(view);
view.dispatch({
changes,
selection: groups[0]!,
effects: setFields.of(groups.length > 1 ? { groups, active: 0 } : null),
annotations: isolateHistory.of("full"),
scrollIntoView: true,
});
}
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more