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

...
Автор SHA1 Повідомлення Дата
l0ng-ai b6c7c519f3 fix(run): resolve Java launches in attached projects 2026-11-23 21:58:42 +08:00
aconeshanaтаaconeshana 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 Verhelstтаbertyhell 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 Verhelstтаbertyhell 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 Verhelstтаbertyhell 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 Verhelstтаbertyhell 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
faysouтаfaysou 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 Verhelstтаbertyhell 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 Verhelstтаbertyhell 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 Ismoilovтаshohruh-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
faysouтаfaysou 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
faysouтаfaysou 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
faysouтаfaysou 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
faysouтаfaysou 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
faysouтаfaysou 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
faysouтаfaysou 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
faysouтаfaysou 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-boopтаakshathayadav378-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 Verhelstтаbertyhell 546ff9f314 fix(run): resolve External Tools file macros against the Project view selection (#5415)
External Tools expanded $FilePath$ and the other file macros from the editor's file even while the Project view was the user's context. They now take the Project view's selected file while it is the context (no editor focus, not a virtual document); caret macros apply only when the editor shows that same file.

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

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

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

Line numbers stay beside the start of their rows when code wraps, and follow scrolling inside a large removed block. Matching rows keep their original numbers when empty lines are ignored. The column order also applies when the editable side is the Git index.
2026-11-23 15:44:15 +08:00
l0ng-ai 8a4b8f45b4 fix(agents): shorten task context menu labels (#5394) 2026-11-23 15:35:46 +08:00
140 змінених файлів з 4180 додано та 627 видалено

No files matched your search

Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 160 KiB

Після

Ширина:  |  Висота:  |  Розмір: 138 KiB

Створено
+2 -2
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
+50
Переглянути файл
@@ -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);
+53
Переглянути файл
@@ -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"});
+17
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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,
})
+57 -62
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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,
+101
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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.
+3 -3
Переглянути файл
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
## Manage agents
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
### External MCP servers
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ A file holds only the values that differ from the layer below. Tables merge key
Some settings are ignored in the project file: `mcpServer`, imported color schemes (`editor.customSchemes`) and `agents.newTaskApprovals` are global only. Project trust is never read from settings.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › External MCP Servers**, and again after its definition changes.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › MCP Connections**, and again after its definition changes.
## File format
+3 -3
Переглянути файл
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
## 管理 agent
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
**设置 › 智能体 › MCP 连接** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ description: "OpenIDEA 的设置保存在哪里、全局文件与项目文件如
有些设置在项目文件中会被忽略:`mcpServer`、导入的配色方案(`editor.customSchemes`)和 `agents.newTaskApprovals` 只能全局配置。项目信任状态永远不会从设置文件中读取。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › 外部 MCP 服务器** 中将其开启;服务器定义改变后也需要重新开启。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › MCP 连接** 中将其开启;服务器定义改变后也需要重新开启。
## 文件格式
+8 -4
Переглянути файл
@@ -308,11 +308,15 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
await sessionPopup.getByRole("button", { name: "Reset" }).click();
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
// 2. Jump directly from the session MCP popover's gear button to Settings › Agents › MCP Connections.
await sessionPopup.getByRole("button", { name: "MCP Connections…", exact: true }).click();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "MCP Connections", exact: true })).toBeVisible();
await expect(settingsDialog.getByRole("treeitem", { name: "MCP Connections", exact: true })).toHaveAttribute(
"aria-selected",
"true",
);
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
@@ -321,7 +325,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "External MCP Servers" })
.getByRole("heading", { name: "MCP Connections", exact: true })
.evaluate((el) => el.scrollIntoView({ block: "start" }));
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
+111
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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);
});
+52
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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 }) => {
+6 -2
Переглянути файл
@@ -90,6 +90,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 +102,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 -1
Переглянути файл
@@ -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();
+2
Переглянути файл
@@ -385,6 +385,8 @@ test("edits and stages from the index in unified diffs of read-only files", asyn
const index = modal.locator('.cm-content[aria-label="Staged (index)"]');
await expect(index).toBeEditable();
await expect(index).toHaveText(/val alpha = "index"\s+val alpha = "local"/, { useInnerText: true });
await expect(modal.locator(".cm-diffNumbers-modified .cm-diffWidgetNumber")).toHaveText(["1", "3"]);
await expect(modal.locator(".cm-diffNumbers-original .cm-diffWidgetNumber")).toHaveCount(0);
const setReadOnly = (readOnly: boolean) =>
page.evaluate((readOnly) => window.__ipc.handlers.test_set_readonly?.({ readOnly }), readOnly);
await setReadOnly(false);
+79
Переглянути файл
@@ -0,0 +1,79 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("groups stashes by repository and keeps the selected stash actions scoped", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(async () => {
const main = "/dev/acme-api";
const service = `${main}/warehouse-api`;
const stash = (index: number, id: string, title: string) => ({
index,
id,
message: `On main: ${title}`,
base: "base",
timeMs: new Date(2025, 4, 14, 10, 30).getTime(),
});
const handlers = window.__ipc.handlers;
handlers.vcs_stashes = ({ repo }) =>
repo === service
? [stash(0, "warehouse-stash", "Review warehouse routing")]
: [stash(0, "ledger-stash", "Check totals"), stash(1, "invoice-stash", "Match invoice balances")];
handlers.vcs_commit_files = ({ repo }) => [
{ path: repo === service ? "routing.txt" : "totals.txt", kind: "modified", oldPath: null },
];
const store = "/src/features/vcs/store.ts";
const context = "/src/platform/context.ts";
const actions = "/src/platform/actions.ts";
const toolWindows = "/src/workbench/toolwindows/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
const { setContext } = await import(/* @vite-ignore */ context);
const { executeAction } = await import(/* @vite-ignore */ actions);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ toolWindows);
useVcs.setState({ available: true, root: main, repo: main, roots: [main, service] });
setContext("vcsAvailable", true);
moveToolWindow("commit", "bottom");
await executeAction("vcs.showStashes");
setToolWindowSize("bottom", 310);
});
const tree = page.getByRole("tree", { name: "Stashes", exact: true });
const main = tree.getByRole("treeitem").filter({ has: page.getByText("acme-api", { exact: true }) });
const service = tree.getByRole("treeitem", { name: /warehouse-api/ });
const apply = page
.getByRole("toolbar", { name: "Stashes", exact: true })
.getByRole("button", { name: "Apply Stash" });
const first = tree.getByRole("treeitem", { name: /Check totals/ });
await expect(service, "repository group starts expanded").toHaveAttribute("aria-expanded", "true");
await expect(main).toHaveAccessibleName(/acme-api\s*2/);
await expect(first).toHaveAttribute("aria-level", "2");
await expect(first).toHaveAttribute("aria-selected", "true");
for (const width of [1100, 440]) {
await page.setViewportSize({ width, height: 720 });
const subject = first.getByText("Check totals", { exact: true });
const date = subject.locator("xpath=following-sibling::*[1]");
await expect(date).toHaveText(/2025/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(date).toHaveCSS("font-size", await subject.evaluate((el) => getComputedStyle(el).fontSize));
const titleBox = (await subject.boundingBox())!;
const dateBox = (await date.boundingBox())!;
expect(dateBox.x - titleBox.x - titleBox.width).toBeCloseTo(6, 0);
}
await tree.focus();
await tree.press("Home");
await tree.press("ArrowLeft");
await expect(main).toHaveAttribute("aria-expanded", "false");
await expect(first).toHaveCount(0);
await expect(apply).toBeDisabled();
await expect(page.getByText("Select a stash to view its changes.")).toBeVisible();
await tree.press("ArrowRight");
await expect(first).toBeVisible();
await tree.getByText("Review warehouse routing", { exact: true }).click();
await expect(apply).toBeEnabled();
await expect(page.getByRole("tree", { name: "Changed files" }).getByText("routing.txt")).toBeVisible();
expect((await ipcCalls(page, "vcs_commit_files")).at(-1)).toEqual({
repo: "/dev/acme-api/warehouse-api",
commit: "warehouse-stash",
});
});
+123
Переглянути файл
@@ -0,0 +1,123 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function seedReview(page: Page) {
await stubDesktop(page);
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const context = "/src/platform/context.ts";
const repositoryStore = "/src/features/github/data/repository.ts";
const pullRequests = "/src/features/github/data/pullRequest.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { setContext } = await import(/* @vite-ignore */ context);
const { useGhRepository } = await import(/* @vite-ignore */ repositoryStore);
const { setPullRequestData } = await import(/* @vite-ignore */ pullRequests);
useProject.setState((s: { settings: { editor: unknown } }) => ({
settings: {
...s.settings,
editor: { ...(s.settings?.editor as object), fontFamily: "Courier New", fontSize: 17, lineHeight: 25 },
},
}));
const coordinates = { owner: "sample", name: "settlement" };
useGhRepository.setState({
connection: {
coordinates,
repository: { id: "repository", nameWithOwner: "sample/settlement" },
currentUser: { id: "reviewer", login: "reviewer" },
root: null,
remotes: [],
},
});
setContext("githubConnected", true);
setContext("githubCurrentBranchPullRequest", true);
setPullRequestData(7, "details", () => ({ number: 7, viewerDidAuthor: false }));
setPullRequestData(7, "pendingReview", () => ({ id: "draft-seven", state: "PENDING", commentsCount: 12 }));
});
}
async function openReview(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("github.pullRequest.submitReview", 7);
});
}
test("centers the unanchored composer, follows the editor font and reflows its review actions", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 840 });
await seedReview(page);
await openReview(page);
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const verticalCenter = () =>
popup.evaluate((el) => {
const { top, height } = el.getBoundingClientRect();
return Math.abs(top + height / 2 - innerHeight / 2);
});
await expect.poll(verticalCenter, { message: "verticalCenter at standard size" }).toBeLessThan(1);
await expect(editor).toBeFocused();
await expect(editor).toHaveCSS("font-size", "17px");
await expect(editor).toHaveCSS("line-height", "25px");
await expect(editor).toHaveCSS("font-family", /Courier New/);
await editor.fill("Please double-check the rounding step.");
const grip = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 56, grip.y + grip.height / 2 + 32);
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(540);
await page.setViewportSize({ width: 300, height: 400 });
await expect.poll(verticalCenter, { message: "verticalCenter after shrinking" }).toBeLessThan(1);
const approve = (await popup.getByRole("button", { name: "Approve", exact: true }).boundingBox())!;
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
expect(comment.y).toBeGreaterThan(approve.y);
expect(comment.x + comment.width).toBeLessThan(300);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await editor.press("Escape");
await expect(popup).toHaveCount(0);
await openReview(page);
await expect(editor).toHaveValue("Please double-check the rounding step.");
});
test("keeps anchored review controls and the comment visible after a long submission error", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 355, height: 390 });
await seedReview(page);
await page.evaluate(async () => {
const path = "/src/features/github/details/SubmitReviewPopup.tsx";
const { showSubmitReview } = await import(/* @vite-ignore */ path);
const anchor = document.createElement("button");
anchor.style.cssText = "position:fixed;top:350px;left:275px;";
anchor.textContent = "Review anchor";
document.body.append(anchor);
window.__ipc.handlers.gh_api = ({ request }) => {
const { query } = JSON.parse((request as { body: string }).body);
if (!query.includes("submitPullRequestReview")) throw Error("Unexpected GitHub request");
return JSON.stringify({ errors: [{ message: "Review request failed. " + "outdated-reference-".repeat(35) }] });
};
void showSubmitReview(7, anchor);
});
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const button = popup.getByRole("button", { name: "Comment", exact: true });
await editor.fill("Check the batch limit.");
await button.click();
const error = popup.getByRole("alert");
await expect(error).toContainText("Review request failed.");
await expect(button).toBeEnabled();
await expect(editor).toHaveValue("Check the batch limit.");
const box = (await popup.boundingBox())!;
const buttonBox = (await button.boundingBox())!;
expect(box.y + box.height).toBeLessThan(350);
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(box.y + box.height);
expect(box.x + box.width).toBeLessThanOrEqual(355);
await expect.poll(() => error.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
const calls = await ipcCalls(page, "gh_api");
expect(calls).toHaveLength(1);
const { variables } = JSON.parse((calls[0]!.request as { body: string }).body);
expect(variables).toEqual({ reviewId: "draft-seven", event: "COMMENT", body: "Check the batch limit." });
});
+88
Переглянути файл
@@ -0,0 +1,88 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openDiff(page: Page, left: string, right: string, options: Record<string, unknown> = {}) {
await page.evaluate(
async ({ left, right, options }) => {
localStorage.setItem(
"openidea.vcs.diffOptions",
JSON.stringify({ mode: "unified", collapse: false, ...options }),
);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("diff.compareTexts", {
path: "SettlementRules.txt",
left: { text: left, label: "Original" },
right: { text: right, label: "Modified" },
});
},
{ left, right, options },
);
return page.getByRole("toolbar", { name: "Diff" });
}
async function rowNumbers(page: Page, text: string, deleted = false) {
return page
.locator(deleted ? ".cm-deletedLine" : ".cm-line")
.filter({ hasText: text })
.evaluate((row) => {
const top = row.getBoundingClientRect().top;
const editor = row.closest(".cm-editor")!;
const read = (side: string) =>
[...editor.querySelectorAll(`.cm-diffNumbers-${side} :is(.cm-gutterElement, .cm-diffWidgetNumber)`)].find(
(number) =>
getComputedStyle(number).visibility === "visible" && Math.abs(number.getBoundingClientRect().top - top) < 1,
)?.textContent ?? null;
return [read("original"), read("modified")];
});
}
test("Unified Diff keeps original and modified numbers aligned with wrapped and removed lines", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1000, height: 640 });
const oldRule = "Obsolete settlement rule " + "requires review for each exceptional invoice. ".repeat(3);
const toolbar = await openDiff(
page,
["Settlement rules", oldRule, "Retire legacy routing", "Report totals", "Finish batch"].join("\n"),
["Settlement rules", "Validate settlement currency", "Report totals", "Finish batch"].join("\n"),
{ softWrap: true },
);
await expect(toolbar).toContainText("1 difference");
for (const width of [1000, 440]) {
await page.setViewportSize({ width, height: 640 });
await expect.poll(() => rowNumbers(page, "Obsolete settlement rule", true)).toEqual(["2", null]);
await expect.poll(() => rowNumbers(page, "Retire legacy routing", true)).toEqual(["3", null]);
await expect.poll(() => rowNumbers(page, "Validate settlement currency")).toEqual([null, "2"]);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["4", "3"]);
}
const removed = page.locator(".cm-deletedLine").filter({ hasText: "Obsolete settlement rule" });
const lineHeight = await removed.evaluate((el) => parseFloat(getComputedStyle(el).lineHeight));
expect((await removed.boundingBox())!.height).toBeGreaterThan(lineHeight * 2);
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(toolbar).toContainText("1 of 1 differences");
});
test("Unified Diff numbers account for ignored empty lines and a removal at EOF without a newline", async ({
workbench: page,
}) => {
await openDiff(
page,
"Settlement rules\n\nReport totals\nFinish batch\nRemove final rule",
"Settlement rules\nReport totals\nFinish batch",
{ ignore: "whitespaceAndLines" },
);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["3", "2"]);
await expect.poll(() => rowNumbers(page, "Finish batch")).toEqual(["4", "3"]);
await expect.poll(() => rowNumbers(page, "Remove final rule", true)).toEqual(["5", null]);
});
test("Unified Diff follows vertical scrolling inside one large removal", async ({ workbench: page }) => {
const removed = Array.from({ length: 250 }, (_, i) => `Retired workflow ${i + 1}.`);
await openDiff(page, ["Start batch", ...removed, "Finish batch"].join("\n"), "Start batch\nFinish batch");
const target = page.locator(".cm-deletedLine").filter({ hasText: "Retired workflow 229." });
await target.scrollIntoViewIfNeeded();
await expect.poll(() => rowNumbers(page, "Retired workflow 229.", true)).toEqual(["230", null]);
});
+73 -7
Переглянути файл
@@ -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();
+2
Переглянути файл
@@ -2529,6 +2529,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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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);
+113 -5
Переглянути файл
@@ -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
Переглянути файл
@@ -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. */
+8 -2
Переглянути файл
@@ -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}
-1
Переглянути файл
@@ -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",
+1 -1
Переглянути файл
@@ -1,5 +1,5 @@
/**
* Settings › Agents › Coding Agents: one searchable list of every agent, those this machine can run first
* Agent Setup lists every agent, with those this machine can run first
* (built in, installed from the ACP Registry, or defined in an agent file), then those it
* can install. The selected agent's page holds its actions, the settings its new tasks
* start with, and how it is launched. Launch edits are staged until Apply; installs run in
+2 -3
Переглянути файл
@@ -1,6 +1,5 @@
/**
* Settings › Tools › Agents › Command Permissions: whitelist (auto-approve)
* and blacklist (auto-reject) command patterns evaluated on agent permission requests.
* Command Rules defines the allow and block patterns for agent permission requests.
*/
import { useMemo, useState } from "react";
import { tx } from "@/platform/i18n";
@@ -47,7 +46,7 @@ export function AgentPolicyPage() {
};
return (
<section className={styles.body} aria-label="Command Permissions">
<section className={styles.body} aria-label={tx("Command Rules")}>
<p className={styles.notice}>
<T>
Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
/** Settings › Agents › Coding Agents. */
/** Settings › Agents › Agent Setup. */
import { AgentList } from "./AgentList";
import { tauriCommands, tauriRegistry, type CommandsBackend, type RegistryBackend } from "./registry";
import styles from "./AgentRegistry.module.css";
+2 -1
Переглянути файл
@@ -224,11 +224,12 @@
flex: none;
}
/* Import Sessions from Other Apps: filter above a fixed-height list, so the dialog doesn't grow. */
/* Keep the import list height stable while filtering. */
.chooser {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: var(--space-3) var(--space-4) 0;
}
.chooserList {
height: 312px;
+6 -5
Переглянути файл
@@ -281,8 +281,9 @@ describe("Agents docked view", () => {
]);
});
it("lists Import Sessions from Other Apps in Find Action", () => {
it("lists Import Sessions in Find Action", () => {
const action = taskActions.find((a) => a.id === "agents.importSessions");
expect(action?.title).toBe("Import Sessions…");
expect(action?.hidden).toBeFalsy();
expect(action?.when).toBe("projectOpen");
act(() => void action?.run({} as never));
@@ -502,17 +503,17 @@ describe("Agents pinned and grouped tasks", () => {
expect(rows.some((text) => text.includes("one"))).toBe(true);
});
it("offers the groups, a new one and a way out in Move to Group", () => {
it("offers the groups, a new one and a way out in the Group submenu", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: { two: "g1" }, pinned: [] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Move to Group");
const move = menu.find((item) => "label" in item && item.label === "Group");
expect(move).toBeDefined();
const submenu = (move as { submenu: { label?: string; checked?: boolean }[] }).submenu;
expect(submenu.map((item) => item.label ?? "separator")).toEqual([
"Frontend",
"separator",
"New Group…",
"Remove from Group",
"No Group",
]);
expect(submenu[0]).toMatchObject({ checked: true });
});
@@ -520,7 +521,7 @@ describe("Agents pinned and grouped tasks", () => {
it("moves a pinned task into a group, out of the pinned section", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: {}, pinned: ["two"] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Move to Group") as {
const move = menu.find((item) => "label" in item && item.label === "Group") as {
submenu: { label?: string; run?: () => void }[];
};
act(() => move.submenu.find((item) => item.label === "Frontend")!.run!());
+40
Переглянути файл
@@ -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>
);
}
+2 -2
Переглянути файл
@@ -1,4 +1,4 @@
/** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */
/** Pick external sessions and import them as agent tasks. */
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui";
import { useRowHeight } from "@/ui/density";
@@ -160,7 +160,7 @@ function ImportSessionsDialog() {
<Dialog
open
onClose={close}
title="Import Sessions from Other Apps"
title="Import Sessions"
width={560}
footerStart={
<span className={styles.chooserFooter}>
+2 -2
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Per-session MCP picker for the New Task and Session composers: shows inherited IDE, Project,
* Global, and Agent-Native CLI MCP servers, lets the user toggle servers for this session only,
* reset session overrides, or jump to Settings › Agents › External MCP Servers.
* reset session overrides, or jump to Settings › Agents › MCP Connections.
*/
import { useMemo, useState } from "react";
import type { McpExternalSource, McpServer } from "@/bindings";
@@ -110,7 +110,7 @@ export function McpPicker({
}}
triggerAriaLabel={tx("MCP servers")}
popupTitle={tx("Session MCP Servers")}
settingsTitle={tx("External MCP Servers…")}
settingsTitle={tx("MCP Connections…")}
settingsPage={MCP_PAGE}
counts={{ active: resolved.activeCount, total: resolved.totalCount, overrides: resolved.overrideCount }}
search={{ placeholder: tx("Filter MCP servers…"), ariaLabel: tx("Filter MCP servers"), shown: totalRows > 5 }}
+2 -2
Переглянути файл
@@ -1,5 +1,5 @@
/**
* Settings › Agents › External MCP Servers: multi-level MCP management across Global (`settings.toml`
* Settings › Agents › MCP Connections: multi-level MCP management across Global (`settings.toml`
* + Keychain), Project (`.openidea/settings.toml`), and Agent CLI config directories
* (`~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`,
* `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, `.vscode/mcp.json`), with
@@ -535,7 +535,7 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB
<div className={page.page}>
<div className={page.header}>
<h2 className={page.title}>
<T>External MCP Servers</T>
<T>MCP Connections</T>
</h2>
<div className={page.headerActions}>
<Button
+13 -2
Переглянути файл
@@ -202,6 +202,8 @@
overflow-x: hidden;
overflow-anchor: none;
padding: var(--space-3);
/* Room below the end that keeps the header of a section folded there in place (`Stream`). */
padding-bottom: calc(var(--space-3) + var(--stream-slack, 0px));
display: flex;
flex-direction: column;
font-size: var(--agent-fs-ui, var(--fs-ui));
@@ -229,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
@@ -1195,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;
@@ -1274,7 +1285,7 @@
}
.changesScope {
flex: none;
padding: 6px 10px 2px;
padding: 0 4px;
}
.changesSummary {
flex: none;
+3 -3
Переглянути файл
@@ -32,7 +32,7 @@ function FormWrapper({ children }: { children: ReactNode }) {
return <SettingsFormContext.Provider value={form}>{children}</SettingsFormContext.Provider>;
}
describe("Command Permissions sub-page", () => {
describe("Command Rules sub-page", () => {
it("registers under Agents group in settings", () => {
const dispose = activateSettingsPages();
try {
@@ -40,7 +40,7 @@ describe("Command Permissions sub-page", () => {
const agentsGroup = tree.find((n) => n.title === AGENTS_GROUP);
expect(agentsGroup).toBeDefined();
const policyNode = agentsGroup?.children.find((n) => n.key === POLICY_PAGE);
expect(policyNode?.title).toBe("Command Permissions");
expect(policyNode?.title).toBe("Command Rules");
// A project's settings file can't decide what agents run without asking.
expect(policyNode?.page?.projectScope).not.toBe(true);
} finally {
@@ -56,7 +56,7 @@ describe("Command Permissions sub-page", () => {
</FormWrapper>,
);
const policy = screen.getByRole("region", { name: "Command Permissions" });
const policy = screen.getByRole("region", { name: "Command Rules" });
expect(within(policy).getByText("rm -rf *")).toBeInTheDocument();
fireEvent.change(within(policy).getByRole("textbox", { name: "Allowed command pattern" }), {
+4 -5
Переглянути файл
@@ -313,7 +313,7 @@ export function activate(): () => void {
{
id: "agents.addAgent",
title: "More Agents…",
description: "Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.",
description: "Install, update, or remove agents from the ACP Registry.",
category: "Agents",
icon: "plugin",
keywords: ["agent", "acp", "registry", "install", "update"],
@@ -321,12 +321,11 @@ export function activate(): () => void {
},
{
id: "agents.mcpServers",
title: "External MCP Servers…",
description:
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
title: "MCP Connections…",
description: "Configure the MCP servers that agents can use.",
category: "Agents",
icon: "settings",
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
run: () => void executeAction("file.settings", MCP_PAGE),
},
{
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Shared MCP server model, multi-level inheritance resolution (IDE -> Project -> Global -> Agent CLI),
* and reactive cache for Settings › Agents › External MCP Servers and the Composer MCP picker.
* and reactive cache for Settings › Agents › MCP Connections and the Composer MCP picker.
*/
import { useEffect } from "react";
import { create } from "zustand";
+3 -3
Переглянути файл
@@ -7,15 +7,15 @@ export const HOME_KEY = "agent:new";
export const TOOL_WINDOW = "agents";
/** MIME of a dragged agent task (a tree row or the docked conversation bar): the payload is the task id. */
export const TASK_DRAG = "application/x-openidea-agent-task";
/** Settings › Agents › Coding Agents: the agents this machine runs. */
/** Settings › Agents › Agent Setup. */
export const REGISTRY_PAGE = "agents.list";
/** The Settings folder holding the agent pages. */
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
/** Settings › Agents › MCP Connections. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Command Permissions. */
/** Settings › Agents › Command Rules. */
export const POLICY_PAGE = "agents.policy";
export const sessionKey = (task: string) => `agent:${task}`;
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ import type { AgentProvider } from "@/bindings";
import type { tx as Tx } from "@/platform/i18n";
import type { SelectOption } from "@/ui";
/** Picker entry that opens Settings › Tools › Agents instead of choosing an agent. */
/** Picker entry that opens Settings › Agents › Agent Setup. */
export const ADD_AGENT = "__addAgent__";
/**
+16 -16
Переглянути файл
@@ -4,14 +4,13 @@ import { repositoryPath } from "@/features/vcs/repositoryPaths";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { basename, dirname, relativeDir } from "@/platform/project";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tree } from "@/ui";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tabs, Tree } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChangesResizer } from "../ChangesResizer";
import styles from "../Session.module.css";
import { setChangesOptions, type ChangesScope } from "../changesOptions";
import { SegmentedControl } from "../ConfigPickers";
import { formatSentAt } from "../conversation";
import { branchLabel } from "../model";
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
@@ -386,20 +385,21 @@ export function ChangesPane({
)}
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
</div>
<div className={styles.changesScope}>
<SegmentedControl
ariaLabel={tx("Changes to show")}
options={[
{ value: "task", label: tx("Whole Task") },
{ value: "turn", label: tx("Last Turn") },
]}
value={scope}
onChange={(value) => {
setChangesOptions({ scope: value === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
/>
</div>
<Tabs
variant="compact"
className={styles.changesScope}
aria-label="Changes to show"
activeId={scope}
onSelect={(id) => {
if (id === scope) return;
setChangesOptions({ scope: id === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
items={[
{ id: "task", label: "Whole Task" },
{ id: "turn", label: "Last Turn" },
]}
/>
{(scope === "turn" || grouped || head || task.base) && (
<div className={styles.changesSummary}>
{scope === "turn" ? (
+26 -16
Переглянути файл
@@ -1,4 +1,5 @@
import { createContext, useContext, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
import { createContext, useContext, useRef, useState, type ReactElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
/** Set while Find in Conversation is open: folded sections render their content, so it is found. */
export const FoldedContent = createContext(false);
@@ -9,8 +10,8 @@ export const FoldedContent = createContext(false);
*/
export const OpenFolds = createContext<Map<string, boolean> | null>(null);
/** Scrolls a section the reader just opened into view (`Stream`). */
export const RevealFold = createContext<((el: HTMLElement) => void) | null>(null);
/** Puts a section's header back at `top` (viewport px) after the reader opened or closed it (`Stream`). */
export const KeepFoldHeader = createContext<((header: HTMLElement, top: number) => void) | null>(null);
/**
* A collapsed section that renders its content only once opened: most of a long conversation
@@ -35,29 +36,38 @@ export function Fold({
}) {
const always = useContext(FoldedContent);
const remembered = useContext(OpenFolds);
const reveal = useContext(RevealFold);
const keepHeader = useContext(KeepFoldHeader);
const [expanded, setExpanded] = useState(() => !!open || !!defaultOpen || (!!id && !!remembered?.get(id)));
const ref = useRef<HTMLDetailsElement>(null);
const opened = useRef(false);
// Once its content is laid out, so its height is known.
useLayoutEffect(() => {
if (!expanded || !opened.current) return;
opened.current = false;
if (ref.current) reveal?.(ref.current);
}, [expanded, reveal]);
const remember = (now: boolean) => {
if (!id || !remembered) return;
if (now) remembered.set(id, true);
else remembered.delete(id);
};
return (
<details
ref={ref}
className={className}
open={open || ((!!id || defaultOpen) && expanded) || undefined}
// Toggle here rather than natively: the content renders in the same frame, and the header
// is put back where it was before anything paints.
onClick={(e) => {
const details = ref.current;
const header = e.target instanceof Element ? e.target.closest("summary") : null;
if (e.defaultPrevented || !details || !header || header.parentElement !== details) return;
if ((e.target as Element).closest("a, button, input, select, textarea, label") !== null) return;
e.preventDefault();
const top = header.getBoundingClientRect().top;
const now = !details.open;
details.open = now;
remember(now);
flushSync(() => setExpanded(now));
keepHeader?.(header, top);
}}
onToggle={(e) => {
const now = e.currentTarget.open;
opened.current = now;
setExpanded(now);
if (id && remembered) {
if (now) remembered.set(id, true);
else remembered.delete(id);
}
remember(now);
}}
>
{summary}
+148 -64
Переглянути файл
@@ -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,
@@ -49,7 +50,7 @@ import {
type EntryRow,
} from "./conversationRows";
import { FindBar } from "./FindBar";
import { OpenFolds, RevealFold } from "./Folds";
import { KeepFoldHeader, OpenFolds } from "./Folds";
import { Entry } from "./messages";
import { ProcessRun, TurnFold } from "./ProcessRows";
import { type QuestionAnswer } from "./QuestionForm";
@@ -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 {
@@ -169,15 +177,31 @@ interface StreamProps {
/** Entries rendered at a time when a conversation opens at its end. */
const ENTRY_BATCH = 40;
function scrollsInside(target: EventTarget | null, root: HTMLElement): boolean {
function scrollsY(el: Element): boolean {
if (el.scrollHeight - el.clientHeight <= 1) return false;
const overflow = getComputedStyle(el).overflowY;
return overflow === "auto" || overflow === "scroll";
}
/** The innermost container under `target` that scrolls vertically: a tool output, a run of calls, or `root`. */
function scrollOwner(target: EventTarget | null, root: HTMLElement): HTMLElement {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el.scrollTop <= 0) continue;
const overflow = getComputedStyle(el).overflowY;
if (overflow === "auto" || overflow === "scroll") return true;
if (el instanceof HTMLElement && scrollsY(el)) return el;
}
return root;
}
/** Whether a container inside `root` under `target` can still scroll up. */
function scrollsUpInside(target: EventTarget | null, root: HTMLElement): boolean {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el.scrollTop > 0 && scrollsY(el)) return true;
}
return false;
}
/** A wheel gesture's events arrive closer together than this; a pause starts a new one. */
const WHEEL_GESTURE_MS = 150;
export function Stream({
loadError,
task,
@@ -199,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));
@@ -223,15 +247,22 @@ export function Stream({
const stopFollowing = useCallback(
(target: EventTarget | null) => {
const el = ref.current;
if (!el || el.scrollHeight <= el.clientHeight || scrollsInside(target, el)) return;
if (!el || el.scrollHeight <= el.clientHeight || scrollsUpInside(target, el)) return;
scrollingUp.current = true;
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);
@@ -285,11 +316,31 @@ export function Stream({
const visible = useEditorShown();
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom);
/**
* Blank space after the conversation that lets a section folded near the end keep its header
* in place. It is only ever what the view shows below the content: scrolling up or new rows
* take it back without moving anything.
*/
const slack = useRef(0);
const setSlack = useCallback((px: number) => {
slack.current = px;
if (px) ref.current?.style.setProperty("--stream-slack", `${px}px`);
else ref.current?.style.removeProperty("--stream-slack");
}, []);
const trimSlack = useCallback(() => {
const el = ref.current;
if (!el || slack.current === 0) return;
const content = el.scrollHeight - slack.current;
const next = Math.max(0, Math.min(slack.current, Math.ceil(el.scrollTop + el.clientHeight - content)));
if (next !== slack.current) setSlack(next);
}, [setSlack]);
/** 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;
@@ -314,10 +365,12 @@ export function Stream({
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
trimSlack();
if (position.current.stick) {
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
@@ -328,52 +381,80 @@ 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;
if (!el) return;
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]);
// How far the end was below the view when a section was toggled, before its content renders.
const gapAtToggle = useRef(Infinity);
}, [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
* at its edge doesn't hand the rest to the conversation; a gesture stays with the container
* it started in.
*/
useEffect(() => {
const el = ref.current;
if (!el) return;
const toggled = () => {
gapAtToggle.current = el.scrollHeight - el.scrollTop - el.clientHeight;
let gesture: { owner: HTMLElement; at: number } | null = null;
const onWheel = (e: WheelEvent) => {
if (e.defaultPrevented || e.ctrlKey || e.metaKey) return;
if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
const now = performance.now();
const latched = gesture && now - gesture.at < WHEEL_GESTURE_MS && gesture.owner.isConnected;
const owner = latched ? gesture!.owner : scrollOwner(e.target, el);
gesture = { owner, at: now };
if (owner !== el) {
const room = e.deltaY < 0 ? owner.scrollTop : owner.scrollHeight - owner.clientHeight - owner.scrollTop;
if (room <= 1) e.preventDefault();
return;
}
markUserScroll();
if (e.deltaY < 0) stopFollowing(e.target);
else if (e.deltaY > 0) scrollingUp.current = false;
};
el.addEventListener("toggle", toggled, true);
return () => el.removeEventListener("toggle", toggled, true);
}, []);
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [markUserScroll, stopFollowing]);
/**
* An opened section grew the conversation below its header: with the end in view, stay at
* it; otherwise bring what it shows into view. Either way its header stays on screen, and
* following stops when that leaves the end out of view.
* The reader opened or closed a section: put its header back where it was, in the run or
* output that scrolls it and then in the conversation. Following stops when that leaves any
* of the end out of view, so the next chunk doesn't pull the header away.
*/
const revealFold = useCallback(
(fold: HTMLElement) => {
const keepFoldHeader = useCallback(
(header: HTMLElement, top: number) => {
const el = ref.current;
if (!el || dragging.current) return;
const view = el.getBoundingClientRect();
const box = fold.getBoundingClientRect();
const atEnd = position.current.stick || gapAtToggle.current < 40;
gapAtToggle.current = Infinity;
const below = atEnd ? el.scrollHeight - el.scrollTop - el.clientHeight : box.bottom - view.bottom;
if (below > 0) el.scrollTop += Math.max(0, Math.min(below, box.top - view.top));
if (atEnd && el.scrollHeight - el.scrollTop - el.clientHeight >= 40) {
if (!el?.contains(header)) return;
// Opened, the section fills the room left by an earlier fold first.
trimSlack();
for (let s = header.parentElement; s; s = s.parentElement) {
const moved = header.getBoundingClientRect().top - top;
if (Math.abs(moved) < 1) break;
if (s === el) {
const short = Math.ceil(el.scrollTop + moved + el.clientHeight - el.scrollHeight);
if (short > 0) setSlack(slack.current + short);
el.scrollTop += moved;
break;
}
if (scrollsY(s)) s.scrollTop += moved;
}
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],
[key, positions, setSlack, trimSlack, updateJumpVisibility],
);
/** Back to the end of the stream; following resumes from there. */
const jumpToLatest = useCallback(() => {
@@ -454,7 +535,7 @@ export function Stream({
);
return (
<OpenFolds.Provider value={openFolds}>
<RevealFold.Provider value={revealFold}>
<KeepFoldHeader.Provider value={keepFoldHeader}>
<div className={styles.streamArea}>
{finding && <FindBar streamRef={ref} focus={findFocus} onClose={onCloseFind} />}
<div
@@ -462,12 +543,6 @@ export function Stream({
// The conversation is read and copied like a document; focusable so ⌘F reaches it.
className={clsx(styles.stream, selectableText)}
tabIndex={-1}
onWheel={(e) => {
if (e.defaultPrevented) return;
markUserScroll();
if (e.deltaY < 0 && !e.ctrlKey && !e.metaKey) stopFollowing(e.target);
else if (e.deltaY > 0 && !e.ctrlKey && !e.metaKey) scrollingUp.current = false;
}}
onTouchStart={(e) => {
touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null;
}}
@@ -497,6 +572,7 @@ export function Stream({
}}
onScroll={(e) => {
const el = e.currentTarget;
trimSlack();
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const laidOut =
el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
@@ -513,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);
@@ -560,33 +636,41 @@ 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>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
</div>
</RevealFold.Provider>
</KeepFoldHeader.Provider>
</OpenFolds.Provider>
);
}
+1 -35
Переглянути файл
@@ -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>
);
}
+151 -61
Переглянути файл
@@ -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]]]) });
@@ -772,30 +828,26 @@ describe("scrolling", () => {
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
});
it.each([
{
name: "stays at the end below it",
top: 300,
bottom: 360,
scrolled: 60,
away: false,
},
{
name: "keeps its header on screen",
top: 50,
bottom: 900,
scrolled: 50,
away: true,
},
{
name: "back at the end without following",
top: 300,
bottom: 360,
scrolled: 60,
away: false,
released: true,
},
])("scrolls a section opened at the end into view: $name", async ({ top, bottom, scrolled, away, released }) => {
/** A stream whose height follows its fold and whose offset is clamped like a browser's. */
const foldingStream = (openHeight: number) => {
const el = stream();
const fold = el.querySelector("details")!;
const slack = () => parseFloat(el.style.getPropertyValue("--stream-slack")) || 0;
const height = () => (fold.children.length > 1 ? 1000 + openHeight : 1000) + slack();
let top = 0;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
Object.defineProperty(el, "scrollTop", {
configurable: true,
get: () => Math.max(0, Math.min(top, height() - 400)),
set: (v: number) => {
top = Math.max(0, Math.min(v, height() - 400));
},
});
return { el, fold, summary: fold.querySelector("summary")!, slack };
};
it("keeps the header of a section opened at the end in place and stops following", async () => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
@@ -803,43 +855,79 @@ describe("scrolling", () => {
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
Object.defineProperty(el, "scrollHeight", {
configurable: true,
value: 1000,
});
Object.defineProperty(el, "clientHeight", {
configurable: true,
value: 400,
});
el.getBoundingClientRect = () => ({ top: 0, bottom: 400 }) as DOMRect;
const { el, summary } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 900 - el.scrollTop }) as DOMRect;
el.scrollTop = 600;
fireEvent.scroll(el);
if (released) {
fireEvent.wheel(el, { deltaY: -50 });
el.scrollTop = 550;
fireEvent.scroll(el);
el.scrollTop = 600;
fireEvent.scroll(el);
expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
}
const fold = stream().querySelector("details")!;
fold.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;
// It grows once its content renders.
Object.defineProperty(el, "scrollHeight", {
configurable: true,
get: () => (fold.children.length > 1 ? 1000 + bottom - top : 1000),
});
fireEvent.pointerDown(fold);
fireEvent.pointerUp(fold);
fold.open = true;
act(() => {
fireEvent(fold, new Event("toggle"));
});
expect(el.scrollTop).toBe(600 + scrolled);
fireEvent.click(summary);
expect(el.scrollTop).toBe(600);
expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
act(() =>
useAgents.setState({
entries: new Map([["A", [...backend.entries.get("A")!, { type: "agent", text: "More" }]]]),
}),
);
expect(el.scrollTop).toBe(600);
});
it("keeps the header of a section closed at the end in place", async () => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const { el, fold, summary, slack } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 1200 - el.scrollTop }) as DOMRect;
fireEvent.click(summary);
expect(fold.open).toBe(true);
el.scrollTop = 1100;
fireEvent.scroll(el);
// With the end out of view, the next chunk doesn't pull the reader away from the section.
expect(screen.queryByRole("button", { name: "Jump to Latest" }) !== null).toBe(away);
// Closing it would pull the end up to 600: room below keeps the header at 100.
fireEvent.click(summary);
expect(fold.open).toBe(false);
expect(el.scrollTop).toBe(1100);
expect(slack()).toBe(500);
// Scrolling up takes the room back without moving the content.
el.scrollTop = 1000;
fireEvent.scroll(el);
expect(slack()).toBe(400);
expect(el.scrollTop).toBe(1000); // Opened again, the section fills that room first: nothing moves and no blank is left below.
fireEvent.click(summary);
expect(fold.open).toBe(true);
expect(slack()).toBe(0);
expect(el.scrollTop).toBe(1000);
});
it("scrolls the innermost container under the wheel and never hands it to the conversation", () => {
const transcript: AgentEntry[] = [tool("live", { status: "running", output: "Tool output" })];
useAgents.setState({ entries: new Map([["A", transcript]]) });
render(<SessionEditor input={input("A")} />);
const el = stream();
Object.defineProperty(el, "scrollHeight", { configurable: true, value: 1000 });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.scrollTop = 600;
fireEvent.scroll(el);
const output = screen.getByText("Tool output");
output.style.overflowY = "auto";
Object.defineProperty(output, "scrollHeight", { configurable: true, value: 300 });
Object.defineProperty(output, "clientHeight", { configurable: true, value: 100 });
let now = 0;
vi.spyOn(performance, "now").mockImplementation(() => now);
// At its top, scrolling up over it stays with it.
output.scrollTop = 0;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(false);
now = 1000;
output.scrollTop = 100;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true);
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
// A gesture that started in the conversation stays there when the output slides under it.
now = 2000;
expect(fireEvent.wheel(el, { deltaY: -4 })).toBe(true);
now = 2050;
output.scrollTop = 0;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true);
});
it("keeps following when the view grows taller and the browser pulls the offset back", () => {
@@ -989,6 +1077,8 @@ describe("scrolling", () => {
value: 400,
});
output.style.overflowY = "auto";
Object.defineProperty(output, "scrollHeight", { configurable: true, value: 300 });
Object.defineProperty(output, "clientHeight", { configurable: true, value: 100 });
output.scrollTop = 100;
el.scrollTop = 600;
fireEvent.scroll(el);
@@ -2529,7 +2619,7 @@ describe("import sessions dialog", () => {
backend.external = sessions;
open();
await listed("Login fix");
expect(screen.getByRole("dialog", { name: "Import Sessions from Other Apps" })).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "Import Sessions" })).toBeInTheDocument();
});
it("imports the selected session and opens it", async () => {
@@ -3046,7 +3136,7 @@ describe("last turn changes", () => {
const pane = await screen.findByRole("complementary", { name: "Changes" });
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Last Turn" }));
fireEvent.click(within(pane).getByRole("tab", { name: "Last Turn" }));
await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull());
expect(within(pane).getByText("b.ts")).toBeInTheDocument();
expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument();
@@ -3059,7 +3149,7 @@ describe("last turn changes", () => {
backend.turnChanges = [];
fireEvent.click(within(pane).getByRole("button", { name: "Refresh" }));
expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Whole Task" }));
fireEvent.click(within(pane).getByRole("tab", { name: "Whole Task" }));
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
});
});
+6 -7
Переглянути файл
@@ -2,24 +2,23 @@ import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
title: "Agent Setup",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
keywords: ["agent", "acp", "registry", "install", "update", "Coding Agents"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
title: "MCP Connections",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
@@ -32,10 +31,10 @@ export function activateSettingsPages(): () => void {
},
{
id: POLICY_PAGE,
title: "Command Permissions",
title: "Command Rules",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "Command Permissions", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
+1 -1
Переглянути файл
@@ -136,7 +136,7 @@ interface AgentsState {
external: ExternalSession[];
/** Why the external sessions could not be listed. */
externalError: string | null;
/** The Import Sessions from Other Apps dialog is open. */
/** The Import Sessions dialog is open. */
importOpen: boolean;
/** External sessions being imported (`provider:sessionId`), so none is imported twice. */
importing: ReadonlySet<string>;
+13 -6
Переглянути файл
@@ -1,6 +1,6 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { t, tx } from "@/platform/i18n";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
@@ -165,7 +165,7 @@ function arrangeMenu(tasks: AgentTask[], ids: string[]): MenuItem[] {
{
kind: "item",
id: "move-to-group",
label: "Move to Group",
label: "Group",
icon: "folder",
submenu: groupSubmenu(
ids,
@@ -194,7 +194,7 @@ function groupSubmenu(ids: string[], groups: OrganizeGroup[], current: Array<str
{
kind: "item",
id: "group:none",
label: "Remove from Group",
label: "No Group",
run: () => moveTasksToGroup(ids, null),
},
] satisfies MenuItem[])
@@ -213,11 +213,11 @@ export function groupMenu(group: OrganizeGroup): MenuItem[] {
export const taskActions: Action[] = [
{
id: "agents.importSessions",
title: "Import Sessions from Other Apps…",
title: "Import Sessions…",
category: "Agents",
icon: "download",
when: "projectOpen",
keywords: ["import", "claude", "codex", "history", "transcript"],
keywords: ["import", "other apps", "claude", "codex", "history", "transcript"],
run: showImportSessions,
},
{
@@ -398,7 +398,14 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
...(!auxiliaryWindow()
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
? ([
{
kind: "action",
action: "agents.moveToNewWindow",
label: t("app.window.askNew"),
arg: task.id,
},
] satisfies MenuItem[])
: []),
...(hasTaskTerminal(task, projectRoot)
? ([
+1 -1
Переглянути файл
@@ -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;
+26
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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 });
+44 -13
Переглянути файл
@@ -31,9 +31,6 @@
.bold {
font-weight: 600;
}
.flex {
flex: 1;
}
.ellipsis {
min-width: 0;
overflow: hidden;
@@ -440,29 +437,49 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
width: var(--submit-width);
min-width: 320px;
height: var(--submit-height);
min-height: 160px;
padding: 12px;
overflow: hidden;
resize: both;
width: 500px;
max-width: calc(100vw - 12px);
height: 200px;
max-height: calc(100vh - 12px);
padding: var(--space-3);
overflow: auto;
}
.submitHeader {
display: flex;
flex: none;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-1);
}
.submitHeading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
align-self: center;
gap: var(--space-0-5) var(--space-2);
min-width: 0;
overflow-wrap: anywhere;
}
.submitCount {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.submitHeaderActions {
display: flex;
flex: none;
align-items: center;
gap: 5px;
gap: var(--space-1);
}
.submitEditor {
flex: 1;
min-height: 40px;
padding: 4px 6px;
padding: var(--space-1) var(--space-2);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--bg-input);
color: var(--fg);
font: inherit;
line-height: var(--lh-code);
resize: none;
outline: none;
}
@@ -470,12 +487,26 @@
border-color: var(--focus-ring);
}
.submitError {
flex: none;
flex: 0 1 auto;
min-height: 0;
max-height: 35%;
overflow: auto;
overflow-wrap: anywhere;
color: var(--danger);
}
.submitButtons {
display: flex;
flex: none;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
}
.submitButtons > button {
max-width: 100%;
height: auto;
min-height: var(--h-button);
padding-block: var(--space-1);
line-height: 1.2;
white-space: normal;
overflow-wrap: anywhere;
}
+40 -28
Переглянути файл
@@ -5,9 +5,11 @@
* Request Changes (not for the author) and Comment. Shown above the button that opened
* it, or centred in the window. 500×200, resizable.
*/
import { useEffect, useState, type CSSProperties } from "react";
import { useEffect, useState } from "react";
import { Button, IconButton, Popup, Spinner, T } from "@/ui";
import { resolveMonoFont } from "@/platform/fonts";
import { useTx, tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { ask } from "@/workbench/messages";
import { errorMessage } from "../api/client";
import type { GHPullRequestReviewEvent } from "../api/types";
@@ -25,26 +27,25 @@ export function showSubmitReview(number: number, anchor?: Element | null): Promi
// The details and the pending review are needed for the buttons and the header.
void loadPullRequestData(number, "details").catch(() => undefined);
void loadPullRequestData(number, "pendingReview").catch(() => undefined);
const at = anchor?.isConnected
? anchor
: { x: Math.round(window.innerWidth / 2) - 250, y: Math.round(window.innerHeight / 3) };
return openDialog<true>((done) => (
<SubmitReview number={number} draftKey={draftKey} anchor={at} onClose={() => done(null)} />
<SubmitReview
number={number}
draftKey={draftKey}
anchor={anchor?.isConnected ? anchor : "center"}
onClose={() => done(null)}
/>
));
}
function SubmitReview(props: {
number: number;
draftKey: string;
anchor: Element | { x: number; y: number };
onClose: () => void;
}) {
const { number, draftKey, onClose } = props;
function SubmitReview(props: { number: number; draftKey: string; anchor: Element | "center"; onClose: () => void }) {
const { number, draftKey, anchor, onClose } = props;
const t = useTx();
const details = usePullRequestData(number, "details").value;
const pending = usePullRequestData(number, "pendingReview").value;
const text = useReviewText((s) => s.text[draftKey] ?? "");
const activeDraftKey = useGhRepository((s) => reviewDraftKey(s.connection, number));
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -94,12 +95,11 @@ function SubmitReview(props: {
setBusy(false);
}
};
const anchored = "getBoundingClientRect" in props.anchor;
return (
<Popup
open
anchor={props.anchor}
placement={anchored ? "top-start" : "bottom-start"}
anchor={anchor}
placement="top-start"
onClose={(reason) => {
// A click outside does not drop a review while it is being sent.
if (reason !== "outside" || !busy) onClose();
@@ -107,26 +107,38 @@ function SubmitReview(props: {
role="dialog"
aria-label={t("Submit Review")}
className={styles.submitPopup}
style={{ "--submit-width": "500px", "--submit-height": "200px" } as CSSProperties}
resizable="both"
minWidth={260}
minHeight={160}
>
<div className={styles.submitHeader}>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span>{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}</span>
)}
<span className={styles.flex} />
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
<div className={styles.submitHeading}>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span className={styles.submitCount}>
{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}
</span>
)}
</div>
<div className={styles.submitHeaderActions}>
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
</div>
<textarea
data-autofocus
className={styles.submitEditor}
placeholder={t("Review comment")}
aria-label={t("Review comment")}
style={{
fontFamily: family,
fontSize: size,
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={text}
onChange={(e) => {
setError(null);
@@ -134,7 +146,7 @@ function SubmitReview(props: {
}}
/>
{error && (
<div className={styles.submitError}>
<div className={styles.submitError} role="alert">
<T>Failed to submit review</T>
<div className={styles.secondary}>{error}</div>
</div>
+36
Переглянути файл
@@ -222,6 +222,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[] = [];
+8
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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
Переглянути файл
@@ -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 };
+20 -4
Переглянути файл
@@ -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
Переглянути файл
@@ -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) */
+8
Переглянути файл
@@ -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
Переглянути файл
@@ -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"],
+291
Переглянути файл
@@ -0,0 +1,291 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import type { Terminal } from "@xterm/xterm";
import { installImeAnchor } from "./imeAnchor";
/** jsdom has no layout: the pieces the anchor reads report their own boxes. */
function rect(left: number, top: number, width = 8, height = 18): DOMRect {
return {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
x: left,
y: top,
toJSON: () => ({}),
} as DOMRect;
}
interface Fake {
host: HTMLElement;
textarea: HTMLTextAreaElement;
term: Terminal;
/** Runs every listener xterm's render and cursor-move events would fire. */
tick(): void;
/** Moves the terminal cursor, as the program's next frame would. */
cursor(x: number, y: number): void;
}
function fake({
cursorX = 0,
cursorY = 0,
cols = 80,
rows = 20,
showCursor = false,
viewportY = 0,
baseY = 0,
} = {}): Fake {
const host = document.createElement("div");
const screen = document.createElement("div");
screen.className = "xterm-screen";
// 80 columns × 20 rows of 8 × 18 px cells.
screen.getBoundingClientRect = () => rect(40, 40, 640, 360);
const rowList = document.createElement("div");
rowList.className = "xterm-rows";
screen.append(rowList);
const textarea = document.createElement("textarea");
textarea.className = "xterm-helper-textarea";
textarea.style.width = "8px";
textarea.style.height = "18px";
host.append(screen, textarea);
const listeners: (() => void)[] = [];
const active = { cursorX, cursorY, viewportY, baseY };
const term = {
textarea,
cols,
rows,
buffer: { active },
modes: { showCursor },
onRender: (fn: () => void) => {
listeners.push(fn);
return { dispose: () => listeners.splice(listeners.indexOf(fn), 1) };
},
onCursorMove: (fn: () => void) => {
listeners.push(fn);
return { dispose: () => listeners.splice(listeners.indexOf(fn), 1) };
},
} as unknown as Terminal;
return {
host,
textarea,
term,
tick: () => listeners.forEach((fn) => fn()),
cursor: (x: number, y: number) => {
active.cursorX = x;
active.cursorY = y;
},
};
}
/** A reverse-video cell at `left`/`top`, on `row` of the rendered grid. */
function addCaret(f: Fake, left: number, top: number, row = 0) {
const rowList = f.host.querySelector(".xterm-rows")!;
while (rowList.children.length <= row) rowList.append(document.createElement("div"));
const span = document.createElement("span");
span.className = "xterm-bg-257";
span.textContent = " ";
span.getBoundingClientRect = () => rect(left, top);
rowList.children[row]!.append(span);
}
/** Lets the `style` observer run, which is a microtask. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
describe("installImeAnchor", () => {
it("puts the IME anchor on the caret a program drew for itself", () => {
const f = fake({ cursorX: 79, cursorY: 3 });
// The caret cell sits 60px right of and 50px below the screen's origin.
addCaret(f, 100, 90, 3);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("keeps the anchor inside the terminal, where the input method reads the caret", () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
// A position outside the screen's box makes Windows put the candidate window in a corner.
const left = Number.parseFloat(f.textarea.style.left);
const top = Number.parseFloat(f.textarea.style.top);
expect(left).toBeGreaterThanOrEqual(0);
expect(top).toBeGreaterThanOrEqual(0);
expect(left).toBeLessThan(640);
expect(top).toBeLessThan(360);
});
it("leaves xterm's own anchor alone while the cursor is inside the screen", () => {
const f = fake({ cursorX: 12 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
expect(f.textarea.style.top).toBe("");
});
it.each([
["the terminal cursor is visible", { showCursor: true }],
["the terminal is showing scrollback", { baseY: 30, viewportY: 15 }],
] as const)("ignores reverse video when %s", (_scenario, options) => {
const f = fake({ cursorX: 79, ...options });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
expect(f.textarea.style.top).toBe("");
});
it("ignores xterm's own cursor cell and takes the program's caret", () => {
const f = fake({ cursorX: 79 });
// The terminal cursor's own cell: column 79 (screen origin 40,40; 8x18 cells).
addCaret(f, 40 + 79 * 8, 40);
// The caret the program drew.
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
});
it("still anchors when xterm clamps the cursor a cell or two short of the edge", () => {
// Measured in pi: the clamped cursor ends up at cols-2 (and one past the row), never always
// at the last cell.
for (const cursorX of [78, 79, 80]) {
const f = fake({ cursorX });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
}
});
it("prefers the caret on the terminal cursor's row", () => {
const f = fake({ cursorX: 79, cursorY: 5 });
addCaret(f, 300, 40, 0); // some other reverse-video cell, e.g. a highlighted row
addCaret(f, 100, 150, 5);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("110px");
});
it("takes a single caret from another row when the program's cursor drifted", () => {
// pi scrolls its input box but keeps asking for the last column of the row its hardware cursor
// landed on, three rows below the caret: the only reverse-video cell is still the caret.
const f = fake({ cursorX: 79, cursorY: 27 });
addCaret(f, 100, 90, 24);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("gives up when the cells elsewhere are not the cursor and there is more than one", () => {
const f = fake({ cursorX: 79, cursorY: 5 });
addCaret(f, 100, 40, 0);
addCaret(f, 300, 40, 1);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
});
it("leaves xterm's own anchor alone when two cells are not the cursor", () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
addCaret(f, 300, 90); // a selection or a highlighted row, not a caret
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
});
it("puts the anchor back when xterm re-places it on the cursor", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
// What xterm's composition helper writes on `compositionstart` and every update.
f.textarea.style.left = "616.8px";
f.textarea.style.top = "0px";
await settle();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("keeps the caret offset through a frame that misses it", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
// The program redraws without its caret for a moment: the composition opening now must not
// fall back to the far end of the row.
f.host.querySelector(".xterm-rows")!.replaceChildren();
f.tick();
await settle();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("hands the position back to xterm when the cursor leaves the last column", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
// A program that puts its hardware cursor on the caret needs no anchor at all.
f.cursor(12, 0);
f.tick();
await settle();
expect(f.textarea.style.left).toBe("96px");
expect(f.textarea.style.top).toBe("0px");
});
it("moves the composition view too, and stops once disposed", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
const view = document.createElement("div");
view.className = "composition-view";
f.host.querySelector(".xterm-screen")!.append(view);
const dispose = installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(view.style.left).toBe("60px");
expect(view.hasAttribute("data-openidea-ime-anchor")).toBe(true);
dispose();
expect(view.style.left).toBe("632px");
expect(view.hasAttribute("data-openidea-ime-anchor")).toBe(false);
// xterm owns the position again: nothing moves it away any more.
f.textarea.style.left = "640px";
await settle();
expect(f.textarea.style.left).toBe("640px");
});
});
+195
Переглянути файл
@@ -0,0 +1,195 @@
/**
* Points the IME at the caret a full-screen program draws itself.
*
* xterm anchors the IME candidate window on its hidden helper textarea, which it keeps on the
* terminal cursor: on every render, on `compositionstart`, and again on each `compositionupdate`.
* A TUI that paints its own cursor hides the terminal's and leaves it wherever the frame's last
* write ended — pi asks for a column past the right edge of its input box (`ESC[21;411H` in a
* 206-column terminal, which xterm clamps to the last column) while it draws the caret itself at
* column 5. The candidate window then opens at the far right of the input box, and every
* composition started there keeps it there, because xterm re-places the textarea as the input
* method opens.
*
* Nothing in the protocol reports where such a caret is, but the program draws it: a caret painted
* with reverse video is an inverted cell, which xterm marks `xterm-bg-257`. While the hidden cursor
* sits at the right edge (`EDGE_COLUMNS`) in the live viewport and one such cell stands out, that
* cell is taken as the caret: one on the cursor's row wins, and a single one anywhere keeps working
* when the program's own row tracking drifts. Anything else is a selection or a highlighted row.
*
* The textarea is moved with `left`/`top`, i.e. inside the terminal's box: Chromium reports that
* rectangle to the input method, and a rectangle outside the window makes Windows open the
* candidate window in the window's corner. xterm rewrites those properties from the cursor on its
* own schedule, so the position is restored after every render, cursor move and composition event,
* and again from a `style` observer, which lands in the microtask right after xterm's write.
*/
import type { Terminal } from "@xterm/xterm";
/** xterm's class for a cell drawn in `INVERTED_DEFAULT_COLOR` (reverse video). */
const INVERTED = "xterm-bg-257";
/**
* How close to the right edge the terminal cursor has to be for the anchor to apply.
*
* Such a program asks for a column past the edge, and xterm clamps that to the last cell — but the
* cursor it ends up with is not always the last cell: a wrapped pending cell (`cursorX` one past
* the row) and requests clamped a cell or two short both showed up while typing in pi, and every
* one of them has to count as "the program cannot place its own cursor".
*/
const EDGE_COLUMNS = 3;
export interface ImeAnchorOptions {
/** The xterm host inside the pane, where `.xterm-screen` lives. */
host: HTMLElement;
term: Terminal;
}
/** One cell of the grid, in CSS pixels. */
interface Cell {
width: number;
height: number;
}
/** Where the helper textarea belongs, in the screen's own coordinates. */
interface Spot {
left: number;
top: number;
}
/**
* The cell a program drew its caret in.
*
* Every inverted cell is a candidate — xterm draws the terminal's own cursor cell inverted too —
* so the one sitting on the terminal cursor is dropped. The caret cell is normally on the cursor's
* row, which is where a hardware cursor request clamped by column leaves it, but that row can drift:
* pi ends up a few rows below its input box once the viewport scrolls. So a single candidate on the
* cursor's row wins, a single candidate anywhere on screen is taken as well, and anything else is a
* selection or a highlighted row, not a caret.
*/
function ownCaret(term: Terminal, host: HTMLElement, cell: Cell): Spot | undefined {
const screen = host.querySelector<HTMLElement>(".xterm-screen");
if (!screen || cell.width <= 0 || cell.height <= 0) return undefined;
const cursor = term.buffer.active;
const screenRect = screen.getBoundingClientRect();
const cursorCol = Math.min(cursor.cursorX, term.cols - 1);
const candidates: { rect: DOMRect; row: number }[] = [];
for (const [row, element] of [...host.querySelectorAll<HTMLElement>(".xterm-rows > div")].entries()) {
for (const span of element.children) {
if (!span.classList.contains(INVERTED)) continue;
const rect = span.getBoundingClientRect();
// The terminal's own cursor: xterm renders its cell inverted as well.
if (row === cursor.cursorY && Math.round((rect.left - screenRect.left) / cell.width) === cursorCol) continue;
if (rect.width > screenRect.width / 2) continue;
candidates.push({ rect, row });
}
}
const onCursorRow = candidates.filter((c) => c.row === cursor.cursorY);
const found = onCursorRow.length === 1 ? onCursorRow[0] : candidates.length === 1 ? candidates[0] : undefined;
if (!found) return undefined;
return { left: found.rect.left - screenRect.left, top: found.rect.top - screenRect.top };
}
/**
* Keeps the IME anchor on the caret such a program draws. Returns a disposer.
*
* Runs after every render rather than on `compositionstart` alone: an input method asks the
* focused element for its caret rectangle as it opens, and a reposition made from that event races
* xterm's own handling of the same event, which puts the textarea back on the terminal cursor.
*/
export function installImeAnchor({ host, term }: ImeAnchorOptions): () => void {
const textarea = term.textarea;
if (!textarea) return () => {};
const preedit = host.querySelector<HTMLElement>(".composition-view");
const elements = preedit ? [textarea, preedit] : [textarea];
/** The caret cell, or `null` while xterm's own placement is the right one. */
let target: Spot | null = null;
/** Whether the anchor currently holds a position of ours that xterm would undo. */
let moved = false;
/**
* The last caret seen, as an offset from the terminal cursor's cell. A frame can miss it — the
* program may be mid-redraw, or two cells of its caret may be on screen for a moment — and the
* composition that opens in such a frame must not fall back to the far end of the row.
*/
let caretFromCursor: Spot | null = null;
const write = (spot: Spot | undefined) => {
if (!spot) return;
const left = `${spot.left}px`;
const top = `${spot.top}px`;
for (const { style } of elements) {
if (style.left !== left) style.left = left;
if (style.top !== top) style.top = top;
}
};
/** What xterm itself writes: the cursor cell, clamped to the last column. */
const cursorSpot = (): Spot | undefined => {
const cols = term.cols;
const screen = host.querySelector<HTMLElement>(".xterm-screen");
if (!screen || cols <= 0) return undefined;
const screenRect = screen.getBoundingClientRect();
const cell = { width: screenRect.width / cols, height: term.rows > 0 ? screenRect.height / term.rows : 0 };
if (cell.width <= 0 || cell.height <= 0) return undefined;
const cursor = term.buffer.active;
return { left: Math.min(cursor.cursorX, cols - 1) * cell.width, top: cursor.cursorY * cell.height };
};
const place = () => {
const cols = term.cols;
const screen = host.querySelector<HTMLElement>(".xterm-screen");
const buffer = term.buffer.active;
target = null;
const cursor = cursorSpot();
if (
screen &&
cursor &&
!term.modes.showCursor &&
buffer.viewportY === buffer.baseY &&
buffer.cursorX >= cols - EDGE_COLUMNS
) {
const screenRect = screen.getBoundingClientRect();
const cell = { width: screenRect.width / cols, height: term.rows > 0 ? screenRect.height / term.rows : 0 };
const anchor = ownCaret(term, host, cell);
if (anchor) caretFromCursor = { left: anchor.left - cursor.left, top: anchor.top - cursor.top };
target =
anchor ??
(caretFromCursor && { left: cursor.left + caretFromCursor.left, top: cursor.top + caretFromCursor.top });
} else {
caretFromCursor = null;
}
if (target) {
if (!moved) preedit?.setAttribute("data-openidea-ime-anchor", "");
moved = true;
write(target);
} else if (moved) {
// The drawn caret is gone: hand the position back to xterm.
moved = false;
preedit?.removeAttribute("data-openidea-ime-anchor");
write(cursorSpot());
}
};
// Registered after `open()`, so these run after xterm's own render and cursor handlers have
// put the textarea back on the terminal cursor.
const render = term.onRender(() => place());
const cursorMove = term.onCursorMove(() => place());
// xterm re-places the textarea as the input method opens and on every update; the observer lands
// in the microtask after that write, before the browser asks for the caret rectangle.
const observer = new MutationObserver(() => {
if (target) write(target);
});
for (const element of elements) observer.observe(element, { attributes: true, attributeFilter: ["style"] });
return () => {
render.dispose();
cursorMove.dispose();
observer.disconnect();
target = null;
if (moved) {
moved = false;
preedit?.removeAttribute("data-openidea-ime-anchor");
write(cursorSpot());
}
};
}
+2
Переглянути файл
@@ -24,6 +24,7 @@ import { installSelectionHighlights, type SelectionHighlightController } from ".
import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights";
import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard } from "./paste";
import { ImeCommitGate } from "./imeCommit";
import { installImeAnchor } from "./imeAnchor";
import { ownTerminalInput } from "./imeInput";
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
import { parseShellCommand } from "@/platform/commandLine";
@@ -681,6 +682,7 @@ export class TerminalSession {
this.opts.onFocus(this.key);
});
this.watchImeCommit();
this.disposables.push({ dispose: installImeAnchor({ host: this.host, term: this.term }) });
if (this.pendingFocus) {
this.pendingFocus = false;
if (this.focusStayedHere()) this.focus();
+10 -2
Переглянути файл
@@ -412,11 +412,12 @@ describe("terminalFont", () => {
it("prefers the terminal's fallback over the editor's", () => {
const font = terminalFont(
{ ...t, fallbackFontFamily: "Sarasa Mono SC" },
{ ...editor, fallbackFont: "PingFang SC" },
{ ...editor, fallbackFont: "Source Code Pro" },
BASE,
);
expect(font.family).toContain('"Sarasa Mono SC"');
expect(font.family).not.toContain("PingFang SC");
// The CJK faces are always named (see the test below), so the editor's pick must not be one.
expect(font.family).not.toContain("Source Code Pro");
});
it("follows the editor's Typography Settings weights with Use editor font", () => {
@@ -446,6 +447,13 @@ describe("terminalFont", () => {
expect(terminalFont({ ...t, useEditorFont: false }, editor, BASE).letterSpacing).toBe(0);
expect(terminalFont({ ...t, useEditorFont: false, columnWidth: 1.5 }, editor, BASE).letterSpacing).toBe(3);
});
it("names CJK faces after the icon fonts so a wide character keeps two cells", () => {
const { family } = terminalFont(t, editor, BASE);
// After the icon fonts: they must win their own glyphs, and only CJK falls through to these.
expect(family.indexOf('"Microsoft YaHei"')).toBeGreaterThan(family.indexOf('"Symbols Nerd Font"'));
expect(family).toContain('"PingFang SC", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC"');
expect(family.endsWith(', "Source Han Sans SC", monospace')).toBe(true);
});
});
describe("terminal tab titles", () => {
+15 -3
Переглянути файл
@@ -6,7 +6,14 @@
*/
import type { ITheme, Terminal } from "@xterm/xterm";
import { fontWeightOf } from "@/platform/editorSettings";
import { fontsLoaded, monoStack, nerdFontFaces, resolveMonoFont } from "@/platform/fonts";
import {
CJK_FALLBACK_FACES,
fontsLoaded,
monoStack,
nerdFontFaces,
quoteFontFamily,
resolveMonoFont,
} from "@/platform/fonts";
import { computedTokenColor, parseColor, type Rgba } from "@/platform/cssColor";
export { parseColor, type Rgba };
@@ -178,9 +185,14 @@ export interface TerminalFont {
boldWeight: number;
}
/** Nerd Fonts before the generic family, so per-glyph fallback finds prompt icons. */
/**
* Nerd Fonts before the generic family, so per-glyph fallback finds prompt icons, then the CJK
* faces: a wide character xterm only finds through the webview's own fallback measures one way and
* draws another (see `CJK_FALLBACK_FACES`), which drifts any row that mixes CJK with a background.
*/
function withNerdFonts(family: string): string {
return `${family.replace(/,\s*monospace\s*$/i, "")}, ${nerdFontFaces().join(", ")}, monospace`;
const cjk = CJK_FALLBACK_FACES.map(quoteFontFamily).join(", ");
return `${family.replace(/,\s*monospace\s*$/i, "")}, ${nerdFontFaces().join(", ")}, ${cjk}, monospace`;
}
/**
+9
Переглянути файл
@@ -17,6 +17,15 @@
overflow: clip;
}
/* During a composition xterm clips its composition view to the space between the cursor and the
right edge, and sizes the helper textarea from that view. A program that leaves the cursor in the
last column therefore leaves one cell of room, and the pre-edit text is painted almost invisibly.
The view is drawn on the caret instead (imeAnchor), so the width that matters is the space from
that caret to the edge — which `.xterm` clips anyway. */
.xterm .composition-view[data-openidea-ime-anchor] {
max-width: none !important;
}
/* An icon or fallback symbol wider than its cell stays over the next cell's background
(domRowCache), while selected spans keep xterm's `.xterm-decoration-top` z-index (2). */
.xterm .xterm-rows .openidea-terminal-icon:not(.xterm-decoration-top) {
+19 -10
Переглянути файл
@@ -270,22 +270,31 @@
min-width: 0;
display: flex;
align-items: center;
gap: var(--space-2);
}
/* The message identifies a stash: the branch gives way first, the time stays whole. */
.stashRow > .detail {
white-space: nowrap;
}
.stashRow > .stashTime {
flex: none;
gap: var(--space-1-5);
}
.stashGroupName,
.stashTime,
.stashBranch,
.stashMessage {
flex: 1 1 auto;
min-width: 4em;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.stashMessage {
min-width: min(4em, 100%);
}
.stashGroupName {
font-weight: 600;
}
.stashTime {
flex-shrink: 10000;
color: var(--fg-secondary);
}
.stashBranch {
max-width: 30%;
margin-inline-start: auto;
}
@container stash-list (max-width: 320px) {
.stashBranch {
display: none;
+19
Переглянути файл
@@ -307,6 +307,25 @@
color: var(--fg-strong);
background: var(--bg-hover);
}
.host :global(.cm-diffNumbers) {
position: relative;
text-align: end;
font-variant-numeric: tabular-nums;
}
.host :global(.cm-diffNumbers .cm-gutterElement),
.host :global(.cm-diffWidgetNumber) {
min-inline-size: calc(var(--space-4) + var(--space-2));
padding-inline: var(--space-1) var(--space-2);
}
.host :global(.cm-diffWidgetNumbers) {
position: absolute;
inset: 0;
pointer-events: none;
}
.host :global(.cm-diffWidgetNumber) {
position: absolute;
inset-inline: 0;
}
.noHighlight :global(.cm-changedLine),
.noHighlight :global(.cm-insertedLine),
.noHighlight :global(.cm-changedText),
+3 -1
Переглянути файл
@@ -121,6 +121,7 @@ import { PaddedPanes, UnalignedPanes, type DiffPanes } from "./diffScroll";
import { groupOf } from "./changes";
import { commitLineTarget, EXCLUDE_COMMIT_LINES, INCLUDE_COMMIT_LINES, inclusionGutter } from "./hunkInclusion";
import { unifiedCommitLines, unifiedCommitSelection } from "./unifiedCommitLines";
import { unifiedLineNumbers } from "./unifiedLineNumbers";
import { hunksOverlapping } from "./hunks";
import { requireDisplayedText, staleDiff, writeIndexChunk } from "./stagingDiffEdits";
import {
@@ -735,7 +736,7 @@ function TwoPaneDiff({
viewerBase({
readOnly: !editable,
findBar: true,
lineNumbers: viewMode === "split" && notes === "left" ? "after" : true,
lineNumbers: viewMode === "split" ? (notes === "left" ? "after" : true) : single,
}),
collapseUnchanged ? collapsedDiffLines() : [],
changedRanges,
@@ -924,6 +925,7 @@ function TwoPaneDiff({
includable ? unifiedCommitSelection : [],
highlightChanges ? diffWords : [],
unifiedOnLeft ? unifiedLeftDiff(highlightChanges) : [],
single ? [] : unifiedLineNumbers(unifiedOnLeft),
unifiedMergeView({
original: unifiedOnLeft ? textB : textA,
highlightChanges,
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more