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

...
Автор SHA1 Повідомлення Дата
l0ng-ai bbdf0052b2 fix(editor): offer to make a read-only file writable when editing it
A file with the read-only attribute set (often kept when copying files in
Explorer) opened read-only, and typing into it did nothing beyond the
banner. Typing, pasting or dropping into such a file now asks to make it
writable (the same question as Toggle Read-only Attribute) and clears the
attribute on confirm. Binary, too-large and library documents still refuse
edits without asking.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: zhzhsx <[email protected]>
2026-11-15 16:40:27 +08:00
l0ng-ai 0f91aac0d4 fix(completion): leave items their server inserts to the server (#3505)
kotlin-lsp items carry an empty text and a command that inserts them through a workspace edit. We added call parentheses to method items anyway (refreshName()(), an override's body followed by ()) and left the caret in front of the server's text. Items with an empty text get no parentheses, and the caret moves past the server's edit when it lands at the caret.
2026-11-15 16:38:37 +08:00
l0ng-ai d4b2ade24d fix(toolwindows): a window that loses its last tab takes its stripe button with it (#3504)
Hierarchy, Run and Debug hid when their last tab closed but kept their stripe button; Find and Find Usages stayed open and empty. Like IDEA (hide on empty content; Hierarchy unavailable without content), they now hide and drop their button until new content opens them again. Terminal keeps its button.
2026-11-15 16:35:49 +08:00
l0ng-ai e5f642f1d1 fix(agents): list only the files a local task changed while it worked (#3480)
A task in the project's own checkout listed every file changed since it started, the user's edits between turns and other tasks' work included, and rolled them back with it. Each turn snapshots the checkout's changed files as it starts and ends; files whose state moved are recorded (and persisted) as the task's, and its changes, grouped changes and rollback keep to them. Imported sessions start with none; worktree tasks and earlier saved tasks keep listing every change.
2026-11-15 11:43:13 +08:00
Deng Liuтаdengliu b8a06863d9 fix(terminal): lift overhanging fallback glyphs and prefer full-width Nerd Fonts (#3475)
Symbols that fall back to a wider font (U+23F2/U+23F1 via STIX Two Math on macOS, drawn with negative letter-spacing) and non-PUA Nerd Font symbols were clipped by the next cell's background: only Private Use Area icons were lifted. Spans measured wider than their cell are lifted too, the class survives link-hover redraws, the rule is shared with embedded terminals, and full-width Nerd Font faces come before their Mono variants in the fallback list.

Co-authored-by: dengliu <[email protected]>
2026-11-15 11:36:14 +08:00
GuoYuтаguoyucode b5d86b4532 feat(mcp): listing tools return a page, so agents can afford to call them (#3471)
Tools that list things (get_run_configurations, git_status, list_runs, get_project_problems, find_references, list_directory_tree, search_*) take limit/offset and report total (where cheap), more and nextOffset; list_runs filters by state, get_run_configurations by query, get_project_problems lists errors only by default. Detected run configurations no longer list the IDE's own environment. Searches stop offering a nextOffset past the 5000 results they can find.

Co-authored-by: guoyucode <[email protected]>
2026-11-15 11:32:01 +08:00
Akbar Husain d8814d18b0 perf(keymap): serve the effective binding table from cache (#3474)
The dispatcher rebuilt the merged, normalized binding table on every keystroke (~0.28 ms with the default keymap). It is now cached against the identity of the store's preset, overrides and extensions, which every writer replaces wholesale.

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 11:25:37 +08:00
l0ng-ai 7bd115bc97 fix(debugger): replace a finished Debug tab when a prepared start begins (#3478)
A start that builds first added its tab right away but dropped finished sessions only once the adapter started, so the previous run's terminated tab stayed beside the new one during the build. startPreparedSession now drops finished sessions before adding its tab.
2026-11-15 11:15:14 +08:00
114 змінених файлів з 3557 додано та 261 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -4232,6 +4232,7 @@ dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"png 0.18.1",
]
[[package]]
+65 -6
Переглянути файл
@@ -283,6 +283,11 @@ struct TaskFile {
/// The folder (in the task store) with copies of the `before` files, for rolling back.
#[serde(default, skip_serializing_if = "Option::is_none")]
saved: Option<String>,
/// In the project's own checkout, where the user and other tasks change files too: the
/// files that changed while one of this task's turns ran, the only ones its changes list.
/// `None` for a worktree task, and a task saved before these were recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
touched: Option<BTreeSet<String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subagents: Vec<SavedSubagent>,
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
@@ -293,6 +298,9 @@ struct TaskFile {
title_renamed: bool,
}
/// The changed files of a checkout, stamped.
type Snapshot = BTreeMap<String, worktree::Stamp>;
struct TaskState {
task: AgentTask,
session_id: Option<String>,
@@ -300,6 +308,8 @@ struct TaskState {
wanted: Vec<AgentConfigChoice>,
before: Arc<BTreeMap<String, worktree::Stamp>>,
saved: Option<String>,
/// See `TaskFile::touched`.
touched: Option<Arc<BTreeSet<String>>>,
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
@@ -673,6 +683,7 @@ impl AgentManager {
wanted: Vec::new(),
before: BTreeMap::new(),
saved: None,
touched: Some(BTreeSet::new()),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
@@ -763,6 +774,7 @@ impl AgentManager {
wanted: req.config,
before,
saved,
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
@@ -864,6 +876,7 @@ impl AgentManager {
wanted: req.config,
before,
saved: None,
touched: None,
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
@@ -1096,6 +1109,7 @@ impl AgentManager {
wanted: s.wanted.clone(),
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
subagents: s.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
@@ -1387,8 +1401,8 @@ impl AgentManager {
pub async fn changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
let task = self.task(id)?;
let at = task.base();
let before = task.state.lock().before.clone();
blocking(move || at.changes(&before)).await
let (before, touched) = task.attribution();
blocking(move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
}
/// The task's uncommitted changes and, for a worktree task, the commits made since it
@@ -1396,8 +1410,13 @@ impl AgentManager {
pub async fn grouped_changes(&self, id: &str) -> IdeResult<AgentChanges> {
let task = self.task(id)?;
let at = task.base();
let before = task.state.lock().before.clone();
blocking(move || at.grouped_changes(&before)).await
let (before, touched) = task.attribution();
blocking(move || {
let mut grouped = at.grouped_changes(&before)?;
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
Ok(grouped)
})
.await
}
/// Content of `path` (in the task's directory) when the task started.
@@ -1423,15 +1442,16 @@ impl AgentManager {
return Err(IdeError::invalid("the agent is working: stop it before rolling back its changes"));
}
let at = task.base();
let (before, saved) = {
let (before, saved, touched) = {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
};
let restamped = blocking(move || {
let (changes, rev) = match view {
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
AgentChangesView::SinceStart => (at.changes(&before)?, at.rev()?),
};
let changes = worktree::made_by_task(changes, touched.as_deref());
let sources = match rev.as_deref() {
Some(rev) => worktree::rename_sources(at.cwd(), rev)?,
None => Default::default(),
@@ -1522,6 +1542,7 @@ impl Task {
wanted: file.wanted,
before: Arc::new(file.before),
saved: file.saved,
touched: file.touched.map(Arc::new),
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
@@ -1548,6 +1569,41 @@ impl Task {
})
}
/// The files already changed when the task started, and the files its turns changed.
fn attribution(&self) -> (Arc<Snapshot>, Option<Arc<BTreeSet<String>>>) {
let s = self.state.lock();
(s.before.clone(), s.touched.clone())
}
/// The changed files of the checkout as a turn starts, when the task records what its turns change.
async fn checkout_before_turn(&self) -> Option<Snapshot> {
let cwd = {
let s = self.state.lock();
s.touched.as_ref()?;
s.task.cwd.0.clone()
};
blocking(move || worktree::snapshot(&cwd)).await.ok()
}
/// Records the files that changed in the checkout since `start`, as the turn ends, as the task's.
async fn record_turn_changes(&self, start: Option<Snapshot>) {
let Some(start) = start else { return };
let cwd = self.state.lock().task.cwd.0.clone();
let Ok(end) = blocking(move || worktree::snapshot(&cwd)).await else { return };
let changed = worktree::changed_between(&start, &end);
if changed.is_empty() {
return;
}
{
let mut s = self.state.lock();
let Some(touched) = &s.touched else { return };
let mut touched = (**touched).clone();
touched.extend(changed);
s.touched = Some(Arc::new(touched));
}
self.persist();
}
fn base(&self) -> worktree::TaskBase {
let s = self.state.lock();
let cwd = s.task.cwd.0.clone();
@@ -1640,6 +1696,7 @@ impl Task {
wanted: s.wanted.clone(),
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
subagents: s.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
@@ -1691,9 +1748,11 @@ impl Task {
/// the user stops one. The caller set `busy`.
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
loop {
let start = self.checkout_before_turn().await;
let result = self.turn(&prompt).await;
self.cancel_pending.store(false, Ordering::Release);
tokio::time::sleep(TURN_GRACE).await;
self.record_turn_changes(start).await;
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
let send_now = self.send_now.swap(false, Ordering::AcqRel);
+14 -3
Переглянути файл
@@ -2211,6 +2211,7 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
.unwrap();
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
count_every_change(&mgr, &task.id);
assert_eq!(task.project_root, Some(IpcPath(member.clone())));
assert_eq!(task.base.as_deref(), Some("member-main"));
if isolation == Isolation::Local {
@@ -2842,12 +2843,14 @@ async fn rolling_back_restores_the_start_of_the_task_and_keeps_the_users_own_edi
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
// What the agent did.
// What the agent did, while its turn ran.
write("mine.txt", "my edit\nand the agent's\n");
write("other.txt", "agent\n");
write("new.txt", "agent\n");
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
// The user's (or another task's) work between turns is not the task's.
write("later.txt", "mine\n");
async fn changed(mgr: &AgentManager, id: &str) -> Vec<String> {
mgr.changes(id).await.unwrap().into_iter().map(|c| c.rel_path).collect()
}
@@ -2863,6 +2866,7 @@ async fn rolling_back_restores_the_start_of_the_task_and_keeps_the_users_own_edi
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(read("mine.txt"), "my edit\n", "the user's edit stays");
assert!(!dir.join("new.txt").exists());
assert_eq!(read("later.txt"), "mine\n", "not the task's to roll back");
assert!(changed(&mgr, &task.id).await.is_empty());
mgr.delete(&task.id, false).await.unwrap();
@@ -2947,10 +2951,17 @@ impl Checkout {
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
count_every_change(&mgr, &task.id);
(mgr, task)
}
}
/// Counts every change in the checkout as the task's, as for a task saved before tasks
/// recorded what their turns changed: for tests that change files outside a turn.
fn count_every_change(mgr: &AgentManager, id: &str) {
mgr.task(id).unwrap().state.lock().touched = None;
}
async fn changed(mgr: &AgentManager, id: &str) -> Vec<String> {
mgr.changes(id).await.unwrap().into_iter().map(|c| c.rel_path).collect()
}
+36 -1
Переглянути файл
@@ -3,7 +3,7 @@
use crate::model::{AgentChange, AgentChanges, AgentCommit};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, LogQuery, Repo};
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
@@ -548,6 +548,25 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
}
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
/// or back to as committed.
pub(crate) fn changed_between(start: &BTreeMap<String, Stamp>, end: &BTreeMap<String, Stamp>) -> Vec<String> {
let mut changed: Vec<String> =
end.iter().filter(|(path, stamp)| start.get(*path) != Some(*stamp)).map(|(path, _)| path.clone()).collect();
changed.extend(start.keys().filter(|path| !end.contains_key(*path)).cloned());
changed
}
/// The changes among `changes` that the task made, when it records the files its turns
/// changed (`None`: every change counts).
pub(crate) fn made_by_task(changes: Vec<AgentChange>, touched: Option<&BTreeSet<String>>) -> Vec<AgentChange> {
let Some(touched) = touched else { return changes };
changes
.into_iter()
.filter(|c| touched.contains(&c.rel_path) || c.old_path.as_ref().is_some_and(|old| touched.contains(old)))
.collect()
}
/// Drops the changes that were there before the task and haven't been touched since.
pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<String, Stamp>) -> Vec<AgentChange> {
changes.into_iter().filter(|c| before.get(&c.rel_path).is_none_or(|s| *s != stamp(&c.path))).collect()
@@ -1184,4 +1203,20 @@ mod tests {
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\nMINE\n");
assert_eq!(std::fs::read_to_string(repo.join("gone.txt")).unwrap(), "bye\nbye\n");
}
#[test]
fn a_turn_changed_the_files_whose_state_moved() {
let start: BTreeMap<String, Stamp> =
[("edited", Some((1, 1))), ("same", Some((2, 2))), ("reverted", Some((3, 3)))]
.into_iter()
.map(|(p, s)| (p.to_owned(), s))
.collect();
let end: BTreeMap<String, Stamp> = [("edited", Some((1, 9))), ("same", Some((2, 2))), ("new", Some((4, 4)))]
.into_iter()
.map(|(p, s)| (p.to_owned(), s))
.collect();
let mut changed = changed_between(&start, &end);
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
}
+9 -3
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -9,8 +9,14 @@ license.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", default-features = false, features = ["std"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSBitmapImageRep", "NSImageRep", "NSPasteboard"] }
[target.'cfg(windows)'.dependencies]
png = "0.18"
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18"
[dev-dependencies]
png = "0.18"
+222 -3
Переглянути файл
@@ -18,6 +18,10 @@
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
//! `PNG` format or `CF_DIB` on Windows. Linux reads it through GTK in the app.
use std::path::PathBuf;
@@ -34,6 +38,19 @@ pub fn text() -> Option<String> {
imp::text()
}
/// The clipboard's image as PNG bytes, None when it holds none. Call on the main
/// thread on macOS.
#[cfg(any(windows, target_os = "macos"))]
pub fn png() -> Option<Vec<u8>> {
imp::png()
}
/// Whether the clipboard holds an image, without reading it. Call on the main
/// thread on macOS and Linux.
pub fn has_image() -> bool {
imp::has_image()
}
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
const HEADER: usize = 20;
@@ -134,9 +151,62 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
out
}
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
#[cfg(any(windows, test))]
const BI_RGB: u32 = 0;
#[cfg(any(windows, test))]
const BI_BITFIELDS: u32 = 3;
/// A packed DIB (`BITMAPINFOHEADER` or a later header, then the pixels) as PNG.
/// Only 24- and 32-bit uncompressed bitmaps, which is what screenshots and
/// copied images are; None for anything else. A 32-bit bitmap whose alpha is
/// all zero (most writers leave it unset) is opaque.
#[cfg(any(windows, test))]
fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
let u32_at = |at: usize| dib.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let header = u32_at(0)? as usize;
let width = u32_at(4)? as i32;
let height = u32_at(8)? as i32;
let bits = u16::from_le_bytes([*dib.get(14)?, *dib.get(15)?]);
let compression = u32_at(16)?;
if header < 40 || width <= 0 || height == 0 || !matches!(bits, 24 | 32) {
return None;
}
if compression != BI_RGB && !(compression == BI_BITFIELDS && bits == 32) {
return None;
}
// A `BITMAPINFOHEADER` keeps the three bitfield masks after it; later
// headers hold them inside. Masks other than BGRA's are not supported.
let masks = if compression == BI_BITFIELDS && header == 40 { 12 } else { 0 };
let colors = u32_at(32)? as usize;
let (width, rows) = (width as usize, height.unsigned_abs() as usize);
let stride = (width * bits as usize).div_ceil(32) * 4;
let start = header + masks + colors * 4;
let pixels = dib.get(start..start.checked_add(stride.checked_mul(rows)?)?)?;
let step = bits as usize / 8;
let mut rgba = Vec::with_capacity(width * rows * 4);
for row in 0..rows {
// A positive height stores the bottom row first.
let source = if height > 0 { rows - 1 - row } else { row };
let line = &pixels[source * stride..source * stride + width * step];
for px in line.chunks_exact(step) {
rgba.extend_from_slice(&[px[2], px[1], px[0], if step == 4 { px[3] } else { 255 }]);
}
}
if step == 4 && rgba.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
rgba.as_chunks_mut::<4>().0.iter_mut().for_each(|px| px[3] = 255);
}
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width as u32, rows as u32);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().ok()?.write_image_data(&rgba).ok()?;
Some(out)
}
#[cfg(windows)]
mod imp {
use super::{HEADER, decode, encode, names_text};
use super::{HEADER, decode, dib_to_png, encode, names_text};
use std::ffi::c_void;
use std::path::PathBuf;
use std::ptr;
@@ -164,6 +234,59 @@ mod imp {
fn GetClipboardData(format: u32) -> Handle;
fn SetClipboardData(format: u32, memory: Handle) -> Handle;
fn IsClipboardFormatAvailable(format: u32) -> i32;
fn RegisterClipboardFormatW(name: *const u16) -> u32;
}
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
/// bitmap on the clipboard reads as one.
const CF_DIB: u32 = 8;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
fn png_format() -> u32 {
let name: Vec<u16> = "PNG\0".encode_utf16().collect();
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
}
pub fn has_image() -> bool {
let png = png_format();
(png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0)
|| unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0
}
/// A copy of the clipboard's `format` block. Call with the clipboard open.
fn read_block(format: u32) -> Option<Vec<u8>> {
// SAFETY: the clipboard keeps the block alive while it is open, and
// `GlobalSize` bounds the bytes read from it.
unsafe {
let memory = GetClipboardData(format);
if memory.is_null() {
return None;
}
let data = GlobalLock(memory);
if data.is_null() {
return None;
}
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory)).to_vec();
GlobalUnlock(memory);
Some(bytes)
}
}
pub fn png() -> Option<Vec<u8>> {
if !open() {
return None;
}
let png = png_format();
let image = if png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0 {
read_block(png)
} else if unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0 {
read_block(CF_DIB).and_then(|dib| dib_to_png(&dib))
} else {
None
};
unsafe { CloseClipboard() };
image
}
#[link(name = "kernel32")]
@@ -327,8 +450,8 @@ mod imp {
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2::{ClassType, MainThreadMarker};
use objc2_app_kit::{
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
NSPasteboardWriting,
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf;
@@ -380,6 +503,33 @@ mod imp {
})
}
pub fn has_image() -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
let types = NSArray::from_slice(&[unsafe { NSPasteboardTypePNG }, unsafe { NSPasteboardTypeTIFF }]);
NSPasteboard::generalPasteboard().availableTypeFromArray(&types).is_some()
})
}
/// PNG as copied, else TIFF (what macOS screenshots and most apps write) converted.
pub fn png() -> Option<Vec<u8>> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let board = NSPasteboard::generalPasteboard();
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
if let Some(png) = board.dataForType(unsafe { NSPasteboardTypePNG }) {
return Some(png.to_vec());
}
let tiff = board.dataForType(unsafe { NSPasteboardTypeTIFF })?;
let image = NSBitmapImageRep::imageRepWithData(&tiff)?;
// SAFETY: an empty property dictionary is valid for every file type.
let png =
unsafe { image.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new()) }?;
Some(png.to_vec())
})
}
pub fn text() -> Option<String> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
@@ -448,6 +598,17 @@ mod imp {
false
}
pub fn has_image() -> bool {
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_is_image_available()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn files() -> std::io::Result<Vec<PathBuf>> {
Ok(Vec::new())
}
@@ -521,4 +682,62 @@ mod tests {
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
}
/// A `BITMAPINFOHEADER` DIB of `width` × `height` (positive: bottom-up).
fn dib(width: i32, height: i32, bits: u16, compression: u32, rows: &[&[u8]]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&40u32.to_le_bytes());
out.extend_from_slice(&width.to_le_bytes());
out.extend_from_slice(&height.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&bits.to_le_bytes());
out.extend_from_slice(&compression.to_le_bytes());
out.extend_from_slice(&[0u8; 20]);
if compression == super::BI_BITFIELDS {
for mask in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff] {
out.extend_from_slice(&mask.to_le_bytes());
}
}
for row in rows {
out.extend_from_slice(row);
}
out
}
fn decode_png(png: &[u8]) -> (u32, u32, Vec<u8>) {
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap();
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut buf).unwrap();
buf.truncate(info.buffer_size());
(info.width, info.height, buf)
}
#[test]
fn a_bottom_up_24_bit_bitmap_becomes_an_upright_opaque_png() {
// Rows are padded to 4 bytes; the first stored row is the bottom one.
let bottom: &[u8] = &[255, 0, 0, 0, 255, 0, 0, 0];
let top: &[u8] = &[0, 0, 255, 255, 255, 255, 0, 0];
let png = super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[bottom, top])).unwrap();
let (w, h, rgba) = decode_png(&png);
assert_eq!((w, h), (2, 2));
assert_eq!(rgba, [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]);
}
#[test]
fn a_32_bit_bitmap_keeps_its_alpha_unless_none_was_written() {
let row: &[u8] = &[10, 20, 30, 0, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_BITFIELDS, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 255, 60, 50, 40, 255]);
let row: &[u8] = &[10, 20, 30, 128, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_RGB, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 128, 60, 50, 40, 0]);
}
#[test]
fn unsupported_or_truncated_bitmaps_are_not_images() {
let row: &[u8] = &[1, 2, 3, 4];
assert!(super::dib_to_png(&dib(4, 1, 8, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&[0; 10]).is_none());
}
}
+30
Переглянути файл
@@ -325,6 +325,20 @@ pub fn migrate(data: &Path, local: &Path) {
if cfg!(target_os = "windows") && data != local {
migrate_entries(data, local);
}
if cfg!(target_os = "windows") {
relative_tool_shims(&local.join("tools"));
}
}
/// Wrappers written before they named their tool relative to themselves hold its absolute
/// path, which cmd.exe can't find through a non-ASCII user directory (#3338).
fn relative_tool_shims(tools: &Path) {
let Ok(entries) = fs::read_dir(tools) else { return };
for dir in entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
if let Err(error) = relocate_shims(&dir, &dir) {
tracing::warn!(%error, ?dir, "cannot make the tool's wrappers relative");
}
}
}
fn migrate_entries(data: &Path, local: &Path) {
@@ -651,6 +665,22 @@ mod tests {
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
}
#[test]
fn installed_tool_wrappers_become_relative() {
let tmp = tempfile::tempdir().unwrap();
let tools = tmp.path().join("tools");
let tool = tools.join("taplo");
fs::create_dir_all(tool.join("bin")).unwrap();
let shim = tool.join("bin/taplo.cmd");
fs::write(&shim, format!("@echo off\r\n\"{}\\taplo.exe\" %*\r\n", tool.display())).unwrap();
// A wrapper the user re-saved in another encoding is left alone.
fs::create_dir_all(tools.join("other/bin")).unwrap();
fs::write(tools.join("other/bin/x.cmd"), b"@echo off\r\n\"C:\\\xd5\xc5\" %*\r\n").unwrap();
relative_tool_shims(&tools);
assert_eq!(fs::read_to_string(&shim).unwrap(), "@echo off\r\n\"%~dp0..\\taplo.exe\" %*\r\n");
relative_tool_shims(&tmp.path().join("missing"));
}
#[test]
fn wrappers_accept_mixed_separators_without_rewriting_neighbor_paths() {
let text = "@echo off\r\n\"C:\\old\\tools/demo\\payload.exe\" \"C:\\old\\tools/demo-other\\x\" %*\r\n";
+29 -6
Переглянути файл
@@ -1,6 +1,10 @@
use super::page::{OFFSET, Page};
use super::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{Diagnostic, IdeResult, Severity};
use serde_json::{Value, json};
use serde_json::{Map, Value, json};
/// Problems `get_project_problems` lists by default.
const PROBLEMS_LIMIT: usize = 100;
pub fn tools() -> Vec<Tool> {
vec![
@@ -37,7 +41,10 @@ Lines and UTF-16 columns are 1-based.",
and inspections after profile filtering. This reflects what the Problems view shows, rather than a fresh analysis.
Lines and UTF-16 columns are 1-based.",
project_problems,
),
)
.param(Param::optional("errorsOnly", ParamType::Boolean, "Only errors (default) or warnings too"))
.param(Param::optional("limit", ParamType::Integer, "Problems to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET)),
]
}
@@ -90,9 +97,25 @@ async fn file_problems(call: Call) -> IdeResult<Output> {
}
async fn project_problems(call: Call) -> IdeResult<Output> {
let page = Page::of(&call, PROBLEMS_LIMIT)?;
let errors_only = call.flag("errorsOnly", true)?;
let files = call.host.mcp_reports.problems(&call.host.mcp_windows(call.root()));
let files: Vec<_> = files.into_iter().map(|f| json!({
"filePath":call.display(&f.path.0), "problems": f.items.into_iter().map(|d| problem(d, "")).collect::<Vec<_>>()
})).collect();
Output::json(json!({"files":files}))
let problems: Vec<(String, Value)> = files
.into_iter()
.flat_map(|f| {
let path = call.display(&f.path.0);
let wanted = f.items.into_iter().filter(|d| !errors_only || d.severity == Severity::Error);
wanted.map(move |d| (path.clone(), problem(d, "")))
})
.collect();
let mut out = Map::new();
let mut files: Vec<Value> = Vec::new();
for (path, problem) in page.take(problems, &mut out) {
match files.last_mut() {
Some(file) if file["filePath"] == path.as_str() => file["problems"].as_array_mut().unwrap().push(problem),
_ => files.push(json!({ "filePath": path, "problems": [problem] })),
}
}
out.insert("files".into(), files.into());
Output::json(Value::Object(out))
}
+100 -6
Переглянути файл
@@ -2,6 +2,7 @@
// the list_directory_tree part of FileToolset.kt, src/com/intellij/mcpserver/util/fs.util.kt), Apache-2.0.
//! Reading files and listing directories.
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use crate::mcp::util::{
self, RELATIVE_PATH_IN_PROJECT_DESCRIPTION, TIMED_OUT_DESCRIPTION, TIMEOUT_MILLISECONDS_DESCRIPTION,
@@ -17,6 +18,8 @@ const MAX_READ_LIMIT: i64 = 5000;
/// Longer lines are cut (minified files would flood the context), in UTF-16 units.
const MAX_LINE_LENGTH: usize = 2000;
const DEFAULT_TREE_DEPTH: i64 = 5;
/// Entries `list_directory_tree` lists by default.
const TREE_LIMIT: usize = 100;
pub fn tools() -> Vec<Tool> {
vec![read_file(), list_directory_tree()]
@@ -149,6 +152,12 @@ struct DirectoryTreeInfo {
errors: Vec<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
listing_timed_out: bool,
/// Entries under the directory within `maxDepth`.
total: usize,
#[serde(skip_serializing_if = "std::ops::Not::not")]
more: bool,
#[serde(skip_serializing_if = "Option::is_none")]
next_offset: Option<usize>,
}
fn list_directory_tree() -> Tool {
@@ -156,10 +165,12 @@ fn list_directory_tree() -> Tool {
"list_directory_tree",
"Provides a tree representation of the specified directory in the pseudo graphic format like `tree` utility does.
Use this tool to explore the contents of a directory or the whole project.
You MUST prefer this tool over listing directories via command line utilities like `ls` or `dir`.",
You MUST prefer this tool over listing directories via command line utilities like `ls` or `dir`.
A page that starts inside a directory repeats the lines of the directories above it.",
|call| async move {
let directory = call.str("directoryPath")?;
let max_depth = call.opt_i64("maxDepth")?.unwrap_or(DEFAULT_TREE_DEPTH);
let page = Page::of(&call, TREE_LIMIT)?;
let timeout = call.opt_i64("timeout")?.unwrap_or(util::MEDIUM_TIMEOUT.as_millis() as i64);
let dir = call.resolve_readable(&directory).await?;
if !dir.exists() {
@@ -170,8 +181,16 @@ You MUST prefer this tool over listing directories via command line utilities li
}
let deadline = Instant::now() + Duration::from_millis(timeout.max(0) as u64);
let cancel = call.cancel.clone();
let mut tree =
TreeRender { out: String::new(), errors: Vec::new(), timed_out: false, deadline, cancel: cancel.clone() };
let mut tree = TreeRender {
out: String::new(),
errors: Vec::new(),
timed_out: false,
deadline,
cancel: cancel.clone(),
page,
seen: 0,
above: Vec::new(),
};
let tree = call
.host()
.blocking(move || {
@@ -187,11 +206,16 @@ You MUST prefer this tool over listing directories via command line utilities li
tree: tree.out,
errors: tree.errors,
listing_timed_out: tree.timed_out,
total: tree.seen,
more: tree.seen > page.end(),
next_offset: (tree.seen > page.end()).then_some(page.end()),
})
},
)
.param(Param::required("directoryPath", ParamType::String, RELATIVE_PATH_IN_PROJECT_DESCRIPTION))
.param(Param::optional("maxDepth", ParamType::Integer, "Maximum recursion depth"))
.param(Param::optional("limit", ParamType::Integer, "Entries to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("timeout", ParamType::Integer, TIMEOUT_MILLISECONDS_DESCRIPTION))
.output(json!({
"type": "object",
@@ -200,19 +224,28 @@ You MUST prefer this tool over listing directories via command line utilities li
"tree": { "type": "string" },
"errors": { "type": "array", "items": { "type": "string" } },
"listingTimedOut": { "type": "boolean", "description": TIMED_OUT_DESCRIPTION },
"total": { "type": "integer" },
"more": { "type": "boolean" },
"nextOffset": { "type": "integer" },
},
"required": ["traversedDirectory", "tree", "errors"],
"required": ["traversedDirectory", "tree", "errors", "total"],
}))
}
/// The `tree`-like listing: the directory's absolute path, then every entry (hidden and
/// ignored ones too) by lower-cased name, directories marked with `/`.
/// ignored ones too) by lower-cased name, directories marked with `/`; entries outside the
/// page are counted, not listed.
struct TreeRender {
out: String,
errors: Vec<String>,
timed_out: bool,
deadline: Instant,
cancel: CancellationToken,
page: Page,
/// Entries met so far.
seen: usize,
/// The lines of the directories above the entry, and whether this page shows them yet.
above: Vec<(String, bool)>,
}
impl TreeRender {
@@ -235,7 +268,13 @@ impl TreeRender {
path.file_name().unwrap_or_default().to_string_lossy().into_owned()
};
let is_dir = path.is_dir() && !path.is_symlink();
self.out.push_str(&format!("{indent}{prefix}{name}{}\n", if is_dir { "/" } else { "" }));
let line = format!("{indent}{prefix}{name}{}\n", if is_dir { "/" } else { "" });
let shown = if is_root {
self.out.push_str(&line);
true
} else {
self.entry(&line)
};
if !is_dir {
return;
}
@@ -250,9 +289,32 @@ impl TreeRender {
children.sort_by_cached_key(|p| (key(p).to_lowercase(), key(p)));
let child_indent = format!("{indent}{}", if is_last { " " } else { "│ " });
let n = children.len();
if !is_root {
self.above.push((line, shown));
}
for (i, child) in children.iter().enumerate() {
self.render(child, &child_indent, i + 1 == n, max_depth - 1, false);
}
if !is_root {
self.above.pop();
}
}
/// Counts an entry and lists it when on the page, after the directories above it.
fn entry(&mut self, line: &str) -> bool {
let n = self.seen;
self.seen += 1;
if n < self.page.offset || n >= self.page.end() {
return false;
}
for (above, shown) in &mut self.above {
if !*shown {
self.out.push_str(above);
*shown = true;
}
}
self.out.push_str(line);
true
}
}
@@ -302,4 +364,36 @@ mod tests {
let short = format!("{}😀", "x".repeat(1998));
assert_eq!(format_line(&short), short);
}
#[test]
fn a_tree_page_repeats_the_directories_above_it() {
let tmp = tempfile::tempdir().unwrap();
for file in ["a/x.txt", "a/y.txt", "b.txt"] {
let path = tmp.path().join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let render = |offset, limit| {
let mut tree = TreeRender {
out: String::new(),
errors: Vec::new(),
timed_out: false,
deadline: Instant::now() + Duration::from_secs(10),
cancel: CancellationToken::new(),
page: Page { offset, limit },
seen: 0,
above: Vec::new(),
};
tree.render(tmp.path(), "", true, 5, true);
let root = format!("{}/\n", tmp.path().display());
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
};
assert_eq!(render(0, 2), (" ├── a/\n │ ├── x.txt\n".to_owned(), 4));
assert_eq!(
render(2, 2).0,
" ├── a/\n │ └── y.txt\n └── b.txt\n",
"the page in `a/` repeats its line"
);
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
}
}
+1
Переглянути файл
@@ -7,6 +7,7 @@ pub(crate) mod run;
mod vcs;
pub use requests::Requests;
mod files;
mod page;
mod reports;
mod search;
mod symbols;
+71
Переглянути файл
@@ -0,0 +1,71 @@
//! `limit` and `offset` of the tools that list things: a few items by default, the rest page by page.
use super::tool::Call;
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value};
/// The most items one call returns.
pub const MAX_LIMIT: usize = 1000;
pub const OFFSET: &str = "Items to skip: `nextOffset` of the previous page";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Page {
pub offset: usize,
pub limit: usize,
}
impl Page {
/// The `limit` (`default` when absent, at most [`MAX_LIMIT`]) and `offset` (0) arguments.
pub fn of(call: &Call, default: usize) -> IdeResult<Self> {
let limit = match call.opt_i64("limit")? {
None => default,
Some(n) if n <= 0 => return Err(IdeError::invalid("limit must be > 0")),
Some(n) => (n as usize).min(MAX_LIMIT),
};
let offset = match call.opt_i64("offset")? {
None => 0,
Some(n) if n < 0 => return Err(IdeError::invalid("offset must be >= 0")),
Some(n) => n as usize,
};
Ok(Self { offset, limit })
}
/// Where the page ends: the items to find for it.
pub fn end(&self) -> usize {
self.offset.saturating_add(self.limit)
}
/// This page of all the `items`; `out` gets their `total`, and `more` and `nextOffset` when some follow.
pub fn take<T>(&self, items: Vec<T>, out: &mut Map<String, Value>) -> Vec<T> {
let total = items.len();
out.insert("total".into(), total.into());
self.mark(total > self.end(), out);
items.into_iter().skip(self.offset).take(self.limit).collect()
}
/// `more` and `nextOffset` when items follow the page.
pub fn mark(&self, more: bool, out: &mut Map<String, Value>) {
if more {
out.insert("more".into(), true.into());
out.insert("nextOffset".into(), self.end().into());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pages_say_what_follows() {
let page = |offset, limit| Page { offset, limit };
let mut out = Map::new();
assert_eq!(page(0, 2).take(vec![1, 2, 3, 4, 5], &mut out), [1, 2]);
assert_eq!(Value::Object(out), serde_json::json!({ "total": 5, "more": true, "nextOffset": 2 }));
let mut out = Map::new();
assert_eq!(page(4, 2).take(vec![1, 2, 3, 4, 5], &mut out), [5]);
assert_eq!(Value::Object(out), serde_json::json!({ "total": 5 }), "the last page");
let mut out = Map::new();
assert!(page(9, 2).take(vec![1], &mut out).is_empty());
}
}
+80 -4
Переглянути файл
@@ -3,6 +3,7 @@
use super::agent::{AgentRun, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
use super::output::RUN_PREVIEW_MAX_LENGTH;
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::run::timeout;
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{IdeError, IdeResult};
@@ -35,6 +36,14 @@ and `nextOffset` are positions in the tab's raw output log; pass `nextOffset` as
const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
(keeps the start), MIDDLE (keeps both ends) or NONE";
/// `list_runs`: tabs returned by default, and characters of each command, enough to tell them apart.
const LIST_LIMIT: usize = 10;
const LIST_COMMAND_CHARS: usize = 80;
const LIST_STATES: [(&str, &[&str]); 3] = [
("running", &["starting", "running", "stopping"]),
("idle", &["succeeded", "failed", "crashed", "stoppedByAgent", "stoppedByUser", "startFailed"]),
("error", &["failed", "crashed", "startFailed"]),
];
fn find(call: &Call) -> IdeResult<Arc<AgentRun>> {
let name = tab_name(&call.str("name")?)?;
@@ -283,13 +292,64 @@ for input) and `tabClosedAt` when the user closed the tab.{INTERVENTIONS}"
pub fn list_runs() -> Tool {
Tool::new(
"list_runs",
"Lists the agent tabs of the project (those started by `run_command`) with their status.",
"Lists the agent tabs of the project (those started by `run_command`), newest first: name, state, the \
start of the command, exit code and times. `get_run_status` gives a tab's whole status.",
|call| async move {
let runs: Vec<Value> =
call.host().mcp_agent_runs.list(call.root()).iter().map(|r| Value::Object(r.status())).collect();
Output::json(serde_json::json!({ "runs": runs }))
let page = Page::of(&call, LIST_LIMIT)?;
let wanted = call.opt_str("state")?.filter(|s| s != "all");
let states = match wanted.as_deref() {
None => None,
Some(s) => Some(match LIST_STATES.iter().find(|(group, _)| *group == s) {
Some((_, states)) => states.to_vec(),
None if LIST_STATES[1].1.contains(&s) || LIST_STATES[0].1.contains(&s) => vec![s],
None => {
return Err(IdeError::invalid(format!(
"unknown state `{s}`: all, running, idle, error, or one of the states of get_run_status"
)));
}
}),
};
let runs: Vec<Value> = call
.host()
.mcp_agent_runs
.list(call.root())
.iter()
.rev()
.map(|r| r.status())
.filter(|s| {
states.as_ref().is_none_or(|states| s["state"].as_str().is_some_and(|v| states.contains(&v)))
})
.map(|s| Value::Object(brief(s)))
.collect();
let mut out = Map::new();
let runs = page.take(runs, &mut out);
out.insert("runs".into(), runs.into());
Output::json(Value::Object(out))
},
)
.param(Param::optional(
"state",
ParamType::String,
"all (default), running, idle (not running), error (failed, crashed, startFailed), or one state",
))
.param(Param::optional("limit", ParamType::Integer, "Tabs to return at most (default 10)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
/// A tab in `list_runs`: what tells it apart and how it went, the command cut short.
fn brief(mut status: Map<String, Value>) -> Map<String, Value> {
let mut out = Map::new();
for key in ["name", "state", "command", "exitCode", "crash", "error", "startedAt", "endedAt", "tabClosedAt"] {
if let Some(v) = status.remove(key) {
out.insert(key.into(), v);
}
}
if let Some(Value::String(command)) = out.get_mut("command")
&& command.chars().count() > LIST_COMMAND_CHARS
{
*command = format!("{}…", command.chars().take(LIST_COMMAND_CHARS).collect::<String>());
}
out
}
/// What a key does to a command on pipes.
@@ -407,6 +467,22 @@ pub fn tools() -> Vec<Tool> {
mod tests {
use super::*;
#[test]
fn listed_tabs_are_brief_and_their_commands_cut_short() {
let status = serde_json::json!({
"name": "_agent_build", "state": "failed", "command": "x".repeat(100), "exitCode": 1,
"workingDirectory": "", "outputLength": 9, "startedBy": "agent",
});
let Value::Object(status) = status else { unreachable!() };
let brief = Value::Object(brief(status));
assert_eq!(brief["command"].as_str().unwrap(), format!("{}…", "x".repeat(LIST_COMMAND_CHARS)));
assert_eq!(
(&brief["name"], &brief["state"], &brief["exitCode"]),
(&"_agent_build".into(), &"failed".into(), &1.into())
);
assert!(brief.get("outputLength").is_none() && brief.get("workingDirectory").is_none());
}
#[test]
fn keys_are_what_pipes_can_take() {
assert_eq!(key(" enter ").unwrap(), Key::Text("\n"));
+25 -3
Переглянути файл
@@ -7,6 +7,7 @@ use super::output::OutputCollector;
use super::process::{quote, split_words};
use super::targets;
use crate::Project;
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::run::timeout;
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_build::compile::BuildKind;
@@ -19,6 +20,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
const DEFAULT_TIMEOUT_MS: usize = 10_000;
/// Configurations `get_run_configurations` lists by default.
const CONFIGURATIONS_LIMIT: usize = 100;
/// Output of a failed before-launch process kept for the error message.
const MAX_PROCESS_OUTPUT_LENGTH: usize = 20_000;
/// A before-launch build gets this long.
@@ -50,7 +53,8 @@ fn describe_config(call: &Call, c: &RunConfig) -> Value {
if let Some(cwd) = c.cwd.as_deref() {
v["workingDirectory"] = call.display(&call.root().join(cwd)).into();
}
if !c.env.is_empty() {
// A detected configuration's environment is the IDE's own (its tools on `PATH`).
if !c.env.is_empty() && !c.detected {
v["environment"] = json!(c.env);
}
}
@@ -133,8 +137,23 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a
.await?;
return Output::json(json!({ "filePath": file, "runPoints": points }));
}
let list: Vec<Value> = configs.iter().map(|c| describe_config(&call, c)).collect();
Output::json(json!({ "configurations": list }))
let page = Page::of(&call, CONFIGURATIONS_LIMIT)?;
let query = call.opt_str("query")?.map(|q| q.to_lowercase());
let list: Vec<Value> = configs
.iter()
.filter(|c| {
query.as_ref().is_none_or(|q| {
[c.name.as_str(), c.kind.as_str(), command_line(c).as_str()]
.iter()
.any(|s| s.to_lowercase().contains(q.as_str()))
})
})
.map(|c| describe_config(&call, c))
.collect();
let mut out = Map::new();
let list = page.take(list, &mut out);
out.insert("configurations".into(), list.into());
Output::json(Value::Object(out))
},
)
.write()
@@ -144,6 +163,9 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a
"Optional file path relative to the project root. When provided, returns run points (executable entry points) \
in the file instead of project-wide run configurations.",
))
.param(Param::optional("query", ParamType::String, "Only configurations whose name, type or command contains it"))
.param(Param::optional("limit", ParamType::Integer, "Configurations to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
/// What `execute_run_configuration` runs.
+36 -16
Переглянути файл
@@ -5,6 +5,7 @@
//! Coordinates are 1-based, end exclusive; columns count UTF-16 code units like
//! the editor (one per character except emoji and other astral characters).
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use crate::mcp::util::{INDEXING_PARTIAL_RESULT_REASON, MEDIUM_TIMEOUT};
use crate::ops::search::SearchEvent;
@@ -21,8 +22,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
pub const MAX_RESULTS_UPPER_BOUND: usize = 5000;
const DEFAULT_LIMIT: i64 = 1000;
pub const SYMBOL_SEARCH_DEFAULT_LIMIT: i64 = 50;
const DEFAULT_LIMIT: usize = 100;
pub const SYMBOL_SEARCH_DEFAULT_LIMIT: usize = 50;
pub const SEARCH_TIMEOUT_PARTIAL_RESULT_REASON: &str =
"The search timed out after 10 s. Narrow the query or pass paths.";
/// Symbols requested from the index per result when `paths` filters them afterwards.
@@ -37,7 +38,8 @@ const LINE_WINDOW: usize = 500;
const PATHS_DESCRIPTION: &str = "Optional list of project-relative glob patterns to filter results. Supports '!' \
excludes. Trailing '/' expands to '**'. Patterns without '/' are treated as '**/pattern'. Empty strings are ignored.";
const LIMIT_DESCRIPTION: &str = "Maximum number of results to return";
const LIMIT_DESCRIPTION: &str = "Results to return at most (default 100)";
const SYMBOL_LIMIT_DESCRIPTION: &str = "Results to return at most (default 50)";
const CONTEXT_DESCRIPTION: &str = "Lines around each match to return besides the matched line (`lineText`): \"+N\" the \
N lines after it (`contextAfter`), \"-N\" the N lines before it (`contextBefore`), \"N\" (or the number N) N lines on \
each side. At most 50. Default: the matched line only.";
@@ -67,6 +69,7 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].",
.param(Param::required("q", ParamType::String, "Text to search for"))
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("context", ParamType::String, CONTEXT_DESCRIPTION))
.output(result_schema())
}
@@ -88,6 +91,7 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].",
.param(Param::required("q", ParamType::String, "Regex pattern to search for"))
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("context", ParamType::String, CONTEXT_DESCRIPTION))
.output(result_schema())
}
@@ -113,7 +117,8 @@ If you don't find a suitable result, try again with include_external=true to sea
"Whether to include SDK and library symbols. Disabled by default; if nothing suitable is found, try again \
with include_external=true.",
))
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
.param(Param::optional("limit", ParamType::Integer, SYMBOL_LIMIT_DESCRIPTION))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("context", ParamType::String, CONTEXT_DESCRIPTION))
.output(result_schema())
}
@@ -138,6 +143,7 @@ Paths are optional additional glob filters relative to the project root.",
"Whether to include excluded/ignored files in results",
))
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.output(result_schema())
}
@@ -191,6 +197,9 @@ struct SearchResult {
items: Vec<SearchItem>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
more: bool,
/// The `offset` of the next page, when `more`.
#[serde(skip_serializing_if = "Option::is_none")]
next_offset: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
partial_result_reason: Option<&'static str>,
}
@@ -212,16 +221,23 @@ fn result_schema() -> Value {
"required": ["filePath"],
} },
"more": { "type": "boolean" },
"nextOffset": int,
"partialResultReason": string,
},
})
}
fn limit(call: &Call, default: i64) -> IdeResult<usize> {
match call.opt_i64("limit")?.unwrap_or(default) {
n if n <= 0 => Err(IdeError::invalid("limit must be > 0")),
n => Ok((n as usize).min(MAX_RESULTS_UPPER_BOUND)),
}
/// The page of `call` and the results to find for it: up to its end.
fn page(call: &Call, default: usize) -> IdeResult<(Page, usize)> {
let page = Page::of(call, default)?;
Ok((page, page.end().min(MAX_RESULTS_UPPER_BOUND)))
}
/// Drops the results before the page, and the `nextOffset` when more follow. A search finds
/// [`MAX_RESULTS_UPPER_BOUND`] results at most, so no page starts past them.
fn skip<T>(page: Page, items: &mut Vec<T>, more: bool) -> Option<usize> {
items.drain(..page.offset.min(items.len()));
(more && page.end() < MAX_RESULTS_UPPER_BOUND).then_some(page.end())
}
fn query(call: &Call, empty: &str) -> IdeResult<String> {
@@ -521,7 +537,7 @@ struct TextHit {
async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
let pattern = query(&call, if is_regex { "Regex pattern is empty" } else { "Search text is empty" })?;
let limit = limit(&call, DEFAULT_LIMIT)?;
let (page, limit) = page(&call, DEFAULT_LIMIT)?;
let around = context(&call)?;
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
// Globs Find in Files cannot take are applied afterwards, so the engine must not
@@ -612,11 +628,12 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
..Default::default()
})
.collect();
let next_offset = skip(page, &mut items, more);
let absolute: std::collections::HashMap<&str, &Path> =
files.iter().map(|(path, file)| (path.as_str(), file.path.0.as_path())).collect();
fill_lines(&call, &mut items, |item| absolute.get(item.file_path.as_str()).map(|p| p.to_path_buf()), around).await;
let partial_result_reason = timed_out.then_some(SEARCH_TIMEOUT_PARTIAL_RESULT_REASON);
Output::json(SearchResult { items, more, partial_result_reason })
Output::json(SearchResult { items, more, next_offset, partial_result_reason })
}
/// The matches of `ranges` (byte ranges in `text`) that start on 0-based `line`, with their
@@ -721,7 +738,7 @@ async fn run_search(call: &Call, query: SearchQuery) -> IdeResult<(Vec<FileMatch
async fn file_search(call: Call) -> IdeResult<Output> {
let q = query(&call, "Glob pattern is empty")?;
let limit = limit(&call, DEFAULT_LIMIT)?;
let (page, limit) = page(&call, DEFAULT_LIMIT)?;
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
let include_excluded = call.flag("includeExcluded", false)?;
let glob = GlobSetBuilder::new()
@@ -759,9 +776,11 @@ async fn file_search(call: Call) -> IdeResult<Output> {
Ok((found, more, walk.timed_out.get()))
})
.await?;
let items = paths.into_iter().map(|file_path| SearchItem { file_path, ..Default::default() }).collect();
let mut items: Vec<SearchItem> =
paths.into_iter().map(|file_path| SearchItem { file_path, ..Default::default() }).collect();
let next_offset = skip(page, &mut items, more);
let partial_result_reason = timed_out.then_some(SEARCH_TIMEOUT_PARTIAL_RESULT_REASON);
Output::json(SearchResult { items, more, partial_result_reason })
Output::json(SearchResult { items, more, next_offset, partial_result_reason })
}
struct Walk {
@@ -835,7 +854,7 @@ impl Walk {
async fn symbol_search(call: Call) -> IdeResult<Output> {
let started = Instant::now();
let q = query(&call, "Search query is empty")?;
let limit = limit(&call, SYMBOL_SEARCH_DEFAULT_LIMIT)?;
let (page, limit) = page(&call, SYMBOL_SEARCH_DEFAULT_LIMIT)?;
let around = context(&call)?;
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
let external = call.flag("include_external", false)?;
@@ -886,6 +905,7 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
}
let more = items.len() > limit || timed_out;
items.truncate(limit);
let next_offset = skip(page, &mut items, more);
// Project files (relative paths, or absolute ones of content roots); library URIs are left out.
let root = call.root().to_path_buf();
let absolute = |item: &SearchItem| {
@@ -899,7 +919,7 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
} else {
timed_out.then_some(SEARCH_TIMEOUT_PARTIAL_RESULT_REASON)
};
Output::json(SearchResult { items, more, partial_result_reason })
Output::json(SearchResult { items, more, next_offset, partial_result_reason })
}
/// The language servers' workspace symbols, and whether `budget` ran out first; empty
+15
Переглянути файл
@@ -210,6 +210,7 @@ fn leads_declaration(line: &str, line_comment: Option<&str>) -> bool {
pub fn find_references() -> Tool {
Tool::new("find_references", "Find references using the language service and the IDE's project index. Positions are 1-based UTF-16. Reports incomplete results when analysis is still running.", |call| async move {
let path = call.resolve_readable(&call.str("filePath")?).await?;
let page = super::page::Page::of(&call, REFERENCES_LIMIT)?;
let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?;
let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?;
let project = call.project.clone();
@@ -244,14 +245,28 @@ pub fn find_references() -> Tool {
}
}
positions(&mut value);
// `classified`, when there, goes with `locations` one to one.
if let serde_json::Value::Object(map) = &mut value {
let mut list = |key: &str| match map.remove(key) { Some(serde_json::Value::Array(items)) => items, _ => Vec::new() };
let (locations, classified) = (list("locations"), list("classified"));
let classified = page.take(classified, &mut serde_json::Map::new());
let locations = page.take(locations, map);
map.insert("locations".into(), locations.into());
map.insert("classified".into(), classified.into());
}
Output::json(value)
})
.param(Param::required("filePath", ParamType::String, "Path relative to the project root"))
.param(Param::required("line", ParamType::Integer, "1-based line"))
.param(Param::required("column", ParamType::Integer, "1-based UTF-16 column"))
.param(Param::optional("includeDeclaration", ParamType::Boolean, "Include declarations (default true)"))
.param(Param::optional("limit", ParamType::Integer, "References to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, super::page::OFFSET))
}
/// References `find_references` lists by default.
const REFERENCES_LIMIT: usize = 100;
fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult<Pos> {
if line < 1 || line > u32::MAX as i64 || column < 1 || column > u32::MAX as i64 {
return Err(IdeError::invalid("line and column must be positive 1-based positions"));
+15 -11
Переглянути файл
@@ -2,12 +2,13 @@
// (mcpserver.vcs/src/com/intellij/mcpserver/toolsets/vcs/VcsToolset.kt), Apache-2.0.
//! Version control: repositories and git status.
use crate::mcp::page::{OFFSET, Page};
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::{IdeError, IdeResult};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
const STATUS_DEFAULT_LIMIT: i64 = 1000;
const STATUS_DEFAULT_LIMIT: usize = 100;
pub fn tools() -> Vec<Tool> {
vec![get_repositories(), git_status(), git_diff()]
@@ -254,11 +255,7 @@ By default all Git repositories are returned.",
|call| async move {
let include_untracked = call.flag("includeUntracked", true)?;
let include_ignored = call.flag("includeIgnored", false)?;
let limit = call.opt_i64("limit")?.unwrap_or(STATUS_DEFAULT_LIMIT);
if limit <= 0 {
return Err(IdeError::invalid("limit must be > 0"));
}
let limit = limit as usize;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
let host = call.host();
let h = host.clone();
let w = call.window.clone();
@@ -305,7 +302,8 @@ By default all Git repositories are returned.",
let count = |f: fn(&StatusEntry) -> bool| entries.iter().filter(|e| f(e)).count();
let listed: Vec<Value> = entries
.iter()
.take(limit)
.skip(page.offset)
.take(page.limit)
.map(|e| {
let mut v = json!({
"pathRelativeToRepository": e.path.trim_end_matches('/'),
@@ -318,19 +316,24 @@ By default all Git repositories are returned.",
v
})
.collect();
repositories.push(json!({
let more = entries.len() > page.end();
let mut repository = json!({
"repositoryPathRelativeToProject": rel,
"currentBranch": branch,
"isClean": entries.is_empty(),
"totalEntries": entries.len(),
"hasMoreEntries": entries.len() > listed.len(),
"hasMoreEntries": more,
"stagedCount": count(StatusEntry::staged),
"unstagedCount": count(StatusEntry::unstaged),
"untrackedCount": count(StatusEntry::untracked),
"ignoredCount": count(StatusEntry::ignored),
"conflictedCount": count(StatusEntry::conflicted),
"entries": listed,
}));
});
if more {
repository["nextOffset"] = page.end().into();
}
repositories.push(repository);
}
Output::json(json!({ "repositories": repositories }))
},
@@ -342,7 +345,8 @@ By default all Git repositories are returned.",
))
.param(Param::optional("includeUntracked", ParamType::Boolean, "Whether to include untracked files"))
.param(Param::optional("includeIgnored", ParamType::Boolean, "Whether to include ignored files"))
.param(Param::optional("limit", ParamType::Integer, "Maximum number of entries returned per repository"))
.param(Param::optional("limit", ParamType::Integer, "Entries to return per repository at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
fn git_diff() -> Tool {
+1
Переглянути файл
@@ -342,6 +342,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "clear_caches"
| "clipboard_file_list"
| "clipboard_has_files"
| "clipboard_has_image"
| "clipboard_image"
| "clipboard_set_file_list"
| "clipboard_write_text"
+68 -1
Переглянути файл
@@ -110,6 +110,11 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
let found = h.json("search_text", json!({"q":"needle","limit":2})).await;
assert_eq!(found["items"].as_array().unwrap().len(), 2);
assert_eq!(found["more"], true);
assert_eq!(found["nextOffset"], 2);
// The next page goes on where this one ended.
let every = h.json("search_text", json!({"q":"needle","limit":20})).await["items"].as_array().unwrap().clone();
let next = h.json("search_text", json!({"q":"needle","limit":2,"offset":2})).await;
assert_eq!(next["items"].as_array().unwrap()[..], every[2..every.len().min(4)]);
let all = h.json("search_text", json!({"q":"fresh","limit":20})).await;
assert_eq!(all["items"][0]["filePath"], "src/a.txt");
// The matched line comes with the result (unsaved text included), and lines around it on request.
@@ -162,7 +167,9 @@ async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_c
assert_eq!(focused["selection"]["startColumn"], 3);
let problems = h.json("get_file_problems", json!({"filePath":"src/a.txt","errorsOnly":false})).await;
assert_eq!(problems["errors"][0]["description"], "reported warning");
assert_eq!(h.json("get_project_problems", json!({})).await["files"].as_array().unwrap().len(), 1);
assert_eq!(h.json("get_project_problems", json!({})).await["files"], json!([]), "errors only by default");
let all = h.json("get_project_problems", json!({"errorsOnly":false})).await;
assert_eq!((all["files"].as_array().unwrap().len(), &all["total"]), (1, &json!(1)));
h.host.close_project("main");
h.host.open_project("main", &h.root).unwrap();
assert_eq!(h.json("get_all_open_file_paths", json!({})).await["openFiles"], json!([]));
@@ -287,6 +294,41 @@ async fn execution_requires_a_window_and_denial_never_runs_a_build() {
assert!(error.contains("window closed"), "{error}");
}
#[tokio::test(flavor = "multi_thread")]
async fn run_configurations_are_listed_a_page_at_a_time_and_filtered() {
let h = Harness::new();
h.trust().await;
let saved = |name: &str, command: &str, env: &[(&str, &str)]| ide_run::RunConfig {
id: format!("user:{name}"),
name: name.into(),
kind: "shell".into(),
command: command.into(),
args: Vec::new(),
cwd: None,
env: env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
let configs =
[saved("build", "tsc", &[("MODE", "ci")]), saved("lint", "oxlint .", &[]), saved("test", "vitest", &[])];
ide_run::save_user_configs(&h.root, &configs).unwrap();
let all = h.json("get_run_configurations", json!({})).await;
let total = all["total"].as_u64().unwrap();
assert!(total >= 3, "{all}");
// A saved configuration's own environment is listed.
let build = all["configurations"].as_array().unwrap().iter().find(|c| c["name"] == "build").unwrap();
assert_eq!(build["environment"], json!({ "MODE": "ci" }));
let first = h.json("get_run_configurations", json!({"limit": 1})).await;
assert_eq!((first["configurations"].as_array().unwrap().len(), &first["nextOffset"]), (1, &json!(1)));
let lint = h.json("get_run_configurations", json!({"query": "OXLINT"})).await;
let found = lint["configurations"].as_array().unwrap();
assert!(!found.is_empty() && (found.len() as u64) < total, "{lint}");
assert!(found.iter().all(|c| c.to_string().to_lowercase().contains("oxlint")), "{lint}");
}
#[tokio::test(flavor = "multi_thread")]
async fn git_status_and_diff_on_a_temporary_repository() {
let h = Harness::new();
@@ -308,6 +350,18 @@ async fn git_status_and_diff_on_a_temporary_repository() {
std::fs::write(h.root.join("src/a.txt"), "changed\n").unwrap();
let status = h.json("git_status", json!({"repositoryPathRelativeToProject":"."})).await;
assert_eq!(status["repositories"][0]["unstagedCount"], 1);
// Two entries, one per page.
std::fs::write(h.root.join("src/new.txt"), "new\n").unwrap();
let page =
|offset: u64| h.json("git_status", json!({"repositoryPathRelativeToProject":".","limit":1,"offset":offset}));
let first = page(0).await["repositories"][0].clone();
assert_eq!(
(&first["totalEntries"], &first["hasMoreEntries"], &first["nextOffset"]),
(&json!(2), &json!(true), &json!(1))
);
let second = page(1).await["repositories"][0].clone();
assert_ne!(second["entries"][0], first["entries"][0]);
assert!(second.get("nextOffset").is_none(), "{second}");
assert!(h.call("git_diff", json!({"filePath":"src/a.txt"})).await.contains("+changed"));
assert!(h.call("git_diff", json!({})).await.contains("src/a.txt"));
assert!(h.call("git_diff", json!({"staged":true})).await.is_empty());
@@ -610,6 +664,19 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
assert!(from_start["output"].as_str().unwrap().contains("hello"), "one log across the tab's commands");
let runs = h.json("list_runs", json!({})).await;
assert_eq!(runs["runs"].as_array().unwrap().len(), 2, "{runs}");
// Newest first, brief, filtered by state and paged.
let newest = h.json("list_runs", json!({"limit": 1})).await;
assert_eq!(
(&newest["runs"][0]["name"], &newest["total"], &newest["nextOffset"]),
(&json!("_agent_server"), &json!(2), &json!(1))
);
assert!(newest["runs"][0].get("outputLength").is_none(), "{newest}");
assert_eq!(h.json("list_runs", json!({"state": "idle"})).await["total"], 2);
assert_eq!(h.json("list_runs", json!({"state": "running"})).await["total"], 0);
assert_eq!(h.json("list_runs", json!({"state": "stoppedByAgent"})).await["total"], 2);
assert_eq!(h.json("list_runs", json!({"state": "error"})).await["total"], 0);
let unknown = h.error("list_runs", json!({"state": "done"})).await;
assert!(unknown.contains("unknown state `done`"), "{unknown}");
let missing = h.error("get_run_status", json!({"name": "nothing"})).await;
assert!(missing.contains("no agent tab named `_agent_nothing`"), "{missing}");
+1
Переглянути файл
@@ -46,6 +46,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
"clear_caches",
"clipboard_file_list",
"clipboard_has_files",
"clipboard_has_image",
"clipboard_image",
"clipboard_set_file_list",
"clipboard_write_text",
+19
Переглянути файл
@@ -207,3 +207,22 @@ async fn change_commit_branch_stash_and_merge_a_conflict() {
assert!(f.status().await.is_empty());
assert_eq!(std::fs::read_to_string(&lib_path).unwrap(), resolved);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn checkout_reports_a_branch_held_by_another_worktree() {
let f = Flow::new("rust-app").await;
let linked = f._tmp.path().join("linked");
git(&f.root, &["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None).await.unwrap();
assert_eq!(
outcome,
ide_vcs::CheckoutOutcome::CheckedOutInWorktree {
branch: "topic".into(),
path: dunce::canonicalize(&linked).unwrap()
}
);
// Nothing changed: the project is still on main.
let branches = ops::vcs::vcs_branches(&f.host, WINDOW, None).await.unwrap();
assert!(branches.iter().any(|b| b.name == "main" && b.current), "{branches:?}");
}
+28 -3
Переглянути файл
@@ -331,8 +331,8 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
#[cfg(not(unix))]
{
let link = bin_dir.join(format!("{command}.cmd"));
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", cmd_path(bin_dir, v))).collect();
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
}
@@ -357,11 +357,25 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
{
let link = bin_dir.join(format!("{command}.cmd"));
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", target.display()))?;
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
Ok(link)
}
}
/// `path` as a `.cmd` shim in `bin_dir` names it: relative to the shim (`%~dp0..\…`) when it
/// is in the tool's own directory. cmd.exe reads a batch file in the console's code page, so
/// an absolute path through a non-ASCII user directory, written as UTF-8, isn't found (#3338).
#[cfg_attr(unix, allow(dead_code))]
fn cmd_path(bin_dir: &Path, path: &Path) -> String {
match bin_dir.parent().and_then(|tool| path.strip_prefix(tool).ok()) {
Some(rest) => {
let rest: Vec<_> = rest.components().map(|c| c.as_os_str().to_string_lossy()).collect();
format!("%~dp0..\\{}", rest.join("\\"))
}
None => path.display().to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -743,6 +757,17 @@ mod tests {
assert!(found.ends_with("server/com.microsoft.java.debug.plugin-0.53.2.jar"));
}
#[test]
fn windows_shims_name_the_tool_relative_to_themselves() {
let tool = Path::new("/Users/张三/AppData/Local/ai.l0ng.openidea/tools/taplo");
let bin = tool.join("bin");
assert_eq!(cmd_path(&bin, &tool.join("taplo.exe")), "%~dp0..\\taplo.exe");
assert_eq!(cmd_path(&bin, &tool.join("gems/bin/solargraph")), "%~dp0..\\gems\\bin\\solargraph");
// Outside the tool's directory (a system SDK) stays absolute.
let sdk = Path::new("/usr/local/share/dotnet");
assert_eq!(cmd_path(&bin, sdk), sdk.display().to_string());
}
#[cfg(unix)]
#[test]
fn wrapper_runs_target() {
+9
Переглянути файл
@@ -496,6 +496,9 @@ pub struct CheckoutOptions {
/// Required when checking out a remote branch whose local namesake is ahead of it.
#[serde(default)]
pub diverged: Option<DivergedLocal>,
/// Check the branch out even though another worktree has it checked out.
#[serde(default)]
pub ignore_other_worktrees: bool,
}
/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
@@ -522,6 +525,12 @@ pub enum CheckoutOutcome {
Conflicts {
files: Vec<String>,
},
/// Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
/// changed; the branch can be worked on there.
CheckedOutInWorktree {
branch: String,
path: PathBuf,
},
}
/// HEAD before and after a history rewrite, for its Undo.
+42 -2
Переглянути файл
@@ -765,6 +765,18 @@ fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
listed_files(stderr, "untracked working tree files would be")
}
/// The branch git refused to check out or update because another worktree has it, from
/// its error message: a switch says `'<branch>' is already used by worktree at '<path>'`,
/// a forced update says `cannot force update the branch '<branch>' used by worktree at
/// '<path>'`; git before 2.42 says `'<branch>' is already checked out at '<path>'`.
fn branch_of_other_worktree(stderr: &str) -> Option<(String, String)> {
const MARKERS: [&str; 3] =
["' is already used by worktree at '", "' used by worktree at '", "' is already checked out at '"];
let (before, path) = stderr.lines().find_map(|l| MARKERS.iter().find_map(|m| l.split_once(m)))?;
let branch = before.rsplit('\'').next()?.to_string();
Some((branch, path.strip_suffix('\'').unwrap_or(path).to_string()))
}
fn listed_files(stderr: &str, header: &str) -> Option<Vec<String>> {
let mut lines = stderr.lines().skip_while(|l| !l.contains(header));
lines.next()?;
@@ -805,12 +817,18 @@ pub(crate) fn checkout_with(
if options.mode == CheckoutMode::Force {
args.push("--discard-changes".into());
}
if options.ignore_other_worktrees {
args.push("--ignore-other-worktrees".into());
}
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
let out = cli::run_raw(r.root(), &argv, None)?;
if out.code == Some(0) {
return Ok(CheckoutOutcome::Done);
}
let stderr = String::from_utf8_lossy(&out.stderr);
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
}
if let Some(files) = overwritten_untracked(&stderr) {
return Ok(CheckoutOutcome::UntrackedFiles { files });
}
@@ -893,7 +911,14 @@ pub(crate) fn create_branch(
args.extend(["--", name]);
}
args.extend(start);
run(r.root(), &args, None).map(|_| ())
let out = cli::run_raw(r.root(), &args, None)?;
if out.code == Some(0) {
return Ok(());
}
if let Some((branch, path)) = branch_of_other_worktree(&String::from_utf8_lossy(&out.stderr)) {
return Err(IdeError::invalid(format!("branch '{branch}' is already checked out in worktree at '{path}'")));
}
Err(cli::failure(&args, &out.stderr, &out.stdout, out.code))
}
/// Whether `start` is a remote-tracking branch with another name than the new branch
@@ -1479,7 +1504,22 @@ fn decode_diff(bytes: &[u8], encoding: TextEncoding) -> String {
#[cfg(test)]
mod tests {
use super::append_revision;
use super::{append_revision, branch_of_other_worktree};
#[test]
fn the_worktree_holding_a_branch_is_read_from_each_git_wording() {
let held = |b: &str, p: &str| Some((b.to_string(), p.to_string()));
assert_eq!(
branch_of_other_worktree("fatal: 'topic' is already used by worktree at '/w/t'\n"),
held("topic", "/w/t")
);
assert_eq!(
branch_of_other_worktree("fatal: cannot force update the branch 'topic' used by worktree at '/w/t'"),
held("topic", "/w/t")
);
assert_eq!(branch_of_other_worktree("fatal: 'a/b' is already checked out at '/w/t'"), held("a/b", "/w/t"));
assert_eq!(branch_of_other_worktree("fatal: invalid reference: x"), None);
}
#[test]
fn a_revision_is_appended_once_keeping_the_list() {
+47 -3
Переглянути файл
@@ -1070,7 +1070,7 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
fx.commit_all("other edit");
fx.git(&["checkout", "-q", "main"]);
let repo = fx.repo();
let opts = |mode| CheckoutOptions { mode, diverged: None };
let opts = |mode| CheckoutOptions { mode, ..Default::default() };
// A non-conflicting local edit to a file the switch rewrites.
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
@@ -1110,6 +1110,50 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
}
#[test]
fn checkout_of_a_branch_held_by_another_worktree_reports_it_and_changes_nothing() {
let fx = Fixture::new();
fx.write("f.txt", "1\n");
fx.commit_all("base");
let linked = fx._tmp.path().join("linked");
fx.git(&["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
let repo = fx.repo();
let none = CheckoutOptions::default();
let linked_path = std::fs::canonicalize(&linked).unwrap();
// From the main worktree, the branch the linked worktree has checked out.
let outcome = repo.checkout_with("topic", false, &none).unwrap();
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
// With local changes in the way too: reported before any Smart Checkout stash.
fx.write("f.txt", "changed\n");
let smart = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
let outcome = repo.checkout_with("topic", false, &smart).unwrap();
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
assert_eq!(fx.read("f.txt"), "changed\n", "local changes untouched");
assert!(repo.stashes().unwrap().is_empty());
fx.git(&["reset", "-q", "--hard"]);
// The same refusal from the linked worktree, for the main worktree's branch.
let linked_repo = Repo::discover(&linked).unwrap().unwrap();
linked_repo.set_execution_allowed(true);
let outcome = linked_repo.checkout_with("main", false, &none).unwrap();
let main_path = std::fs::canonicalize(&fx.dir).unwrap();
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "main".into(), path: main_path });
assert_eq!(linked_repo.branch_info().unwrap().head.as_deref(), Some("topic"));
// Overwriting such a branch (New Branch with Checkout) names the worktree, not raw stderr.
let error = repo.create_branch_with_overwrite("topic", Some("main"), true, true).unwrap_err();
assert!(error.message.contains("branch 'topic' is already checked out in worktree"), "{error}");
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
// Checkout Anyway: both worktrees then have the branch.
let anyway = CheckoutOptions { ignore_other_worktrees: true, ..Default::default() };
assert_eq!(repo.checkout_with("topic", false, &anyway).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
}
#[test]
fn checkout_remote_branch_with_existing_local_namesake() {
let (fx, bare) = with_remote();
@@ -1939,7 +1983,7 @@ fn smart_checkout_keeps_staged_changes_staged() {
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
fx.write("s.txt", "staged\n");
fx.git(&["add", "s.txt"]);
let opts = CheckoutOptions { mode: CheckoutMode::Smart, diverged: None };
let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done);
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n");
@@ -1960,7 +2004,7 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
fx.write("dir/new.txt", "mine\n");
let repo = fx.repo();
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
let opts = CheckoutOptions { mode, diverged: None };
let opts = CheckoutOptions { mode, ..Default::default() };
let outcome = repo.checkout_with("other", false, &opts).unwrap();
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ Once an agent has run a task, new tasks start in its mode that approves everythi
### Review the changes
Click **Show changes** in the task header to list the files the task changed. Click a file to open a diff between the task's starting point and now. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
Drag the pane's left edge to resize it. The width applies to every task and is remembered across restarts.
+1
Переглянути файл
@@ -98,6 +98,7 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i
Notes on what they do:
- `read_file` also reads sources of dependencies and files inside jar and zip archives.
- The tools that list things return one page: `limit` items (100 by default; 50 for `search_symbol`, 10 for `list_runs`), from `offset`. `total` (where counting is cheap), `more` and `nextOffset` say what follows. `list_runs` filters by `state` (`running`, `idle`, `error` or one state), `get_run_configurations` by `query`, and `get_project_problems` lists errors only unless `errorsOnly` is false.
- `search_symbol` and `find_references` use the IDE's index and the language servers; `get_symbol_info` returns what Quick Documentation shows.
- `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis.
- `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed.
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
### 查看改动
在任务标题栏中单击 **显示更改**,列出任务改动过的文件;单击文件可以打开它从任务开始到现在的 diff。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
拖动改动面板的左边缘可以调整宽度。宽度对所有任务生效,重启后保留。
+1
Переглянути файл
@@ -98,6 +98,7 @@ stdio 配置大致如下(路径以你机器上的为准):
- `read_file` 还能读取依赖的源代码,以及 jar 和 zip 压缩包中的文件。
- `search_symbol` 和 `find_references` 使用 IDE 的索引和语言服务器;`get_symbol_info` 返回的内容与快速文档相同。
- 列表类工具每次返回一页:从 `offset` 开始的 `limit` 项(默认 100;`search_symbol` 为 50,`list_runs` 为 10)。`total`(计数代价低的工具才有)、`more` 和 `nextOffset` 说明后面还有多少。`list_runs` 可按 `state` 过滤(`running`、`idle`、`error` 或某个具体状态),`get_run_configurations` 可按 `query` 过滤,`get_project_problems` 默认只列错误,`errorsOnly` 传 false 时也列警告。
- `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。
- `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。
- `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。
+102 -9
Переглянути файл
@@ -372,20 +372,25 @@ test("keeps chat history readable and selections free of timestamps and status l
expect(narrow.reply).toBeLessThanOrEqual((narrow.width - narrow.padding) * 0.96);
});
test("fits conversation stream, composer, question card and user bubbles to window width when enabled", async ({
test("fits conversation stream, composer, question card and off-screen rows live from Settings without restarting", async ({
page,
}) => {
await page.setViewportSize({ width: 1800, height: 1000 });
await page.setViewportSize({ width: 1800, height: 900 });
await openReply(page, "Initial reply");
await page.evaluate(async (task) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
const filler = Array.from({ length: 8 }, (_, i) => ({
type: "agent" as const,
text: `Earlier paragraph ${i + 1}: ` + "wrapped words across the column ".repeat(35),
}));
store.useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "needsInput" as const }]]),
entries: new Map([
[
task.id,
[
...filler,
{
type: "user",
text: "Long prompt ".repeat(40),
@@ -419,11 +424,15 @@ test("fits conversation stream, composer, question card and user bubbles to wind
const stream = page.locator("[class*='_stream_']:visible");
await expect(page.getByRole("form", { name: "Choose layout" })).toBeVisible();
await expect(stream.locator("[data-measured]").first()).toBeAttached();
const measure = () =>
stream.evaluate((root) => {
const conversation = root.closest<HTMLElement>("[class*='_conversation_']")!;
const column = root.querySelector<HTMLElement>("[class*='_agentMessage_']")!.getBoundingClientRect();
const rows = [...root.querySelectorAll<HTMLElement>("[class*='_conversationRow_']")];
const column = [...root.querySelectorAll<HTMLElement>("[class*='_agentMessage_']")]
.at(-1)!
.getBoundingClientRect();
const bubble = root.querySelector<HTMLElement>("[class*='_user_']")!.getBoundingClientRect();
const composer = conversation.querySelector<HTMLElement>("[class*='_composerArea_']")!.getBoundingClientRect();
const question = conversation.querySelector<HTMLElement>("[class*='_questionCard_']")!.getBoundingClientRect();
@@ -436,6 +445,8 @@ test("fits conversation stream, composer, question card and user bubbles to wind
bubbleWidth: bubble.width,
composerWidth: composer.width,
questionWidth: question.width,
offscreenRowHeight: rows[0]!.getBoundingClientRect().height,
scrollHeight: root.scrollHeight,
};
});
@@ -446,14 +457,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
expect(Math.abs(capped.composerWidth - 924)).toBeLessThan(1);
expect(Math.abs(capped.questionWidth - 900)).toBeLessThan(1);
// Toggle on through Settings › Agents › Chat › Apply and verify live re-layout including off-screen rows.
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(projectPath);
const settings = useProject.getState().settings;
useProject.setState({
settings: { ...settings, agents: { ...settings?.agents, fitWindowWidth: true } } as never,
});
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(actionsPath);
await executeAction("file.settings", "agents.chat");
});
const dialog = page.getByRole("dialog", { name: "Settings" });
const toggle = dialog.getByRole("checkbox", { name: "Fit conversation to the window width" });
await expect(toggle).not.toBeChecked();
await toggle.click();
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(stream.locator("[data-measured]").first()).toBeAttached();
const fitted = await measure();
expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1);
@@ -461,6 +476,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1);
expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1);
expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1);
expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight);
expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight);
// Toggle back off and click OK: dialog closes and conversation returns to the 900px column live.
await toggle.click();
await dialog.getByRole("button", { name: "OK", exact: true }).click();
await expect(dialog).toBeHidden();
await expect(stream.locator("[data-measured]").first()).toBeAttached();
const restored = await measure();
expect(Math.abs(restored.columnWidth - 900)).toBeLessThan(1);
expect(Math.abs(restored.offscreenRowHeight - capped.offscreenRowHeight)).toBeLessThan(1);
});
test("keeps hover actions reachable when the pointer leaves the message body", async ({ page, context }) => {
@@ -668,3 +695,69 @@ test("draws a diagram without reaching the hosts its configuration names", async
);
expect(asked).toEqual(["/after"]);
});
test("Find in Conversation skips user-select:none summaries and closed <details> until stepped into", async ({
page,
}) => {
await openReply(page, "Confirmed—PR is merged.");
await page.evaluate(async (task) => {
const path = "/src/features/agents/store.ts";
const store = await import(path);
store.useAgents.setState({
entries: new Map([
[
task.id,
[
{
type: "thought",
text: "**Confirming Active Watch Shell**\n\nCheck background shell before rebasing.",
},
{
type: "tool",
id: "t1",
title: "stop_bash",
kind: "other",
status: "completed",
locations: [],
output: "<command with id: 60 had already stopped>",
diffs: [],
},
{ type: "agent", text: "Confirmed—PR is merged." },
],
],
]),
});
store.openTaskInEditorLocation(task.id);
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
await runSummary.click();
await expect(stream.getByText("stop_bash")).toBeVisible();
await stream.focus();
await page.keyboard.press("Meta+f");
const findBox = page.getByLabel("Find in Conversation");
await findBox.fill("confirm");
// 2 matches total (1 inside collapsed thought body, 1 in visible reply); unselectable <summary> is excluded.
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
const initialHighlights = await page.evaluate(() => ({
find: [...(CSS.highlights.get("agent-find") ?? [])].map((r) => (r as Range).startContainer.textContent),
current: [...(CSS.highlights.get("agent-find-current") ?? [])].map((r) => (r as Range).startContainer.textContent),
}));
expect(initialHighlights.find).toEqual(["Confirmed—PR is merged."]);
expect(initialHighlights.current).toEqual([]);
// Stepping to match 2/2 opens the collapsed thought <details> and highlights it.
await findBox.press("Enter");
await expect(page.locator("[class*='_findCount_']")).toHaveText("2/2");
await findBox.press("Enter");
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
const expandedHighlights = await page.evaluate(() => ({
thoughtOpen: document.querySelector<HTMLDetailsElement>("details[class*='_thought_']")?.open,
findCount: CSS.highlights.get("agent-find")?.size ?? 0,
currentCount: CSS.highlights.get("agent-find-current")?.size ?? 0,
}));
expect(expandedHighlights).toEqual({ thoughtOpen: true, findCount: 2, currentCount: 1 });
});
+52
Переглянути файл
@@ -98,6 +98,58 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(() => {
const item = (label: string) => ({
label,
labelDetail: "()",
detail: "Unit",
kind: "method",
documentation: { kind: "markdown", value: `Docs for **${label}**.` },
sortText: null,
filterText: null,
preselect: false,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_completion = () => ({
isIncomplete: false,
items: [item("service"), item("serviceName"), item("setUp")],
});
window.__ipc.handlers.lsp_hover = () => ({
contents: { kind: "markdown", value: "Docs for **service**." },
range: null,
});
});
const geometry = await editor.locator(".cm-content").evaluate(async (content) => {
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const view = EditorView.findFromDOM(content as HTMLElement)!;
const find = view.state.doc.toString().indexOf("find");
if (find < 0 || !view.coordsAtPos(find)) throw new Error('the fixture has no visible "find"');
const word = view.coordsAtPos(find)!;
view.dispatch({ selection: { anchor: find + 5 } });
view.focus();
return { wordX: word.left + 2, wordY: (word.top + word.bottom) / 2 };
});
await page.mouse.move(geometry.wordX, geometry.wordY);
const tooltip = page.locator(".cm-tooltip-hover");
await expect(tooltip).toBeVisible();
await page.keyboard.type("se");
const popup = page.locator(".cm-tooltip-autocomplete");
await expect(popup.getByText("service", { exact: true })).toBeVisible();
await expect(tooltip).toHaveCount(0);
});
for (const key of ["Enter", "Tab"]) {
for (const prefix of ["", "v"]) {
test(`${key} leaves the caret after a field snippet at root.${prefix}`, async ({ workbench: page }, info) => {
+64 -2
Переглянути файл
@@ -174,12 +174,36 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
});
test("Markdown preview highlights ⌘F matches and selected word occurrences", async ({ workbench: page }) => {
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const svg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 96" width="320" height="96"><!-- svg-source:excalidraw --><rect width="320" height="96"/></svg>';
const url = `data:image/svg+xml;base64,${btoa(svg)}`;
const routeModule = "/src/platform/tauriCore.ts";
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(url) : null));
});
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("# Order Service\n\nManage **Order** items and `Order` status.\n");
await page.keyboard.insertText(
[
"# Order Service",
"",
"Manage **Order** items and `Order` status.",
"",
"```mermaid",
"flowchart LR",
" A --> B",
"```",
"",
"![Diagram](./arch.excalidraw.svg)",
].join("\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(preview).toContainText("Manage Order items");
@@ -209,6 +233,44 @@ test("Markdown preview highlights ⌘F matches and selected word occurrences", a
})),
)
.toEqual({ current: ["Order"], other: ["Order", "Order"] });
const mermaidSvg = preview.locator(".mermaid-output svg");
const excalidrawImg = preview.locator('img[alt="Diagram"]');
await expect(mermaidSvg).toBeVisible();
await expect(excalidrawImg).toHaveAttribute("src", /^data:image\/svg\+xml/);
const widths = async () => ({
mermaid: (await mermaidSvg.boundingBox())!.width,
excalidraw: (await excalidrawImg.boundingBox())!.width,
});
const base = await widths();
expect(base.mermaid).toBeGreaterThan(50);
expect(base.excalidraw).toBeCloseTo(320, 0);
const runAction = (id: string, times = 1) =>
page.evaluate(
async ({ id, times }) => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
for (let i = 0; i < times; i++) await executeAction(id);
},
{ id, times },
);
await runAction("editor.increaseFontSize", 4);
const zoomedIn = await widths();
expect(zoomedIn.mermaid / base.mermaid).toBeCloseTo(17 / 13, 2);
expect(zoomedIn.excalidraw / base.excalidraw).toBeCloseTo(17 / 13, 2);
await runAction("editor.decreaseFontSize", 6);
const zoomedOut = await widths();
expect(zoomedOut.mermaid / base.mermaid).toBeCloseTo(11 / 13, 2);
expect(zoomedOut.excalidraw / base.excalidraw).toBeCloseTo(11 / 13, 2);
await runAction("editor.resetFontSize");
const reset = await widths();
expect(reset.mermaid).toBeCloseTo(base.mermaid, 1);
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
+17 -9
Переглянути файл
@@ -76,15 +76,26 @@ pub async fn clipboard_set_file_list(app: AppHandle, paths: Vec<PathBuf>) -> Ide
with_clipboard(app, move || Ok(ide_clipboard::set_files(&paths))).await
}
/// The clipboard's image as a PNG data URL, for a paste whose event carried no
/// files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
/// None when the clipboard holds no image, and always on other platforms.
/// Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
/// enabled state.
#[tauri::command]
#[specta::specta]
pub fn clipboard_has_image() -> bool {
// Synchronous Tauri commands run on the main thread, as macOS and GTK require.
ide_clipboard::has_image()
}
/// The clipboard's image as a PNG data URL: for a paste whose event carried no files
/// (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
/// the project view's Paste, which has no paste event. None when it holds no image.
#[tauri::command]
#[specta::specta]
pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
use base64::Engine;
let data_url =
|bytes: Vec<u8>| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
#[cfg(target_os = "linux")]
{
use base64::Engine;
let (tx, rx) = tokio::sync::oneshot::channel();
app.run_on_main_thread(move || {
let sender = std::cell::Cell::new(Some(tx));
@@ -98,14 +109,11 @@ pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
.map_err(|error| {
ide_core::IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}"))
})?;
let png = rx.await.ok().flatten();
Ok(png
.map(|bytes| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))))
Ok(rx.await.ok().flatten().map(data_url))
}
#[cfg(not(target_os = "linux"))]
{
let _ = app;
Ok(None)
Ok(with_clipboard(app, || Ok(ide_clipboard::png())).await?.map(data_url))
}
}
+1
Переглянути файл
@@ -195,6 +195,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
clipboard::clipboard_text,
clipboard::clipboard_file_list,
clipboard::clipboard_has_files,
clipboard::clipboard_has_image,
clipboard::clipboard_image,
clipboard::clipboard_set_file_list,
fonts::system_font_families,
+18 -4
Переглянути файл
@@ -310,9 +310,14 @@ export const commands = {
/** Whether the clipboard holds files: cheap, for the Paste item's enabled state. */
clipboardHasFiles: () => __TAURI_INVOKE<boolean>("clipboard_has_files"),
/**
* The clipboard's image as a PNG data URL, for a paste whose event carried no
* files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
* None when the clipboard holds no image, and always on other platforms.
* Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
* enabled state.
*/
clipboardHasImage: () => __TAURI_INVOKE<boolean>("clipboard_has_image"),
/**
* The clipboard's image as a PNG data URL: for a paste whose event carried no files
* (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
* the project view's Paste, which has no paste event. None when it holds no image.
*/
clipboardImage: () => typedError<string | null, IdeError>(__TAURI_INVOKE("clipboard_image")),
/**
@@ -708,6 +713,8 @@ export const commands = {
mode?: CheckoutMode,
/** Required when checking out a remote branch whose local namesake is ahead of it. */
diverged?: DivergedLocal | null,
/** Check the branch out even though another worktree has it checked out. */
ignoreOtherWorktrees?: boolean,
} | null) => typedError<CheckoutOutcome, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })),
vcsDeleteBranch: (repo: string | null, branch: string) => typedError<DeletedBranch, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })),
/** "Restore" of the branch-deleted notification. */
@@ -2980,6 +2987,8 @@ export type CheckoutOptions = {
mode?: CheckoutMode,
/** Required when checking out a remote branch whose local namesake is ahead of it. */
diverged?: DivergedLocal | null,
/** Check the branch out even though another worktree has it checked out. */
ignoreOtherWorktrees?: boolean,
};
/**
@@ -2997,7 +3006,12 @@ export type CheckoutOutcome = { kind: "done" } |
* Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
* on conflicts in these files.
*/
{ kind: "conflicts"; files: string[] };
{ kind: "conflicts"; files: string[] } |
/**
* Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
* changed; the branch can be worked on there.
*/
{ kind: "checkedOutInWorktree"; branch: string; path: string };
export type ChoiceOption = {
value: string,
+25 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DocModel } from "./model/document";
import { readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
import { offerMakeWritable, readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
function model(readOnly: boolean, extra: Partial<{ virtual: boolean; banner: string | null }> = {}) {
const meta = { readOnly, banner: extra.banner ?? (readOnly ? "readOnly" : null) };
@@ -43,3 +43,27 @@ describe("Toggle Read-only Attribute", () => {
expect(readOnlyQuestion("a.txt", false).confirm).toBe("Make Read-only");
});
});
describe("editing a read-only file", () => {
it("offers to make it writable once, then lets edits through", async () => {
const m = model(true);
answer = true;
expect(offerMakeWritable(m)).toBe(true);
expect(offerMakeWritable(m)).toBe(true);
expect(confirm).toHaveBeenCalledTimes(1);
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Writable" }));
await vi.waitFor(() => expect(m.setReadOnly).toHaveBeenCalledWith(false));
expect(offerMakeWritable(m)).toBe(false);
});
it("refuses edits without asking for library, binary and too-large documents", () => {
for (const m of [
model(true, { virtual: true }),
model(true, { banner: "binary" }),
model(true, { banner: "tooLarge" }),
])
expect(offerMakeWritable(m)).toBe(true);
expect(confirm).not.toHaveBeenCalled();
expect(offerMakeWritable(model(false))).toBe(false);
});
});
+21 -1
Переглянути файл
@@ -1,7 +1,8 @@
/**
* File › File Properties › Make File Read-only / Writable (IDEA's "Toggle
* Read-only Attribute", also the status bar lock): asks, then flips the
* file's writable bit and the open document's editability.
* file's writable bit and the open document's editability. Typing into a file
* whose read-only attribute is set asks the same (IDEA's Clear Read-Only Status).
*/
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
@@ -41,3 +42,22 @@ export function toggleReadOnly(model: DocModel) {
(ok) => ok && void setFileWritable(model, meta.readOnly),
);
}
let asking: DocModel | null = null;
/**
* An edit was attempted in `model`. When only the file's read-only attribute is in the
* way (not a binary, too large or library file), offers to make it writable, once at a
* time. Returns whether the edit was refused: the caller drops it either way.
*/
export function offerMakeWritable(model: DocModel): boolean {
const meta = model.getMeta();
if (!meta.readOnly) return false;
if (model.virtual || meta.banner !== "readOnly" || asking) return true;
asking = model;
const q = readOnlyQuestion(basename(model.path), true);
void confirm({ title: q.title, message: q.message, ok: q.confirm })
.then((ok) => ok && model.getMeta().readOnly && setFileWritable(model, true))
.finally(() => (asking = null));
return true;
}
+11
Переглянути файл
@@ -34,6 +34,7 @@ import {
import { showContextMenu } from "@/ui";
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
import { offerMakeWritable } from "../fileAttributes";
import type { DocModel } from "./document";
import type { WorkspaceHistoryTarget } from "./workspaceHistory";
import { isNavigation } from "./navHistory";
@@ -147,6 +148,12 @@ export class EditorSlot {
return this.state;
}
private refuseReadOnlyEdit(e: Event): boolean {
if (!offerMakeWritable(this.model)) return false;
e.preventDefault();
return true;
}
private slotExtensions() {
return [
this.model.manager.workspaceHistory.extension(this.historyTarget),
@@ -169,6 +176,10 @@ export class EditorSlot {
this.host.onContextMenu(this, e);
return true;
},
// Typing, pasting or dropping into a read-only file offers to make it writable.
beforeinput: (e) => this.refuseReadOnlyEdit(e),
paste: (e) => this.refuseReadOnlyEdit(e),
drop: (e) => this.refuseReadOnlyEdit(e),
}),
ViewPlugin.define((view) => {
// Gutters sit outside the content DOM. Gutter extensions with their own menu (breakpoints,
+28 -1
Переглянути файл
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState, StateEffect, type Extension } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import type { CompletionItem } from "@/bindings";
import type { EditorDocContext } from "@/editor/api";
import { remoteChange, type EditorDocContext } from "@/editor/api";
import { lspDoc } from "./lsp";
import { insertTab, tabOut, tabOutOfScope } from "@/editor/core/cm/smartKeys";
import {
@@ -294,6 +294,32 @@ describe("applying completions", () => {
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
});
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
const executed: string[] = [];
setInvokeRoute((cmd) => {
executed.push(cmd);
return Promise.resolve(null);
});
try {
const { view, req } = setup("p.ref|\n", "", [completionExtension()]);
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
// kotlin-lsp: an empty text, inserted by `jetbrains.kotlin.completion.apply` as a workspace edit.
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command });
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
expect(view.state.doc.toString()).toBe("p.ref\n");
await vi.waitFor(() => expect(executed).toContain("lsp_execute_command"));
view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) });
expect(view.state.doc.toString()).toBe("p.refreshName()\n");
expect(view.state.selection.main.head).toBe(15);
// Later edits from elsewhere leave the caret alone.
view.dispatch({ changes: { from: 15, insert: " " }, annotations: remoteChange.of(true) });
expect(view.state.selection.main.head).toBe(15);
} finally {
setInvokeRoute(null);
}
});
it("does not register a scope when jumping outside closing brackets is off", () => {
const { view, req } = setup("service.cr|");
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
@@ -532,6 +558,7 @@ describe("insert parentheses", () => {
expect(callParens(item({ kind: "field" }), line("a.cr"), 2, 4)).toBeNull();
expect(callParens(item({ isSnippet: true }), line("a.cr"), 2, 4)).toBeNull();
expect(callParens(item({ insertText: "create()" }), line("a.cr"), 2, 4)).toBeNull();
expect(callParens(item({ insertText: "" }), line("a.cr"), 4, 4)).toBeNull();
});
it("skips calls that already have parentheses and imports", () => {
+49 -5
Переглянути файл
@@ -24,7 +24,7 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorSelection, Prec, type Text } from "@codemirror/state";
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
import {
call,
@@ -58,6 +58,7 @@ import { tx } from "@/platform/i18n";
import { showHint } from "./hint";
import { inplaceRenameActive } from "./inplaceRename";
import { languageSemantics } from "./semantic";
import { remoteChange } from "@/editor/api";
interface RequestContext {
doc: number;
@@ -297,7 +298,9 @@ export function callParens(
start: number,
end: number,
): "inside" | "after" | null {
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || /[(<[{]/.test(item.insertText)) return null;
// An empty text is inserted by the item's server command (kotlin-lsp), parentheses included.
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || !item.insertText || /[(<[{]/.test(item.insertText))
return null;
const next = line.text.charAt(end - line.from);
if (next && /[(\p{L}\p{N}_$'"`]/u.test(next)) return null;
if (IMPORT_LINE.test(line.text.slice(0, start - line.from))) return null;
@@ -322,6 +325,33 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
view.dispatch({ changes: edits, userEvent: "input.complete" });
}
/** Where the caret was when an item its server inserts was picked, until that edit lands (`null`: none). */
const awaitServerInsert = StateEffect.define<number | null>();
const serverInsertAt = StateField.define<number | null>({
create: () => null,
update(at, tr) {
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
// The edit landed, or the caret moved on before it did.
if (at === null || tr.annotation(remoteChange) || tr.selection) return null;
return tr.changes.mapPos(at, -1);
},
});
/**
* The server's edit inserts the item at the caret: the caret goes after it, as after any other
* completion (a remote insertion at the caret would otherwise leave it in front).
*/
const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
const at = tr.startState.field(serverInsertAt, false);
const caret = tr.startState.selection.main;
if (at == null || !tr.docChanged || !tr.annotation(remoteChange) || !caret.empty || caret.head !== at) return tr;
let inserted = false;
tr.changes.iterChangedRanges((fromA, toA) => {
if (fromA <= at && toA >= at) inserted = true;
});
return inserted ? [tr, { selection: EditorSelection.cursor(tr.changes.mapPos(at, 1)), sequential: true }] : tr;
});
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
@@ -329,18 +359,30 @@ function runCommand(view: EditorView, item: CompletionItem) {
const command = item.command;
if (!command?.command) return;
const cmd = command.command;
// kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing went in here.
const serverInserted = !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.");
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of(view.state.selection.main.head) });
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
const doc = docOf(view);
// Server commands (auto-import, postfix…); resulting edits come back as workspace/applyEdit.
if (doc)
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command)).catch((e: unknown) =>
reportLspError(view, e, false),
);
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command))
.catch((e: unknown) => reportLspError(view, e, false))
.finally(() => {
// The edit arrives before the command's answer; allow for the document update.
if (serverInserted)
setTimeout(() => {
if (view.dom.isConnected && view.state.field(serverInsertAt, false) != null)
view.dispatch({ effects: awaitServerInsert.of(null) });
}, SERVER_INSERT_WAIT_MS);
});
}
}
const SERVER_INSERT_WAIT_MS = 1000;
// ---------------------------------------------------------------------------
// Source
@@ -828,6 +870,8 @@ export function completionExtension() {
}),
completionFooter,
lookupTracker,
serverInsertAt,
caretAfterServerInsert,
Prec.highest(
keymap.of([
// macOS: ⌃N / ⌃P are line down / up in text, so they move through the lookup as ↓ / ↑ do.
+4 -1
Переглянути файл
@@ -216,7 +216,10 @@ const hoverYieldsToNavigation = ViewPlugin.fromClass(
export function hoverExtension(): Extension {
return [
hoverTooltip(hoverSource, { hoverTime: Math.max(100, editorPrefs().codeEditing.quickDocDelay) }),
hoverTooltip(hoverSource, {
hoverTime: Math.max(100, editorPrefs().codeEditing.quickDocDelay),
hideOnChange: true,
}),
hoverYieldsToNavigation,
];
}
+40 -21
Переглянути файл
@@ -81,7 +81,7 @@ import {
} from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { useEffortFocus } from "./effortFocus";
import { findRanges, formatDuration, formatSentAt } from "./conversation";
import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation";
import { ImagePreview, imageSrc } from "./ImagePreview";
import { useAgentSettings } from "./agentSettings";
import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline";
@@ -594,10 +594,15 @@ function SubagentBar({
* doesn't jump (WebKit has no scroll anchoring). A new width lays them out again once it
* settles; Find in Conversation (`enabled` false) needs every row laid out.
*/
function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean, enabled: boolean) {
// The width the marked rows were laid out at.
const width = useRef(0);
useEffect(() => {
function useOffscreenRows(
ref: RefObject<HTMLElement | null>,
visible: boolean,
enabled: boolean,
fitWindowWidth: boolean,
) {
// The container width and column mode the marked rows were laid out at.
const measured = useRef<{ width: number; fitWindowWidth: boolean } | null>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const unmark = () => {
@@ -605,10 +610,26 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
row.removeAttribute("data-measured");
}
};
if (!enabled) return unmark();
if (!enabled) {
measured.current = null;
unmark();
return;
}
if (!visible) return;
if (measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth) return;
measured.current = { width: el.clientWidth, fitWindowWidth };
unmark();
}, [ref, visible, enabled, fitWindowWidth]);
useEffect(() => {
const el = ref.current;
if (!el || !enabled || !visible) return;
let frame = 0;
let timer: number | undefined;
const unmark = () => {
for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}[data-measured]`)) {
row.removeAttribute("data-measured");
}
};
const mark = () => {
cancelAnimationFrame(frame);
// The next frame lays the new rows out (and remembers their size); mark them after it.
@@ -621,8 +642,8 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
});
};
const remeasure = () => {
if (el.clientWidth === width.current) return;
width.current = el.clientWidth;
if (measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth) return;
measured.current = { width: el.clientWidth, fitWindowWidth };
unmark();
};
remeasure();
@@ -643,7 +664,7 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
rows.disconnect();
resize.disconnect();
};
}, [ref, visible, enabled]);
}, [ref, visible, enabled, fitWindowWidth]);
}
interface StreamProps {
@@ -765,7 +786,8 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
}, [start]);
// Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again.
const visible = useEditorShown();
useOffscreenRows(ref, visible, !finding);
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
useOffscreenRows(ref, visible, !finding, fitWindowWidth);
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
@@ -874,7 +896,6 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
const busy = subagent ? subagentWorking(subagent.status) : isBusy(task.status);
const lastIndex = entries ? entries.length - 1 : -1;
// Keep the row stable when earlier history is prepended; its author can move with the work.
const { foldTurns, toolCalls } = useAgentSettings();
const rows = useMemo(() => {
if (!entries) return [];
const rows = conversationRows(entries, start, toolCalls === "grouped");
@@ -1121,14 +1142,9 @@ interface RangeSet {
clear(): void;
add(range: Range): void;
}
const highlights = (globalThis as { CSS?: { highlights?: Map<string, RangeSet> } }).CSS?.highlights;
const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight;
/**
* Sets the ranges of highlight `name`. One registered highlight per name, changed in
* place: WebKit doesn't repaint where a replaced highlight object was.
*/
function setHighlight(name: string, ranges: Range[]) {
const highlights = (globalThis as { CSS?: { highlights?: Map<string, RangeSet> } }).CSS?.highlights;
const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight;
if (!highlights || !HighlightCtor) return;
let set = highlights.get(name);
if (!set) {
@@ -1204,12 +1220,15 @@ function FindBar({
return () => stream?.removeEventListener("toggle", toggled, true);
}, [streamRef]);
useEffect(() => {
// Only rendered matches: WebKit paints those in collapsed <details> over the text next to them.
const visible = (r: Range) => r.getClientRects().length > 0;
const stream = streamRef.current;
if (!stream) return;
// Only rendered selectable matches outside closed <details>: WebKit paints unrendered
// or user-select:none ranges in CSS.highlights over the next selectable row instead.
const visible = (r: Range) => isFindRangeShown(r, stream);
const current = index >= 0 ? ranges[index]! : null;
setHighlight("agent-find", ranges.filter(visible));
setHighlight("agent-find-current", current && visible(current) ? [current] : []);
}, [ranges, index, shown]);
}, [ranges, index, shown, streamRef]);
useEffect(
() => () => {
setHighlight("agent-find", []);
+34 -1
Переглянути файл
@@ -1,5 +1,14 @@
import { describe, expect, it } from "vitest";
import { fileHref, findAll, findRanges, formatDuration, pathLink, quoteText, withQuote } from "./conversation";
import {
fileHref,
findAll,
findRanges,
formatDuration,
isFindRangeShown,
pathLink,
quoteText,
withQuote,
} from "./conversation";
describe("quoting", () => {
it("quotes each line and leaves a line to type on", () => {
@@ -84,4 +93,28 @@ describe("finding", () => {
expect(findRanges(root, "one").map((r) => r.toString())).toEqual(["one", "one"]);
expect(findRanges(root, "TWO")).toHaveLength(1);
});
it("skips user-select:none chrome, buttons, svgs and mermaid source, and hides ranges in closed <details>", () => {
const root = document.createElement("div");
root.innerHTML = [
'<details><summary style="user-select: none">Confirming summary</summary><div>hidden confirm body</div></details>',
"<details><summary>stop_bash confirm</summary><pre>tool confirm output</pre></details>",
"<button>confirm button</button>",
"<svg><text>confirm svg</text></svg>",
'<div data-mermaid-state="ok"><pre><code>graph TD; confirm</code></pre></div>',
"<p>Visible confirm</p>",
].join("");
const ranges = findRanges(root, "confirm");
expect(ranges.map((r) => r.startContainer.parentElement?.tagName)).toEqual(["DIV", "SUMMARY", "PRE", "P"]);
// Simulate WebKit's content-visibility: hidden on closed <details>, where getClientRects() stays non-empty.
for (const r of ranges) r.getClientRects = () => [new DOMRect(0, 0, 10, 10)] as unknown as DOMRectList;
expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual(
["SUMMARY", "P"],
);
for (const d of root.querySelectorAll("details")) d.open = true;
expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual(
["DIV", "SUMMARY", "PRE", "P"],
);
});
});
+44 -2
Переглянути файл
@@ -93,11 +93,36 @@ export function findAll(text: string, query: string): number[] {
return out;
}
/** DOM ranges of `query` in the text under `root` (matches within one text node). */
const SKIP_FIND_TAGS = new Set(["STYLE", "SCRIPT", "NOSCRIPT", "SVG", "BUTTON"]);
function isUnselectable(el: Element): boolean {
const style = getComputedStyle(el);
return style.userSelect === "none" || style.webkitUserSelect === "none";
}
/**
* DOM ranges of `query` in the selectable text under `root` (matches within one text node).
* Skips `user-select: none` chrome (`.thought summary`, `.processSummary`, `.messageTime`,
* `.role`…): WebKit's `CSS.highlights` skips unselectable text renderers and paints the
* highlight over the next selectable text node instead.
*/
export function findRanges(root: Node, query: string): Range[] {
const out: Range[] = [];
if (!query) return out;
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
acceptNode(node) {
if (node.nodeType === Node.ELEMENT_NODE) {
const el = node as Element;
const tag = el.tagName.toUpperCase();
if (SKIP_FIND_TAGS.has(tag)) return NodeFilter.FILTER_REJECT;
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok")
return NodeFilter.FILTER_REJECT;
if (isUnselectable(el)) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_SKIP;
}
return NodeFilter.FILTER_ACCEPT;
},
});
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
for (const at of findAll(node.textContent ?? "", query)) {
const range = document.createRange();
@@ -108,3 +133,20 @@ export function findRanges(root: Node, query: string): Range[] {
}
return out;
}
/**
* True when `range` is rendered on screen and not inside a collapsed `<details>` or
* `user-select: none` subtree. WebKit hides closed `<details>` bodies with
* `content-visibility: hidden` (where `getClientRects()` stays non-empty once opened)
* and forwards unrendered or unselectable `CSS.highlights` ranges onto adjacent rows.
*/
export function isFindRangeShown(range: Range, root: Node): boolean {
for (let el = range.startContainer.parentElement; el && el !== root; el = el.parentElement) {
if (isUnselectable(el)) return false;
if (el instanceof HTMLDetailsElement && !el.open) {
const summary = el.querySelector(":scope > summary");
if (!summary?.contains(range.startContainer)) return false;
}
}
return range.getClientRects().length > 0;
}
+105 -38
Переглянути файл
@@ -540,20 +540,60 @@ describe("opened runs", () => {
});
describe("folded content", () => {
it("is rendered for Find in Conversation, so its text is found", async () => {
backend.entries.set("A", [
tool("one", { output: "needle in a tool output" }),
tool("two"),
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
const summary = await screen.findByText("Read 2 files");
expect(screen.queryByText("needle in a tool output")).toBeNull();
fireEvent.focus(summary);
act(() => focusedSession()!.openFind());
expect(await screen.findByText("needle in a tool output")).toBeInTheDocument();
expect(summary.closest("details")!.open).toBe(false);
it("is rendered for Find in Conversation without painting closed <details> highlights until stepped into", async () => {
const rectSpy = vi
.spyOn(Range.prototype, "getClientRects")
.mockImplementation(() => [new DOMRect(0, 0, 20, 12)] as unknown as DOMRectList);
const prevCss = (globalThis as { CSS?: unknown }).CSS;
const prevHighlight = (globalThis as { Highlight?: unknown }).Highlight;
const highlights = new Map<string, Set<Range>>();
if (typeof prevHighlight === "undefined") {
(globalThis as { Highlight?: unknown }).Highlight = Set;
}
if (!(prevCss as { highlights?: unknown } | undefined)?.highlights) {
(globalThis as { CSS?: unknown }).CSS = {
...(typeof prevCss === "object" && prevCss ? prevCss : {}),
highlights,
};
}
try {
backend.entries.set("A", [
{ type: "thought", text: "Reviewing Changes\n\nConfirm the branch state before rebasing." },
tool("one", { title: "stop_bash", output: "stopped" }),
{ type: "agent", text: "Confirmed—PR is merged." },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
const runSummary = await screen.findByText("Read 1 file");
const runDetails = runSummary.closest("details")!;
runDetails.open = true;
fireEvent(runDetails, new Event("toggle"));
const thoughtDetails = (await screen.findByText("Reviewing Changes")).closest("details")!;
expect(thoughtDetails.open).toBe(false);
fireEvent.focus(runSummary);
act(() => focusedSession()!.openFind());
const findBox = await screen.findByLabelText("Find in Conversation");
fireEvent.change(findBox, { target: { value: "confirm" } });
const registry = (globalThis as unknown as { CSS: { highlights: Map<string, Set<Range>> } }).CSS.highlights;
await waitFor(() => expect(screen.getByText("1/2")).toBeInTheDocument());
await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(1));
expect([...(registry.get("agent-find") ?? [])][0]!.startContainer.textContent).toContain("Confirmed");
expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(0);
fireEvent.keyDown(findBox, { key: "Enter" });
fireEvent.keyDown(findBox, { key: "Enter" });
fireEvent(thoughtDetails, new Event("toggle"));
expect(thoughtDetails.open).toBe(true);
await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(2));
expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(1);
} finally {
rectSpy.mockRestore();
(globalThis as { CSS?: unknown }).CSS = prevCss;
(globalThis as { Highlight?: unknown }).Highlight = prevHighlight;
}
});
});
@@ -1817,30 +1857,57 @@ describe("meters in the task header", () => {
expect(screen.getByText("$0.42")).toBeInTheDocument();
});
it("toggles fitWidth on the session root from settings.agents.fitWindowWidth", () => {
const { container } = render(<SessionEditor input={input("A")} />);
const root = container.querySelector(`.${styles.session}`)!;
expect(root).not.toHaveClass(styles.fitWidth!);
act(() =>
useProject.setState({
settings: {
agents: {
fitWindowWidth: true,
},
} as never,
}),
);
expect(root).toHaveClass(styles.fitWidth!);
act(() =>
useProject.setState({
settings: {
agents: {
fitWindowWidth: false,
},
} as never,
}),
);
expect(root).not.toHaveClass(styles.fitWidth!);
it("toggles fitWidth on the session root and remeasures off-screen rows from settings.agents.fitWindowWidth", async () => {
const frames: FrameRequestCallback[] = [];
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
frames.push(cb);
return frames.length;
});
const flushFrames = () => {
for (let pass = 0; pass < 2; pass++) {
for (const cb of frames.splice(0)) cb(performance.now());
}
};
try {
const { container } = render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const root = container.querySelector(`.${styles.session}`)!;
const row = container.querySelector(`.${styles.conversationRow}`)!;
act(flushFrames);
expect(root).not.toHaveClass(styles.fitWidth!);
expect(row).toHaveAttribute("data-measured");
act(() =>
useProject.setState({
settings: {
agents: {
fitWindowWidth: true,
},
} as never,
}),
);
expect(root).toHaveClass(styles.fitWidth!);
// Cleared synchronously before paint so content-visibility doesn't keep the 900px intrinsic height.
expect(row).not.toHaveAttribute("data-measured");
act(flushFrames);
expect(row).toHaveAttribute("data-measured");
act(() =>
useProject.setState({
settings: {
agents: {
fitWindowWidth: false,
},
} as never,
}),
);
expect(root).not.toHaveClass(styles.fitWidth!);
expect(row).not.toHaveAttribute("data-measured");
act(flushFrames);
expect(row).toHaveAttribute("data-measured");
} finally {
raf.mockRestore();
}
});
it("hides the status-bar Terminal button in the local checkout and opens the worktree's terminal otherwise", async () => {
+1 -1
Переглянути файл
@@ -303,6 +303,6 @@ describe("closing the hierarchy tab", () => {
useHierarchy.setState({ root: { name: "Number", path: "/p/Number.java", line: 0, col: 0 } as never });
closeHierarchy();
expect(useHierarchy.getState().root).toBeNull();
expect(hide).toHaveBeenCalledWith("hierarchy");
expect(hide).toHaveBeenCalledWith("hierarchy", { removeFromStripe: true });
});
});
+2 -2
Переглянути файл
@@ -92,10 +92,10 @@ export function resetHierarchy() {
}));
}
/** Closes the hierarchy's content tab; with no content left the tool window hides. */
/** Closes the hierarchy's content tab; with no content left the tool window and its stripe button go. */
export function closeHierarchy() {
resetHierarchy();
toolWindowService().hide("hierarchy");
toolWindowService().hide("hierarchy", { removeFromStripe: true });
}
/** The empty-result line of the hierarchy tree. */
+24 -3
Переглянути файл
@@ -1,9 +1,10 @@
import { describe, expect, it, vi } from "vitest";
const show = vi.fn();
const hide = vi.fn();
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
toolWindowService: () => ({ show }),
toolWindowService: () => ({ show, hide }),
}));
/** The editor at the caret (`null`: a search from outside an editor). */
let caretView: import("@codemirror/view").EditorView | null = null;
@@ -35,8 +36,16 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
const { registerDocumentIndexSync } = await import("@/workbench/contributions");
const { activeUsageSearch, findUsages, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
await import("./usages");
const {
activeUsageSearch,
closeUsageTab,
findUsages,
openUsageTab,
pinUsageTab,
resetUsages,
showUsageResults,
useUsages,
} = await import("./usages");
describe("showUsageResults", () => {
it("shows given usages in the Find Usages tool window", async () => {
@@ -221,4 +230,16 @@ describe("usage tabs", () => {
openUsageTab(search(104));
expect(useUsages.getState().tabs.map((t) => t.id)).toEqual([102, 104]);
});
it("take the tool window and its stripe button away with the last one", () => {
resetUsages();
hide.mockClear();
openUsageTab(search(201));
pinUsageTab(201, true);
openUsageTab(search(202));
closeUsageTab(201);
expect(hide).not.toHaveBeenCalled();
closeUsageTab(202);
expect(hide).toHaveBeenCalledWith("usages", { removeFromStripe: true });
});
});
+8
Переглянути файл
@@ -168,6 +168,14 @@ export function closeUsageTab(id: number) {
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
return { tabs, active };
});
// As in IDEA, the tool window and its stripe button go away with its last tab.
if (!useUsages.getState().tabs.length) {
try {
toolWindowService().hide("usages", { removeFromStripe: true });
} catch {
// Workbench not ready (tests).
}
}
}
/** Rerun of the selected tab (⌘R in the Find Usages tool window). */
+1 -1
Переглянути файл
@@ -15,5 +15,5 @@ it("hides the Debug tool window once its last session tab is closed", async () =
expect(await closeSessionTab(1)).toBe(true);
expect(hide).not.toHaveBeenCalled();
expect(await closeSessionTab(2)).toBe(true);
expect(hide).toHaveBeenCalledWith("debug");
expect(hide).toHaveBeenCalledWith("debug", { removeFromStripe: true });
});
+19
Переглянути файл
@@ -218,3 +218,22 @@ it("releases a failed shared drain so a later start can retry", async () => {
expect(await startSession(config("launch"))).toBe(42);
expect(ipc.debugStart).toHaveBeenCalledOnce();
});
it("replaces finished tabs as soon as a prepared start begins", async () => {
await startSession(config("launch"));
handleDebugEvent(42, { kind: "terminated" });
expect(useDebug.getState().sessions[42]?.status).toBe("terminated");
let finishBuild!: () => void;
const build = new Promise<void>((resolve) => (finishBuild = resolve));
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 43 });
const started = startPreparedSession({ id: "java", name: "Java" } as never, async () => {
await build;
return config("launch");
});
const preparing = Object.values(useDebug.getState().sessions);
expect(preparing).toHaveLength(1);
expect(preparing[0]).toMatchObject({ name: "Java", status: "starting" });
finishBuild();
await expect(started).resolves.toBe(43);
expect(Object.keys(useDebug.getState().sessions)).toEqual(["43"]);
});
+4 -2
Переглянути файл
@@ -670,6 +670,8 @@ export async function startPreparedSession(
const id = --preparationSeq as DebugSessionId;
const controller = new AbortController();
preparations.set(id, controller);
// The new tab takes the place of finished ones while its build runs, not once the adapter starts.
dropFinished();
useDebug.setState((s) => ({
sessions: {
...s.sessions,
@@ -878,10 +880,10 @@ export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
await stopSession(s.id);
}
removeSession(s.id);
// As in IDEA, the tool window goes away with its last tab.
// As in IDEA, the tool window and its stripe button go away with its last tab.
if (!Object.keys(useDebug.getState().sessions).length) {
try {
toolWindowService().hide("debug");
toolWindowService().hide("debug", { removeFromStripe: true });
} catch {
// Workbench not ready (tests).
}
+35 -4
Переглянути файл
@@ -1,6 +1,7 @@
/**
* The OS clipboard's file list: what Explorer copies, and what the project view
* puts there so Explorer can paste it back. The format is native (Windows
* puts there so Explorer can paste it back; and its image (a screenshot), which
* Paste saves as a file. The format is native (Windows
* `CF_HDROP`), so the backend owns it; a plain browser has nothing to exchange
* and every call degrades to "no files".
*/
@@ -13,6 +14,10 @@ export interface OsClipboard {
hasFiles(): Promise<boolean>;
/** True only when the OS accepted the file list; false for unsupported hosts. */
setFiles(paths: string[]): Promise<boolean>;
/** Whether the clipboard holds an image: cheap, for the Paste item's enabled state. */
hasImage(): Promise<boolean>;
/** The clipboard's image as PNG bytes, null when it holds none. */
image(): Promise<Uint8Array | null>;
}
const native: OsClipboard = {
@@ -39,6 +44,23 @@ const native: OsClipboard = {
return false;
}
},
async hasImage() {
if (!isTauri()) return false;
try {
return await commands.clipboardHasImage();
} catch {
return false;
}
},
async image() {
if (!isTauri()) return null;
const url = await call(commands.clipboardImage());
if (!url) return null;
const binary = atob(url.slice(url.indexOf(",") + 1));
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
},
};
let current = native;
@@ -47,7 +69,16 @@ export function osClipboard(): OsClipboard {
return current;
}
/** Tests: force a clipboard implementation. */
export function setOsClipboardForTests(clipboard: OsClipboard | null) {
current = clipboard ?? native;
/** Tests: force a clipboard implementation; what it leaves out holds nothing. */
export function setOsClipboardForTests(clipboard: Partial<OsClipboard> | null) {
current = clipboard
? {
files: async () => [],
hasFiles: async () => false,
setFiles: async () => false,
hasImage: async () => false,
image: async () => null,
...clipboard,
}
: native;
}
+13
Переглянути файл
@@ -14,6 +14,8 @@ import { isInside, joinPath, nameOf, parentOf } from "./paths";
export interface ProjectFs {
readDir(path: string): Promise<FileEntry[]>;
createFile(path: string): Promise<void>;
/** Creates `path` with `data`; fails when it exists. */
createFileBytes(path: string, data: Uint8Array): Promise<void>;
createDir(path: string): Promise<void>;
rename(from: string, to: string): Promise<void>;
/** Moves to the trash when possible. */
@@ -28,6 +30,10 @@ export const tauriFs: ProjectFs = {
await call(commands.fsCreateFile(path));
notifyFileOperation({ kind: "created", paths: [path] });
},
createFileBytes: async (path, data) => {
await call(commands.fsCreateFileBytes(path, [...data]));
notifyFileOperation({ kind: "created", paths: [path] });
},
createDir: async (path) => void (await call(commands.fsCreateDir(path))),
rename: async (from, to) => void (await call(commands.fsRename(from, to))),
delete: async (path) => {
@@ -161,6 +167,13 @@ export class MemoryFs implements ProjectFs {
this.emit({ created: [path] });
}
async createFileBytes(path: string, data: Uint8Array) {
if (this.nodes.has(path)) throw err("alreadyExists", `${path} already exists`);
this.mkdirp(parentOf(path));
this.nodes.set(path, { kind: "file", size: data.length });
this.emit({ created: [path] });
}
async createDir(path: string) {
if (this.nodes.has(path)) throw err("alreadyExists", `${path} already exists`);
this.mkdirp(path);
+20
Переглянути файл
@@ -185,6 +185,26 @@ describe("OS file imports", () => {
expect(fs.nodes.has("/p/target/local.txt")).toBe(true);
});
it("saves a pasted image as img.png, then img_1.png, and selects it", async () => {
const png = new Uint8Array([137, 80, 78, 71]);
setOsClipboardForTests({ hasImage: async () => true, image: async () => png });
await refreshOsClipboard();
expect(canPaste()).toBe(true);
await paste("/p/target");
await paste("/p/target");
expect(fs.nodes.get("/p/target/img.png")).toEqual({ kind: "file", size: 4 });
expect(fs.nodes.has("/p/target/img_1.png")).toBe(true);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/target/img_1.png");
expect(notify).not.toHaveBeenCalled();
});
it("says the clipboard is empty when it holds neither files nor an image", async () => {
setOsClipboardForTests({});
await paste("/p/target");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No files on the clipboard" }));
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/p/target/"))).toEqual([]);
});
it("reports a clipboard read failure", async () => {
setOsClipboardForTests({
files: async () => {
+42 -5
Переглянути файл
@@ -13,7 +13,7 @@ import { osClipboard } from "./clipboard";
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
import { beginLocalImport, projectFs } from "./fs";
import { call, commands, isCancelled } from "@/platform/ipc";
import { call, commands, IpcError, isCancelled } from "@/platform/ipc";
import { MEMBER_PREFIX, type ProjectNode } from "./model";
import {
isInside,
@@ -573,8 +573,9 @@ export function copySelection(cut: boolean) {
setClipboard({ paths, cut, remote, osWrite });
}
/** Files on the OS clipboard, cached: `canPaste` runs while a menu renders. */
/** Files or an image on the OS clipboard, cached: `canPaste` runs while a menu renders. */
let osHasFiles = false;
let osHasImage = false;
/** Keeps Paste enabled for what Explorer copied; called when the window gains focus. */
export async function refreshOsClipboard() {
@@ -588,10 +589,11 @@ export async function refreshOsClipboard() {
async function readOsClipboard(): Promise<string[] | null> {
const { clipboard } = get();
const handedOff = await clipboard?.osWrite;
const external = await osClipboard().files();
const [external, image] = await Promise.all([osClipboard().files(), osClipboard().hasImage()]);
// A newer Copy/Cut owns the state if this read (or its hand-off) was delayed.
if (get().clipboard !== clipboard) return null;
osHasFiles = external.length > 0;
osHasImage = image;
// Our remote text write removes file URLs, so any files were copied later.
// A failed write leaves ownership uncertain; retain the remote copy then.
if (handedOff && (clipboard?.remote ? external.length > 0 : !sameFiles(external, clipboard?.paths)))
@@ -600,12 +602,13 @@ async function readOsClipboard(): Promise<string[] | null> {
}
export function canPaste(): boolean {
return !!get().clipboard?.paths.length || osHasFiles;
return !!get().clipboard?.paths.length || osHasFiles || osHasImage;
}
/**
* Paste: cut items go through the Move dialog, copied ones through the Copy
* dialog (IDEA). Files copied in Explorer paste as copies.
* dialog (IDEA). Files copied in Explorer paste as copies; an image (a
* screenshot) is saved as `img.png`.
*/
export async function paste(target = targetFolder()) {
if (!target || isReadOnlyPath(target)) return;
@@ -626,6 +629,7 @@ export async function paste(target = targetFolder()) {
if (!clipboard?.remote && external.length && !sameFiles(external, clipboard?.paths))
return pasteFromOsClipboard(external, target);
if (!clipboard?.paths.length) {
if (await pasteImage(target)) return;
notifications().notify({ level: "info", title: "No files on the clipboard" });
return;
}
@@ -640,6 +644,39 @@ export async function paste(target = targetFolder()) {
});
}
/**
* Saves the clipboard's image in `target` as `img.png`, or `img_1.png`, `img_2.png`
* … when taken, and selects it. False when the clipboard holds no image.
*/
async function pasteImage(target: string): Promise<boolean> {
let png: Uint8Array | null;
try {
png = await osClipboard().image();
} catch (e) {
fail(tx("Cannot access the clipboard"), e);
return true;
}
if (!png) return false;
await loadDir(target);
const taken = new Set((get().listings.get(target) ?? []).map((e) => e.name));
for (let i = 0; ; i++) {
const name = i ? `img_${i}.png` : "img.png";
if (taken.has(name)) continue;
const path = joinPath(target, name);
try {
await projectFs(get().root ?? target).createFileBytes(path, png);
} catch (e) {
// Created since the listing was read: take the next name.
if (e instanceof IpcError && e.kind === "alreadyExists") continue;
fail(tx`Cannot paste the image into ${name}`, e);
return true;
}
await loadDir(target, true);
revealPath(path, true);
return true;
}
}
/** Pasting from Explorer copies, whatever the source: never a move or a refactoring. */
async function pasteFromOsClipboard(paths: string[], target: string) {
osHasFiles = true;
+2 -1
Переглянути файл
@@ -303,7 +303,8 @@ function currentTab(
export async function closeRunTab(id: string, traces: readonly StackTraceTab[]) {
if (traces.some((t) => t.id === id)) closeStackTrace(id);
else if (!(await closeSessionTab(id))) return;
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length) toolWindowService().hide("run");
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length)
toolWindowService().hide("run", { removeFromStripe: true });
}
/** Session (and stack trace) tabs in the tool window header. */
+175 -1
Переглянути файл
@@ -1,8 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { useState } from "react";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { registerActions } from "@/platform/actions";
import { ContextMenuHost } from "@/ui";
import { occurrenceNavigator } from "@/workbench/contributions";
import { TestResults } from "./testing";
import { TestTreeView } from "./TestTreeView";
import { testTree } from "./testTree";
const nav = vi.hoisted(() => ({ openTarget: vi.fn(async () => {}) }));
vi.mock("./navigate", () => nav);
@@ -112,3 +116,173 @@ describe("TestTreeView", () => {
},
);
});
describe("Previous / Next Failed Test", () => {
beforeEach(() => localStorage.clear());
afterEach(() => vi.clearAllMocks());
/** Two suites with failures in a nested suite and between passing tests. */
function nested(failures = true) {
const r = new TestResults();
const bad = failures ? "failed" : "passed";
r.apply([
{ type: "result", path: ["ApiTest", "lists()"], status: "passed" },
{ type: "result", path: ["ApiTest", "Auth", "rejects()"], status: bad },
{ type: "result", path: ["ApiTest", "Auth", "accepts()"], status: "passed" },
{ type: "result", path: ["DbTest", "reads()"], status: bad },
{ type: "result", path: ["DbTest", "skips()"], status: "skipped" },
{ type: "result", path: ["DbTest", "writes()"], status: bad },
{ type: "location", path: ["DbTest", "writes()"], location: { path: "DbTest.java", line: 20, resolve: "name" } },
]);
r.finish(failures ? 1 : 0);
return r;
}
function Nested({ results }: { results: TestResults }) {
const [selected, setSelected] = useState<string | null>(null);
return (
<TestTreeView results={results} version={1} cwd="/p" selected={selected} onSelect={setSelected} running={false} />
);
}
const go = (dir: 1 | -1, focus = false) => {
let step: ReturnType<NonNullable<ReturnType<typeof occurrenceNavigator>>["go"]> = null;
act(() => {
step = occurrenceNavigator("run")!.go(dir, focus);
});
return step as { key: string; index: number; total: number } | null;
};
const selectedName = () => screen.getByRole("treeitem", { selected: true }).textContent;
const prev = () => screen.getByRole("button", { name: "Previous Failed Test" });
const next = () => screen.getByRole("button", { name: "Next Failed Test" });
it("steps through the failed tests in tree order and stops at both ends", () => {
render(<Nested results={nested()} />);
expect(prev()).toBeEnabled();
expect(next()).toBeEnabled();
expect(go(1)).toMatchObject({ index: 1, total: 3 });
expect(selectedName()).toContain("rejects()");
expect(go(1)).toMatchObject({ index: 2, total: 3 });
expect(selectedName()).toContain("reads()");
expect(go(1)).toMatchObject({ index: 3, total: 3 });
expect(selectedName()).toContain("writes()");
// IDEA doesn't wrap: Next is unavailable on the last failure, and the selection stays.
expect(next()).toBeDisabled();
expect(prev()).toBeEnabled();
expect(go(1)).toBeNull();
expect(selectedName()).toContain("writes()");
expect(go(-1)).toMatchObject({ index: 2 });
expect(go(-1)).toMatchObject({ index: 1 });
expect(prev()).toBeDisabled();
expect(go(-1)).toBeNull();
expect(selectedName()).toContain("rejects()");
});
it("expands the collapsed suites of the failure it selects", () => {
render(<Nested results={nested()} />);
const suite = screen.getByText("ApiTest").closest('[role="treeitem"]')!;
fireEvent.mouseDown(suite.querySelector("[data-tree-toggle]")!, { button: 0 });
expect(screen.queryByText("rejects()")).toBeNull();
go(1);
expect(selectedName()).toContain("rejects()");
});
it("opens the failure's source, focusing the editor only when asked", () => {
render(<Nested results={nested()} />);
go(-1);
expect(nav.openTarget).toHaveBeenCalledWith(
expect.objectContaining({ path: "DbTest.java", line: 20 }),
"/p",
false,
);
go(-1, true);
// reads() has no location: nothing to open.
expect(nav.openTarget).toHaveBeenCalledTimes(1);
});
it("is unavailable when no test failed", () => {
render(<Nested results={nested(false)} />);
expect(prev()).toBeDisabled();
expect(next()).toBeDisabled();
expect(go(1)).toBeNull();
expect(go(-1)).toBeNull();
});
it("runs Previous / Next Occurrence, so ⌘⌥↑ / ⌘⌥↓ do the same", () => {
render(<Nested results={nested()} />);
fireEvent.click(next());
expect(actions.executeAction).toHaveBeenCalledWith("navigate.nextOccurrence", undefined);
fireEvent.click(prev());
expect(actions.executeAction).toHaveBeenCalledWith("navigate.prevOccurrence", undefined);
});
});
describe("Expand All / Collapse All", () => {
beforeEach(() => localStorage.clear());
afterEach(() => vi.clearAllMocks());
function nested() {
const r = new TestResults();
r.apply([
{ type: "result", path: ["ApiTest", "Auth", "Tokens", "refreshes()"], status: "failed" },
{ type: "result", path: ["ApiTest", "Users", "lists()"], status: "passed" },
{ type: "result", path: ["DbTest", "Pool", "reuses()"], status: "passed" },
]);
r.finish(1);
return r;
}
const view = (results: TestResults) => (
<TestTreeView results={results} version={1} cwd="/p" selected={null} onSelect={() => {}} running={false} />
);
const rows = () => screen.queryAllByRole("treeitem").map((r) => r.textContent?.replace(/\d+ ms$/, ""));
it("opens every suite, including those of hidden passed tests, and folds back to the top-level suites", () => {
localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true }));
render(view(nested()));
// By default only the top level and the suites with failures are open.
expect(rows()).toEqual(["ApiTest", "Auth", "Tokens", "refreshes()", "Users", "DbTest", "Pool"]);
act(() => testTree.expandAll!());
expect(rows()).toEqual([
"ApiTest",
"Auth",
"Tokens",
"refreshes()",
"Users",
"lists()",
"DbTest",
"Pool",
"reuses()",
]);
act(() => testTree.collapseAll!());
expect(rows()).toEqual(["ApiTest", "DbTest"]);
// Expanded state survives a filter change.
act(() => testTree.expandAll!());
fireEvent.click(screen.getByRole("button", { name: "Show Passed" }));
expect(rows()).toEqual(["ApiTest", "Auth", "Tokens", "refreshes()"]);
fireEvent.click(screen.getByRole("button", { name: "Show Passed" }));
expect(rows()).toContain("reuses()");
});
it("the buttons run the actions, and are unavailable without suites", () => {
const dispose = registerActions([
{ id: "run.expandAllTests", title: "Expand All", run: () => {} },
{ id: "run.collapseAllTests", title: "Collapse All", run: () => {} },
]);
onTestFinished(dispose);
const { unmount } = render(view(nested()));
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined);
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined);
unmount();
expect(testTree.expandAll).toBeNull();
const flat = new TestResults();
flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]);
flat.finish(1);
render(view(flat));
expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled();
});
});
+82 -2
Переглянути файл
@@ -1,10 +1,22 @@
import { useMemo, useState, type MouseEvent } from "react";
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { Icon, IconButton, showContextMenu, useContextMenuStore, Spinner, Tree, type MenuItem } from "@/ui";
import {
findOccurrence,
Icon,
IconButton,
showContextMenu,
useContextMenuStore,
Spinner,
Tree,
type MenuItem,
type TreeHandle,
} from "@/ui";
import { useOccurrenceNavigator } from "@/workbench/contributions";
import { openTarget } from "./navigate";
import { nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
import { parseComparison } from "./testing/comparison";
import { TEST_TREE_FOCUS, testTree } from "./testTree";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
@@ -84,6 +96,24 @@ export function StatusIcon({ status }: { status: TestStatus | null }) {
}
}
const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed";
const treeModel = {
getKey: (n: TestNode) => n.id,
getChildren: (n: TestNode) => n.children,
isExpandable: (n: TestNode) => n.children.length > 0,
isOccurrence: isFailedTest,
};
function suiteIds(nodes: readonly TestNode[], out: Set<string> = new Set()): Set<string> {
for (const n of nodes) {
if (n.children.length === 0) continue;
out.add(n.id);
suiteIds(n.children, out);
}
return out;
}
function filterTree(nodes: readonly TestNode[], keep: (n: TestNode) => boolean): TestNode[] {
const out: TestNode[] = [];
for (const n of nodes) {
@@ -129,6 +159,7 @@ export function TestTreeView({
});
const [expanded, setExpanded] = useState<Set<string> | null>(null);
const [selection, setSelection] = useState<Set<string>>(new Set());
const tree = useRef<TreeHandle>(null);
const selectedKeys = useMemo(
() => (selected === null ? new Set<string>() : selection.has(selected) ? selection : new Set([selected])),
[selected, selection],
@@ -209,6 +240,28 @@ export function TestTreeView({
return set;
}, [expanded, roots]);
// Collapse All leaves the top-level suites in view, as IDEA's test tree does.
useEffect(() => {
testTree.expandAll = () => setExpanded(suiteIds(results.roots));
testTree.collapseAll = () => setExpanded(new Set());
return () => {
testTree.expandAll = null;
testTree.collapseAll = null;
};
});
const hasSuites = roots.some((n) => n.children.length > 0);
// Previous / Next Failed Test (⌘⌥↑ / ⌘⌥↓): like IDEA, stops at the first / last failure instead of wrapping.
useOccurrenceNavigator("run", (dir, focus) => {
const step = tree.current?.selectOccurrence(dir);
if (!step) return null;
const n = step.node as TestNode;
if (n.location) void openTarget(n.location, cwd, focus);
return step;
});
const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null;
const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null;
const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null;
const duration = results.summary.durationMs;
@@ -240,15 +293,42 @@ export function TestTreeView({
pressed={showIgnored}
onClick={() => toggle("showIgnored")}
/>
<IconButton icon="expand-all" action="run.expandAllTests" size="small" iconSize={16} disabled={!hasSuites} />
<IconButton
icon="collapse-all"
action="run.collapseAllTests"
size="small"
iconSize={16}
disabled={!hasSuites}
/>
<IconButton
icon="arrow-up"
action="navigate.prevOccurrence"
size="small"
iconSize={16}
title="Previous Failed Test"
disabled={!hasPrevFailed}
/>
<IconButton
icon="arrow-down"
action="navigate.nextOccurrence"
size="small"
iconSize={16}
title="Next Failed Test"
disabled={!hasNextFailed}
/>
</div>
<Tree<TestNode>
aria-label="Test results"
className={styles.testTree}
handleRef={tree}
focusContext={TEST_TREE_FOCUS}
roots={roots}
getKey={(n) => n.id}
getLabel={(n) => n.name}
getChildren={(n) => (n.children.length ? n.children : undefined)}
isExpandable={(n) => n.children.length > 0}
isOccurrence={isFailedTest}
expanded={effectiveExpanded}
onExpandedChange={(next) => setExpanded(next)}
selected={selectedKeys}
+1 -1
Переглянути файл
@@ -24,5 +24,5 @@ it("hides the Run tool window once its last tab is closed", async () => {
await closeRunTab("t", useStackTraces.getState().tabs);
expect(hide).not.toHaveBeenCalled();
await closeRunTab("b", useStackTraces.getState().tabs);
expect(hide).toHaveBeenCalledWith("run");
expect(hide).toHaveBeenCalledWith("run", { removeFromStripe: true });
});
+45
Переглянути файл
@@ -218,3 +218,48 @@ describe("Debug entry", () => {
).toBe(false);
});
});
describe("Run with Fuzzing", () => {
const goTest: RunConfig = {
...npmTest,
id: "go:test",
name: "go test ./...",
kind: "go",
command: "go",
args: ["test", "./..."],
debugAdapter: "delve",
};
const text = "package parse\nfunc TestParse(t *testing.T) {}\nfunc FuzzParse(f *testing.F) {\n}\n";
const path = `${ROOT}/parse/parse_test.go`;
const target = (line: number, name: string): RunTarget => ({ line, kind: "test", name, path: [name] });
const itemLabels = (items: MenuItem[]) => items.map((i) => ("label" in i ? (i.label ?? "") : "---"));
beforeEach(() => {
useProject.setState({ project: { name: "app", root: ROOT, trusted: true, isGit: false, settings: {} } as never });
useRun.setState({ configs: [goTest], loaded: true });
});
afterEach(() => {
useProject.setState({ project: null });
useRun.setState({ configs: [], loaded: false });
});
it("the gutter offers it on a Fuzz function, after Run and Debug", () => {
expect(itemLabels(targetMenuItems(target(2, "FuzzParse"), path, text))).toEqual([
"Run 'FuzzParse in parse'",
"Debug 'FuzzParse in parse'",
"Run 'FuzzParse in parse' with Fuzzing",
"---",
"Modify Run Configuration…",
]);
expect(itemLabels(targetMenuItems(target(1, "TestParse"), path, text)).some((l) => /Fuzzing/.test(l))).toBe(false);
});
it("the editor menu offers it under More Run/Debug at a Fuzz function only", () => {
const at = (line: number) => labels(contextMenuItems("editor", { paths: [path], text, line }));
expect(at(2)).toContain("Run 'FuzzParse in parse' with Fuzzing");
expect(at(1).some((l) => /Fuzzing/.test(l))).toBe(false);
expect(
labels(contextMenuItems("projectView", { paths: [path], dirs: [false] })).some((l) => /Fuzzing/.test(l)),
).toBe(false);
});
});
+17
Переглянути файл
@@ -26,6 +26,7 @@ import {
produceContextChoices,
produceDirectory,
produceFile,
produceFuzz,
scriptLanguage,
type ContextInput,
type Produced,
@@ -293,6 +294,21 @@ export function executorItems(config: RunConfig | null | undefined, name: string
}));
}
/** "Run '<FuzzXxx>' with Fuzzing" at a Go fuzz target: `go test -fuzz` until it is stopped or fails. */
export function fuzzItems(input: ContextInput, context: ContextArg): MenuItem[] {
const p = produceFuzz(input, OPTIMISTIC);
return p ? [{ label: tx`Run '${p.name}' with Fuzzing`, icon: "run", run: () => void fuzzContext(context) }] : [];
}
async function fuzzContext(arg: ContextArg): Promise<void> {
await ensureConfigs();
const input = await withArgContent(arg);
if (!input) return;
await loadGoModules(input.root, useRun.getState().configs);
const p = produceFuzz({ ...input, configs: useRun.getState().configs, goModule: goModulePath }, OPTIMISTIC);
if (p) await launchProduced(p, false);
}
export interface ContextArg {
path: string;
line?: number;
@@ -394,6 +410,7 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
label: "More Run/Debug",
submenu: [
...executorItems(p.config, p.name, arg),
...fuzzItems(input, arg),
{ kind: "action", action: "run.modifyContext", arg, label: "Modify Run Configuration…", icon: "edit" },
],
},
+19
Переглянути файл
@@ -99,6 +99,7 @@ import {
isLive,
} from "./store";
import { rerunFailedConfigs } from "./testing/rerun";
import { TEST_TREE_FOCUS, testTree } from "./testTree";
import { startAgentRun, trimAgentArchive, type AgentRunRequest } from "./agentRuns";
import { compoundTargets, selectedTarget } from "./sessionTargets";
import { tx } from "@/platform/i18n";
@@ -638,6 +639,24 @@ export function activate(): () => void {
});
},
},
{
id: "run.expandAllTests",
title: "Expand All",
category: "Run",
icon: "expand-all",
when: "projectOpen && activeToolWindow == 'run'",
keyWhen: TEST_TREE_FOCUS,
run: () => testTree.expandAll?.(),
},
{
id: "run.collapseAllTests",
title: "Collapse All",
category: "Run",
icon: "collapse-all",
when: "projectOpen && activeToolWindow == 'run'",
keyWhen: TEST_TREE_FOCUS,
run: () => testTree.collapseAll?.(),
},
{
id: "run.reloadConfigs",
title: "Reload Run Configurations",
+52
Переглянути файл
@@ -9,6 +9,7 @@ import {
produceContextChoices,
produceDirectory,
produceFile,
produceFuzz,
shebang,
shellWord,
fileTargets,
@@ -1137,6 +1138,57 @@ describe("Go test names (GoLand)", () => {
});
});
describe("Go Run with Fuzzing (GoLand)", () => {
const GO = [
cfg({ id: "go:test", kind: "go", command: "go", args: ["test", "./..."], isTest: true, debugAdapter: "delve" }),
];
const src = [
"package parse", // 0
'import "testing"',
"func TestParse(t *testing.T) {}", // 2
"func BenchmarkParse(b *testing.B) {}",
"func ExampleParse() {}",
"func FuzzParse(f *testing.F) {", // 5
'\tf.Add("x")',
"\tf.Fuzz(func(t *testing.T, s string) {", // 7
"\t})",
"}",
"func helper() {}", // 10
].join("\n");
const modules = (dir: string) => (dir === ROOT ? "example.com/fixture" : undefined);
const at = (line: number | undefined, path = `${ROOT}/internal/parse/parse_test.go`, content = src) =>
produceFuzz({ path, root: ROOT, configs: GO, content, line, goModule: modules }, ALL);
it("the Fuzz function at the caret, its body included, fuzzes its package", () => {
for (const line of [5, 7]) {
const p = at(line)!;
expect(p.name).toBe("FuzzParse in example.com/fixture/internal/parse");
expect(p.config).toMatchObject({
args: ["test", "./internal/parse", "-run", "^FuzzParse$", "-fuzz", "^FuzzParse$"],
name: "FuzzParse in example.com/fixture/internal/parse (fuzzing)",
isTest: true,
});
}
expect(at(5, `${ROOT}/parse_test.go`)!.config!.args).toEqual([
"test",
".",
"-run",
"^FuzzParse$",
"-fuzz",
"^FuzzParse$",
]);
});
it("nothing for tests, benchmarks, examples, other code or the file", () => {
for (const line of [0, 2, 3, 4, 10, undefined]) expect(at(line)).toBeNull();
// Not a test file: `go test` doesn't build its Fuzz functions as fuzz targets.
expect(at(5, `${ROOT}/internal/parse/parse.go`)).toBeNull();
// `Fuzzer` is not a fuzz target name; a Fuzz function needs a *testing.F.
const misnamed = "package p\nfunc Fuzzer(f *testing.F) {}\nfunc FuzzT(t *testing.T) {}";
for (const line of [1, 2]) expect(at(line, undefined, misnamed)).toBeNull();
});
});
describe("CMake file context", () => {
const configure = cfg({
id: "cmake:build:configure",
+12 -1
Переглянути файл
@@ -31,7 +31,7 @@ import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes";
import { firstTopLevelType, scanJvmTargets, simpleClassName } from "./jvmTargets";
import { isWindows } from "./jvmTypes";
import { inheritedRunTargets } from "./inheritedMain";
import { detectRunTargets, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
import { detectRunTargets, goFuzzConfig, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
import { tx } from "@/platform/i18n";
export interface LocatedTool {
@@ -1164,6 +1164,17 @@ export function produceContext(input: ContextInput, env: ToolEnv): Produced | nu
return produceFile(input, env);
}
/** GoLand's "Run '<name>' with Fuzzing": the `Fuzz` function at the caret, run with `go test -fuzz`. */
export function produceFuzz(input: ContextInput, env: ToolEnv): Produced | null {
input = scopedInput(input);
if (input.content === undefined || input.line === undefined || !/_test\.go$/.test(input.path)) return null;
const targets = fileTargets(input, input.content.slice(0, 400_000));
const inner = innermostTarget(input.content, targets, input.line);
const produced = inner && elementProduction(input, env, inner);
const config = inner && produced?.config && goFuzzConfig(produced.config, inner);
return produced && config ? { ...produced, config } : null;
}
/**
* Every configuration that can run the context, when several test
* configurations match it equally well (`npm run test` and `npm run test:unit`):
+2
Переглянути файл
@@ -17,6 +17,7 @@ import {
canDebugProduced,
choiceItems,
executeContext,
fuzzItems,
launchProduced,
modifyContext,
produceResolved,
@@ -123,6 +124,7 @@ export function targetMenuItems(target: RunTarget, path: string, content: string
...runExecutors()
.filter((e) => !!p?.config && e.supports(p.config))
.map((e) => ({ label: e.label(name), icon: e.icon, run: () => void executeContext(e.id, context) })),
...fuzzItems(input, context),
{ kind: "separator" },
{ label: "Modify Run Configuration…", icon: "edit", run: () => void modifyContext(context) },
];
+94 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { detectRunTargets, jsNamePattern, targetConfig } from "./targets";
import { detectRunTargets, goFuzzConfig, jsNamePattern, targetConfig, type RunTarget } from "./targets";
const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({
name: over.id,
@@ -239,6 +239,99 @@ describe("Go test targets", () => {
"-test.short",
]);
});
describe("Run with Fuzzing", () => {
const text = [
"package parse",
"func TestParse(t *testing.T) {}",
"func BenchmarkParse(b *testing.B) {}",
"func FuzzParse(f *testing.F) {",
' f.Add("x")',
" f.Fuzz(func(t *testing.T, s string) {})",
"}",
"func ExampleParse() {}",
].join("\n");
const base = cfg({ id: "go:test", kind: "go", args: ["test", "-tags", "demo", "./...", "-args", "-test.short"] });
const fuzzOf = (rel: string, name: string, configs = [base]) => {
const target = detectRunTargets(text, rel).find((t) => t.name === name)!;
const config = targetConfig(target, rel, configs, text)!;
return goFuzzConfig(config, target);
};
it("adds -fuzz with the -run pattern of a Fuzz function", () => {
const config = fuzzOf("parse/parse_test.go", "FuzzParse")!;
expect(config.args).toEqual([
"test",
"-tags",
"demo",
"./parse",
"-run",
"^FuzzParse$",
"-fuzz",
"^FuzzParse$",
"-args",
"-test.short",
]);
// A temporary configuration of its own, beside the plain run of the fuzz target.
expect(config.id).not.toBe(
targetConfig(detectRunTargets(text, "parse/parse_test.go")[2]!, "parse/parse_test.go", [base], text)!.id,
);
expect(config.name).toBe("FuzzParse (fuzzing)");
});
it("runs a fuzz target at the module root and in nested package directories", () => {
expect(fuzzOf("parse_test.go", "FuzzParse")!.args.slice(3, 4)).toEqual(["."]);
expect(fuzzOf("internal/text/parse/parse_test.go", "FuzzParse")!.args.slice(3, 4)).toEqual([
"./internal/text/parse",
]);
});
it("is offered for Fuzz functions only", () => {
for (const name of ["TestParse", "BenchmarkParse", "ExampleParse"])
expect(fuzzOf("parse/parse_test.go", name)).toBeNull();
const npm = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] });
const js: RunTarget = { line: 0, kind: "test", name: "Fuzz it", path: ["Fuzz it"] };
expect(goFuzzConfig(targetConfig(js, "src/a.test.ts", [npm])!, js)).toBeNull();
});
it("escapes the name and replaces a saved selection", () => {
const saved = cfg({
id: "go:saved",
kind: "go",
args: ["test", "-fuzz=Old", "-run", "Old", "-bench", ".", "./parse", "-fuzztime", "30s"],
});
const target: RunTarget = { line: 0, kind: "test", name: "Fuzz.Δ+", path: ["Fuzz.Δ+"] };
expect(goFuzzConfig(saved, target)!.args).toEqual([
"test",
"-fuzztime",
"30s",
"./parse",
"-run",
"^Fuzz\\.Δ\\+$",
"-fuzz",
"^Fuzz\\.Δ\\+$",
]);
});
it("needs exactly one package: -fuzz cannot match across packages", () => {
const target: RunTarget = { line: 0, kind: "test", name: "FuzzParse", path: ["FuzzParse"] };
const go = (args: string[]) => cfg({ id: "go:x", kind: "go", args });
expect(goFuzzConfig(go(["test", "./..."]), target)).toBeNull();
expect(goFuzzConfig(go(["test", "./a", "./b"]), target)).toBeNull();
expect(goFuzzConfig(go(["run", "."]), target)).toBeNull();
expect(goFuzzConfig(go(["test", "./a"]), target)).not.toBeNull();
});
it("keeps a Go Test configuration's form in step", () => {
const typed = cfg({
id: "go:typed",
kind: "go",
args: ["test", "-tags", "demo", "."],
params: { goKind: "test", scope: "package", target: ".", toolArgs: "-tags demo" },
});
const config = fuzzOf("parse/parse_test.go", "FuzzParse", [typed])!;
expect(config.params).toMatchObject({ pattern: "^FuzzParse$", toolArgs: "-tags demo -fuzz '^FuzzParse$'" });
});
});
it("uses the module and overrides a saved filter before binary arguments", () => {
const base = cfg({
id: "go:typed",
+23
Переглянути файл
@@ -415,6 +415,29 @@ function withLast(args: string[], f: (last: string) => string): string[] {
return args.length ? [...args.slice(0, -1), f(args[args.length - 1]!)] : args;
}
/**
* GoLand's "Run with Fuzzing" of a `Fuzz` function: its `go test` configuration with
* `-fuzz` added. Null for other targets, and when the configuration doesn't test one
* package (`go test -fuzz` refuses several).
*/
export function goFuzzConfig(config: RunConfig, target: RunTarget): RunConfig | null {
if (target.kind !== "test" || target.path.length !== 1 || !/^Fuzz/.test(target.name)) return null;
if (config.kind !== "go" || config.args[0] !== "test") return null;
const parts = goTestParts(config.args);
if (parts.targets.length !== 1 || /(^|\/)\.\.\.$/.test(parts.targets[0]!)) return null;
const pattern = `^${escapeRegExp(target.name)}$`;
const flags = withoutGoSelection(parts.flags);
return {
...config,
id: `${config.id}:fuzz`,
name: `${config.name} (fuzzing)`,
args: ["test", ...flags, ...parts.targets, "-run", pattern, "-fuzz", pattern, ...withoutGoSelection(parts.program)],
...(config.params?.goKind
? { params: { ...config.params, pattern, toolArgs: formatArgs([...flags, "-fuzz", pattern]) } }
: {}),
};
}
/** Run configuration for one target, or null when the project has no matching runner. */
export function targetConfig(
target: RunTarget,
+8
Переглянути файл
@@ -0,0 +1,8 @@
/** Context key: the test results tree has focus. */
export const TEST_TREE_FOCUS = "testTreeFocus";
/** Set while a test results tree is shown: Expand All / Collapse All act on it. */
export const testTree: { expandAll: (() => void) | null; collapseAll: (() => void) | null } = {
expandAll: null,
collapseAll: null,
};
+14
Переглянути файл
@@ -1,8 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
import type { FileMatches, SearchQuery } from "@/platform/ipc";
import { buildFindTree } from "../find/FindToolWindow";
import type { FindDeps } from "../find/session";
import {
closeFindTab,
disposeFindWindow,
openEditorResults,
openInFindWindow,
@@ -38,6 +40,18 @@ const file = (rel: string): FileMatches => ({
afterEach(disposeFindWindow);
describe("Find tool window tabs", () => {
it("take the tool window and its stripe button away with the last one", () => {
const hide = vi.fn();
provideToolWindowService({ show: vi.fn(), hide } as unknown as ToolWindowService);
const a = openInFindWindow(q("a"), "a", { deps });
pinFindTab(a, true);
const b = openInFindWindow(q("b"), "b", { deps });
closeFindTab(a);
expect(hide).not.toHaveBeenCalled();
closeFindTab(b);
expect(hide).toHaveBeenCalledWith("find", { removeFromStripe: true });
});
it("reuses the selected tab unless it is pinned", () => {
const a = openInFindWindow(q("a"), "a", { deps });
const b = openInFindWindow(q("b"), "b", { deps });
+2
Переглянути файл
@@ -134,6 +134,8 @@ export function closeFindTab(id: number) {
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
return { tabs, active };
});
// As in IDEA, the tool window and its stripe button go away with its last tab.
if (!useFindWindow.getState().tabs.length) maybeToolWindowService()?.hide("find", { removeFromStripe: true });
}
export function disposeFindWindow() {
-5
Переглянути файл
@@ -110,11 +110,6 @@
line-height: normal;
transform: translateY(-50%);
}
/* An icon wider than its cell stays over the next cell's background (domRowCache). */
.pane :global(.xterm-rows .openidea-terminal-icon) {
position: relative;
z-index: 1;
}
.pane :global(.xterm-viewport) {
background-color: var(--bg-island, var(--bg-app)) !important;
}
+15 -5
Переглянути файл
@@ -18,10 +18,13 @@ function fakeRendererClass() {
dimensions = { css: { cell: { width: 8 } } };
_widthCache = {};
_rowFactory = {
defaultSpacing: 0,
createRow: (line: string) =>
line.split(" ").map((word) => {
const span = document.createElement("span");
span.textContent = word;
const [text = "", spacing] = word.split("@");
span.textContent = text;
if (spacing) span.style.letterSpacing = spacing;
return span;
}),
};
@@ -76,14 +79,21 @@ describe("installDomRowCache", () => {
expect(rowAt(renderer, 1).textContent).toBe("ce");
});
it("lifts spans with Nerd Font icons over the next cell's background", () => {
it("lifts spans with Nerd Font icons or wider-than-cell fallback glyphs over the next cell's background", () => {
const Renderer = fakeRendererClass();
// U+E606 (Python logo) and U+F0035 (a Material Design icon) are drawn wider than one cell.
const renderer = new Renderer(["\uE606 py \u{F0035} ~/src"]);
// PUA icons (U+E606, U+F0035), non-PUA Nerd Font symbols (U+26A1), and fallback symbols
// measured wider than one cell (U+23F2 with negative letter-spacing) lift; tiny subpixel
// DPR rounding (-0.1px) and narrow glyphs (+1.2px) stay normal.
const renderer = new Renderer(["\uE606 py \u{F0035} \u26A1 \[email protected] [email protected] [email protected] ~/src"]);
installDomRowCache(terminalWith(renderer));
renderer.renderRows(0, 0);
const lifted = [...rowAt(renderer, 0).children].map((span) => span.classList.contains(ICON_SPAN_CLASS));
expect(lifted).toEqual([true, false, true, false]);
expect(lifted).toEqual([true, false, true, true, true, false, false, false]);
// Hovering a link (_setCellUnderline) rebuilds the row directly; overhanging spans stay lifted.
renderer._setCellUnderline();
const liftedOnHover = [...rowAt(renderer, 0).children].map((span) => span.classList.contains(ICON_SPAN_CLASS));
expect(liftedOnHover).toEqual([true, false, true, true, true, false, false, false]);
});
it("re-renders rows after clear() and link underlines rebuilt them", () => {
+21 -4
Переглянути файл
@@ -17,11 +17,20 @@ import type { Terminal } from "@xterm/xterm";
const MARKUP = Symbol("rowMarkup");
/** Private Use Area characters: Nerd Font / Powerline icons, often drawn wider than their cell. */
const ICON = /[\uE000-\uF8FF]|[\u{F0000}-\u{10FFFD}]/u;
/** Lifts a span holding such an icon over the next one, so the next cell's background doesn't cover it. */
/**
* Glyphs whose ink can extend past one cell even when their font advance equals the cell:
* Nerd Font / Powerline Private Use Area icons plus Nerd Font's non-PUA patched symbols.
*/
const ICON = /[\u23FB-\u23FE\u2630\u2665\u26A1\u2B58\uE000-\uF8FF]|[\u{F0000}-\u{10FFFD}]/u;
/** Lifts a span holding an overhanging glyph over the next one, so the next cell's background doesn't cover it. */
export const ICON_SPAN_CLASS = "openidea-terminal-icon";
function overhangsCell(span: HTMLElement, maxSpacing: number): boolean {
const { letterSpacing } = span.style;
if (letterSpacing && Number.parseFloat(letterSpacing) < maxSpacing) return true;
return ICON.test(span.textContent ?? "");
}
type RowElement = HTMLElement & { [MARKUP]?: string };
type BufferLine = unknown;
@@ -30,6 +39,7 @@ type BufferLine = unknown;
interface DomRenderer {
_rowElements: RowElement[];
_rowFactory: {
defaultSpacing?: number;
createRow(
line: BufferLine,
row: number,
@@ -82,6 +92,7 @@ function renderRows(this: DomRenderer, start: number, end: number) {
const options = this._optionsService.rawOptions;
const cursorBlink = modes.cursorBlink ?? options.cursorBlink;
const cursorStyle = modes.cursorStyle ?? options.cursorStyle;
const maxSpacing = Math.min(0, this._rowFactory.defaultSpacing ?? 0) - 0.5;
for (let y = start; y <= end; y++) {
const row = y + buffer.ydisp;
const element = this._rowElements[y];
@@ -102,7 +113,7 @@ function renderRows(this: DomRenderer, start: number, end: number) {
);
let markup = "";
for (const span of spans) {
if (ICON.test(span.textContent ?? "")) span.classList.add(ICON_SPAN_CLASS);
if (overhangsCell(span, maxSpacing)) span.classList.add(ICON_SPAN_CLASS);
markup += span.outerHTML;
}
if (element[MARKUP] === markup) continue;
@@ -132,5 +143,11 @@ export function installDomRowCache(term: Terminal) {
proto._setCellUnderline = function (this: DomRenderer, ...args: unknown[]) {
forget(this);
_setCellUnderline.apply(this, args);
const maxSpacing = Math.min(0, this._rowFactory.defaultSpacing ?? 0) - 0.5;
for (const row of this._rowElements) {
for (const child of row.children) {
if (overhangsCell(child as HTMLElement, maxSpacing)) child.classList.add(ICON_SPAN_CLASS);
}
}
};
}
+7 -1
Переглянути файл
@@ -322,7 +322,7 @@ describe("terminalFont", () => {
columnWidth: 1,
};
const editor = { fontFamily: "JetBrains Mono", fontSize: 10, lineHeight: 12 };
const head = (family: string) => family.slice(0, family.indexOf('"Symbols Nerd Font Mono"'));
const head = (family: string) => family.slice(0, family.indexOf('"Symbols Nerd Font"'));
it.each([
// #26: "Use editor font" with the default family must reach the bundled face, not the system monospace.
@@ -407,6 +407,12 @@ describe("terminalFont", () => {
expect(terminalFont({ ...t, lineHeight: 1.2 }, editor, BASE).lineHeight).toBe(1.2);
});
it("prefers full-width Nerd Font fallbacks ahead of shrunk Mono variants", () => {
const { family } = terminalFont(t, editor, BASE);
expect(family.indexOf('"Symbols Nerd Font"')).toBeLessThan(family.indexOf('"Symbols Nerd Font Mono"'));
expect(family.indexOf('"JetBrainsMono Nerd Font"')).toBeLessThan(family.indexOf('"JetBrainsMono Nerd Font Mono"'));
});
it("turns the column width into letter spacing", () => {
expect(terminalFont({ ...t, useEditorFont: false }, editor, BASE).letterSpacing).toBe(0);
expect(terminalFont({ ...t, useEditorFont: false, columnWidth: 1.5 }, editor, BASE).letterSpacing).toBe(3);
+2 -1
Переглянути файл
@@ -142,9 +142,10 @@ export function readTerminalTheme(): ITheme {
}
const NERD_FONT_FALLBACKS = [
"Symbols Nerd Font",
"Symbols Nerd Font Mono",
"JetBrainsMono Nerd Font Mono",
"JetBrainsMono Nerd Font",
"JetBrainsMono Nerd Font Mono",
"MesloLGS NF",
"MesloLGS Nerd Font",
"Hack Nerd Font",
+7
Переглянути файл
@@ -6,3 +6,10 @@
.xterm textarea.xterm-helper-textarea {
white-space: pre;
}
/* 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) {
position: relative;
z-index: 1;
}
+8 -2
Переглянути файл
@@ -71,6 +71,7 @@ import {
setCommitDiffPreview,
setDiffPreview,
setGroupByDir,
setGroupByRepo,
setGroupByStaging,
useCommit,
type CommitTab,
@@ -567,6 +568,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
const root = useVcs((s) => s.root) ?? "";
const groupByDir = useCommit((s) => s.groupByDir);
const groupByStaging = useCommit((s) => s.groupByStaging);
const groupByRepo = useCommit((s) => s.groupByRepo);
const diffPreview = useCommit((s) => s.diffPreview);
const commitDiffPreview = useCommit((s) => s.commitDiffPreview);
const doubleClickOpensDiff = useWorkflowSettings((s) => s.vcs.commit.doubleClickOpensDiff);
@@ -584,8 +586,8 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
const heads = useVcs((s) => s.heads);
const projectRoots = useEffectiveRoots();
const roots = useMemo(
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads),
[status, root, groupByDir, lists, repos, groupByStaging, heads],
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo),
[status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo],
);
const [byKey, parents] = useMemo(() => {
const m = new Map<string, ChangeNode>();
@@ -703,6 +705,10 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) },
...(mode === "local"
? [
+45 -1
Переглянути файл
@@ -10,12 +10,23 @@ const mocks = vi.hoisted(() => ({
restoreBranch: vi.fn(),
branches: vi.fn(),
rename: vi.fn(),
ask: vi.fn(),
checkout: vi.fn(),
executeAction: vi.fn(),
}));
vi.mock("../dialogs", async (original) => ({
...(await original<typeof import("../dialogs")>()),
promptText: mocks.prompt,
confirmDialog: mocks.confirm,
}));
vi.mock("@/workbench/messages", async (original) => ({
...(await original<typeof import("@/workbench/messages")>()),
ask: mocks.ask,
}));
vi.mock("@/platform/actions", async (original) => ({
...(await original<typeof import("@/platform/actions")>()),
executeAction: mocks.executeAction,
}));
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify, expire: vi.fn() }) }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
@@ -29,10 +40,11 @@ vi.mock("@/platform/ipc", async (original) => {
vcsRestoreBranch: mocks.restoreBranch,
vcsBranches: mocks.branches,
vcsRenameBranch: mocks.rename,
vcsCheckout: mocks.checkout,
},
};
});
import { deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps";
import { checkoutBranch, deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps";
import { useVcs } from "../store";
import { useProject } from "@/platform/project";
@@ -175,6 +187,38 @@ it("deletes a worktree holding the branch before deleting it", async () => {
expect(mocks.deleteBranch).toHaveBeenCalledWith("/p/front", "feature/wt");
});
it("offers to open the worktree that has the branch checked out", async () => {
mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }));
mocks.ask.mockResolvedValue({ button: "open" });
await checkoutBranch("feature/wt");
expect(mocks.checkout).toHaveBeenCalledWith("/p/front", "feature/wt", false, { mode: "normal", diverged: null });
expect(mocks.ask.mock.calls[0]?.[0].title).toBe("Worktree Conflict");
expect(mocks.ask.mock.calls[0]?.[0].body).toContain("already checked out in a worktree at:\n/p/front-wt");
expect(mocks.executeAction).toHaveBeenCalledWith("file.openProjectPath", "/p/front-wt");
expect(mocks.checkout).toHaveBeenCalledTimes(1);
});
it("checks the branch out anyway when asked, alongside the other worktree", async () => {
mocks.checkout
.mockResolvedValueOnce(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }))
.mockResolvedValueOnce(ok({ kind: "done" }));
mocks.ask.mockResolvedValue({ button: "anyway" });
await checkoutBranch("feature/wt");
expect(mocks.checkout).toHaveBeenLastCalledWith("/p/front", "feature/wt", false, {
mode: "normal",
diverged: null,
ignoreOtherWorktrees: true,
});
expect(mocks.executeAction).not.toHaveBeenCalled();
});
it("does not open the worktree when the checkout offer is declined", async () => {
mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }));
mocks.ask.mockResolvedValue({ button: "cancel" });
await checkoutBranch("feature/wt");
expect(mocks.executeAction).not.toHaveBeenCalled();
});
it("keeps the branch when the worktree question is turned down", async () => {
mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")]));
mocks.confirm.mockResolvedValue(false);
+91
Переглянути файл
@@ -229,6 +229,97 @@ describe("several repositories", () => {
});
});
describe("Group By › Repository off", () => {
const at = (path: string, unstaged: FileStatus["unstaged"] = "modified", staged: FileStatus["staged"] = null) => ({
path,
relPath: path.split("/").slice(3).join("/"),
staged,
unstaged,
renamedFrom: null,
});
// Two repositories holding the same repository-relative path.
const repos = ["/w/api", "/w/sdk"];
const twins = [at("/w/api/src/config.ts"), at("/w/sdk/src/config.ts"), at("/w/sdk/src/client.ts")];
const keys = (nodes: readonly ChangeNode[]): string[] => nodes.flatMap((n) => [n.key, ...keys(n.children ?? [])]);
const files = (nodes: readonly ChangeNode[]) =>
changeFileNodes(nodes).map((n) => `${n.label} ${n.path} ${n.detail || "-"}`);
it("lists the files of all repositories together, told apart by their directory", () => {
const tree = buildChangeTree(twins, "/w", false, undefined, repos, false, {}, false);
expect(shape(tree)).toEqual(["Changes", " client.ts", " config.ts", " config.ts"]);
expect(files(tree)).toEqual([
"client.ts /w/sdk/src/client.ts sdk/src",
"config.ts /w/api/src/config.ts api/src",
"config.ts /w/sdk/src/config.ts sdk/src",
]);
const all = keys(tree);
expect(new Set(all).size).toBe(all.length);
});
it("keeps directory grouping, with each repository's directories apart", () => {
const tree = buildChangeTree(twins, "/w", true, undefined, repos, false, {}, false);
expect(shape(tree)).toEqual([
"Changes",
" api/src",
" config.ts",
" sdk/src",
" client.ts",
" config.ts",
]);
expect(tree[0]!.children!.map((n) => [n.path, n.files.length])).toEqual([
["/w/api/src", 1],
["/w/sdk/src", 2],
]);
const all = keys(tree);
expect(new Set(all).size).toBe(all.length);
});
it("shows a repository outside the project by its absolute directory", () => {
const outside = [at("/w/README.md"), at("/x/lib/src/Lib.kt")];
const flat = buildChangeTree(outside, "/w", false, undefined, ["/w", "/x/lib"], false, {}, false);
expect(files(flat)).toEqual(["Lib.kt /x/lib/src/Lib.kt /x/lib/src", "README.md /w/README.md -"]);
const dirs = buildChangeTree(outside, "/w", true, undefined, ["/w", "/x/lib"], false, {}, false);
expect(shape(dirs)).toEqual(["Changes", " /x/lib/src", " Lib.kt", " README.md"]);
expect(dirs[0]!.children![0]!.path).toBe("/x/lib/src");
});
it("applies to every group, staging groups and change lists included", () => {
const mixed = [...twins, at("/w/api/new.txt", "untracked"), at("/w/sdk/src/both.ts", "modified", "modified")];
const noRepoNodes = (tree: ChangeNode[]) =>
tree.every((g) => g.children!.every((n) => n.type === "file" && !repos.includes(n.path!)));
expect(noRepoNodes(buildChangeTree(mixed, "/w", false, undefined, repos, false, {}, false))).toBe(true);
expect(noRepoNodes(buildChangeTree(mixed, "/w", false, undefined, repos, true, {}, false))).toBe(true);
const lists = { active: "default", lists: [{ id: "default", name: "Changes", comment: "" }], files: {} };
const listed = buildChangeTree(mixed, "/w", false, lists as never, repos, false, {}, false);
expect(noRepoNodes(listed)).toBe(true);
expect(changeFileNodes(listed).every((n) => n.changelist === "default" || n.group === "unversioned")).toBe(true);
});
it("checks and commits files of every repository from the one flat group", () => {
const [changes] = buildChangeTree(twins, "/w", false, undefined, repos, false, {}, false);
expect(aggregateCheck(changes!.files, new Map())).toMatchObject({ checked: true, on: 3 });
const checks = new Map<string, CheckState>([["/w/api/src/config.ts", "none"]]);
expect(aggregateCheck(changes!.files, checks)).toMatchObject({ checked: false, indeterminate: true, on: 2 });
const plan = planCommit(twins, checks);
expect(plan.included.map((f) => f.path)).toEqual(["/w/sdk/src/config.ts", "/w/sdk/src/client.ts"]);
expect(commitRepos(planCommit(twins, new Map()).included, repos, "/w/api")).toEqual(["/w/sdk", "/w/api"]);
});
it("is on by default: a repository level as before", () => {
expect(buildChangeTree(twins, "/w", true, undefined, repos, false, {})).toEqual(
buildChangeTree(twins, "/w", true, undefined, repos, false, {}, true),
);
expect(shape(buildChangeTree(twins, "/w", false, undefined, repos))).toEqual([
"Changes",
" api",
" config.ts",
" sdk",
" client.ts",
" config.ts",
]);
});
});
describe("ignore targets", () => {
const group = (roots: ChangeNode[], id: string) => roots.find((n) => n.group === id)!;
+127
Переглянути файл
@@ -0,0 +1,127 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, call: vi.fn() };
});
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
import { ChangesTree } from "../CommitView";
import { setGroupByRepo, useCommit } from "../commitStore";
import { useVcs } from "../store";
import { useProject } from "@/platform/project";
import { useContextMenuStore, type MenuItem } from "@/ui/Menu";
const change = (path: string) => ({
path,
relPath: path.split("/").slice(3).join("/"),
staged: null,
unstaged: "modified" as const,
renamedFrom: null,
});
/** The Group By items of the View Options menu: label → checked. */
function groupByItems(): Record<string, boolean> {
act(() => {
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
});
const items = useContextMenuStore.getState().menu!.items as Array<MenuItem & { label?: string; checked?: boolean }>;
act(() => useContextMenuStore.setState({ menu: null }));
const end = items.findIndex((i) => i.kind === "separator");
return Object.fromEntries(
items
.slice(0, end < 0 ? undefined : end)
.filter((i) => i.kind !== "header" && i.label)
.map((i) => [i.label!, !!i.checked]),
);
}
function runItem(label: string) {
act(() => {
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
});
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label) as {
run: () => void;
};
act(() => {
item.run();
useContextMenuStore.setState({ menu: null });
});
}
describe("Group By › Repository in the changes tree", () => {
beforeEach(() => {
localStorage.clear();
useCommit.setState({
groupByDir: false,
groupByStaging: false,
groupByRepo: true,
checks: new Map(),
selection: [],
});
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
useVcs.setState({
root: "/p",
repo: "/p",
roots: ["/p", "/p/orders"],
status: [change("/p/src/App.kt"), change("/p/orders/src/App.kt")],
heads: {},
});
});
it("is offered, checked, with several repositories", () => {
render(<ChangesTree mode="commit" />);
expect(groupByItems()).toEqual({ Directory: false, Repository: true, "Staging State": false });
});
it("is not offered with one repository", () => {
useVcs.setState({ roots: ["/p"], status: [change("/p/src/App.kt")] });
render(<ChangesTree mode="commit" />);
expect(groupByItems()).toEqual({ Directory: false, "Staging State": false });
});
it("unchecked, lists both repositories' files together and remembers the choice", () => {
render(<ChangesTree mode="commit" />);
expect(screen.getByText("orders")).toBeTruthy();
runItem("Repository");
expect(useCommit.getState().groupByRepo).toBe(false);
expect(localStorage.getItem("openidea.vcs.groupByRepo")).toBe("false");
expect(screen.queryByText("orders")).toBeNull();
expect(screen.getAllByText("App.kt")).toHaveLength(2);
expect(screen.getByText("orders/src")).toBeTruthy();
expect(groupByItems().Repository).toBe(false);
// Each file keeps its own checkbox.
const boxes = screen.getAllByRole("checkbox", { name: "Include App.kt in commit" });
expect(boxes).toHaveLength(2);
act(() => {
fireEvent.mouseDown(boxes[0]!);
});
expect([...useCommit.getState().checks]).toEqual([["/p/orders/src/App.kt", "none"]]);
runItem("Repository");
expect(localStorage.getItem("openidea.vcs.groupByRepo")).toBe("true");
expect(screen.getByText("orders")).toBeTruthy();
});
});
describe("Group By › Repository persistence", () => {
beforeEach(() => {
localStorage.clear();
vi.resetModules();
});
it("starts on when nothing is stored", async () => {
const { useCommit: fresh } = await import("../commitStore");
expect(fresh.getState().groupByRepo).toBe(true);
});
it("starts with the stored choice", async () => {
setGroupByRepo(false);
const { useCommit: fresh } = await import("../commitStore");
expect(fresh.getState().groupByRepo).toBe(false);
});
});
+135
Переглянути файл
@@ -0,0 +1,135 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
const mocks = vi.hoisted(() => ({
pushes: [] as Array<{ repo: string | null; message: string | null; paths: string[] | null }>,
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
return {
...real,
commands: {
...real.commands,
vcsBranchInfo: (repo: string | null) =>
ok({
head: repo === "/p/b" ? "dev" : "main",
headCommit: "c1",
upstream: null,
ahead: 0,
behind: 0,
operation: null,
}),
vcsStashPush: (
repo: string | null,
message: string | null,
_untracked: boolean,
_keepIndex: boolean,
paths: string[] | null,
) => {
mocks.pushes.push({ repo, message, paths });
return ok(null);
},
vcsStashes: () => ok([]),
},
};
});
import { VcsDialogHost } from "../dialogs";
import { stashChanges } from "../changeOps";
import { useVcs } from "../store";
beforeEach(() => {
mocks.pushes = [];
useVcs.setState({
root: "/p",
roots: ["/p/a", "/p/b"],
repo: "/p/a",
branch: { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
available: false,
});
});
const pick = async (combo: string, option: string) => {
fireEvent.click(screen.getByRole("button", { name: combo }));
fireEvent.click(await screen.findByRole("option", { name: option }));
};
it("offers no repository choice when the project has one repository", async () => {
useVcs.setState({ roots: ["/p"], repo: null });
render(<VcsDialogHost />);
let done!: Promise<void>;
act(() => {
done = stashChanges();
});
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
await done;
expect(mocks.pushes).toEqual([{ repo: null, message: null, paths: null }]);
});
it("stashes the repository picked in the dialog and shows its branch", async () => {
render(<VcsDialogHost />);
let done!: Promise<void>;
act(() => {
done = stashChanges();
});
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("a");
fireEvent.change(screen.getByRole("textbox", { name: "Message" }), { target: { value: "wip b" } });
await pick("Repository", "b");
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
expect(screen.queryByText("Current branch: main")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
await done;
expect(mocks.pushes).toEqual([{ repo: "/p/b", message: "wip b", paths: null }]);
});
it("starts on the repository it was given and can switch back", async () => {
render(<VcsDialogHost />);
let done!: Promise<void>;
act(() => {
done = stashChanges([], "/p/b");
});
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("b");
await pick("Repository", "a");
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
await done;
expect(mocks.pushes).toEqual([{ repo: "/p/a", message: null, paths: null }]);
});
it("offers no repository choice when stashing selected files, which pick their own repositories", async () => {
render(<VcsDialogHost />);
let done!: Promise<void>;
act(() => {
done = stashChanges(["/p/a/x.ts", "/p/b/y.ts"]);
});
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
await done;
expect(mocks.pushes).toEqual([{ repo: "/p/a", message: null, paths: ["/p/a/x.ts", "/p/b/y.ts"] }]);
});
it("stashes nothing when cancelled after picking another repository", async () => {
render(<VcsDialogHost />);
let done!: Promise<void>;
act(() => {
done = stashChanges();
});
await pick("Repository", "b");
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await done;
await waitFor(() => expect(screen.queryByRole("button", { name: "Repository" })).toBeNull());
expect(mocks.pushes).toEqual([]);
});
+111
Переглянути файл
@@ -0,0 +1,111 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
const mocks = vi.hoisted(() => ({
created: [] as Array<{ repo: string | null; name: string; commit: string; message: string | null; force: boolean }>,
tags: {} as Record<string, Promise<string[]> | string[]>,
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
return {
...real,
commands: {
...real.commands,
vcsTags: async (repo: string | null) => ({ status: "ok" as const, data: await (mocks.tags[repo ?? ""] ?? []) }),
vcsCreateTag: (repo: string | null, name: string, commit: string, message: string | null, force: boolean) => {
mocks.created.push({ repo, name, commit, message, force });
return ok(null);
},
},
};
});
import { VcsDialogHost } from "../dialogs";
import { showTagDialog } from "../operations";
import { useVcs } from "../store";
beforeEach(() => {
mocks.created = [];
mocks.tags = { "/p/a": ["v1.0"], "/p/b": ["v2.0"], "/p": ["v1.0"] };
useVcs.setState({
root: "/p",
roots: ["/p/a", "/p/b"],
repo: "/p/a",
branch: { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
available: false,
});
});
const pick = async (combo: string, option: string) => {
fireEvent.click(screen.getByRole("button", { name: combo }));
fireEvent.click(await screen.findByRole("option", { name: option }));
};
const typeName = (value: string) => fireEvent.change(screen.getByLabelText("Tag name:"), { target: { value } });
it("offers no repository choice when the project has one repository", async () => {
useVcs.setState({ roots: ["/p"], repo: null });
mocks.tags = { "": ["v1.0"] };
render(<VcsDialogHost />);
await act(() => showTagDialog());
expect(await screen.findByText("Tag")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
typeName("v1.0");
expect(await screen.findByText("Tag 'v1.0' already exists")).toBeInTheDocument();
typeName("v1.1");
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
await waitFor(() => expect(mocks.created).toHaveLength(1));
expect(mocks.created[0]).toMatchObject({ repo: null, name: "v1.1", commit: "HEAD" });
});
it("creates the tag in the repository picked in the dialog", async () => {
render(<VcsDialogHost />);
await act(() => showTagDialog());
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("a");
await pick("Repository", "b");
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("b");
typeName("v3.0");
fireEvent.change(screen.getByLabelText("Message:"), { target: { value: "Release" } });
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
await waitFor(() => expect(mocks.created).toHaveLength(1));
expect(mocks.created[0]).toEqual({ repo: "/p/b", name: "v3.0", commit: "HEAD", message: "Release", force: false });
});
it("checks the name against the tags of the picked repository", async () => {
render(<VcsDialogHost />);
await act(() => showTagDialog());
typeName("v1.0");
expect(await screen.findByText("Tag 'v1.0' already exists")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Create Tag" })).toBeDisabled();
// v1.0 exists only in a: the name is free in b, and b's own v2.0 is taken.
await pick("Repository", "b");
await waitFor(() => expect(screen.queryByText("Tag 'v1.0' already exists")).toBeNull());
expect(screen.getByRole("button", { name: "Create Tag" })).toBeEnabled();
typeName("v2.0");
expect(await screen.findByText("Tag 'v2.0' already exists")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(mocks.created).toEqual([]);
});
it("ignores the tags of a repository that is no longer picked", async () => {
let resolveA: (tags: string[]) => void = () => undefined;
mocks.tags["/p/a"] = new Promise<string[]>((resolve) => (resolveA = resolve));
render(<VcsDialogHost />);
await act(() => showTagDialog());
await pick("Repository", "b");
typeName("v1.0");
// a's tags arrive after b was picked: they must not mark v1.0 as taken in b.
await act(async () => resolveA(["v1.0"]));
expect(screen.queryByText("Tag 'v1.0' already exists")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
await waitFor(() => expect(mocks.created).toHaveLength(1));
expect(mocks.created[0]).toMatchObject({ repo: "/p/b", name: "v1.0" });
});
+152
Переглянути файл
@@ -0,0 +1,152 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { Stash } from "@/bindings";
const mocks = vi.hoisted(() => ({
stashes: new Map<string | null, Stash[]>(),
drops: [] as Array<{ repo: string | null; index: number }>,
diffs: [] as Array<{ repo: string | null; from: string; to: string }>,
applies: [] as Array<{ repo: string | null; index: number }>,
confirm: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
return {
...real,
commands: {
...real.commands,
vcsStashes: (repo: string | null) => ok(mocks.stashes.get(repo) ?? []),
vcsStashDrop: (repo: string | null, index: number) => {
mocks.drops.push({ repo, index });
const list = mocks.stashes.get(repo) ?? [];
mocks.stashes.set(
repo,
list.filter((s) => s.index !== index).map((s) => (s.index > index ? { ...s, index: s.index - 1 } : s)),
);
return ok(null);
},
vcsStashApply: (repo: string | null, index: number) => {
mocks.applies.push({ repo, index });
return ok(null);
},
vcsDiffRevisions: (repo: string | null, from: string, to: string) => {
mocks.diffs.push({ repo, from, to });
return ok([{ path: "src/a.ts", kind: "modified", oldPath: null }]);
},
},
};
});
vi.mock("../dialogs", async (importOriginal) => ({
...(await importOriginal<typeof import("../dialogs")>()),
confirmDialog: mocks.confirm,
}));
import { VcsDialogHost } from "../dialogs";
import { showUnstashDialog } from "../changeOps";
import { useVcs } from "../store";
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null });
beforeEach(() => {
mocks.stashes = new Map([
["/p/a", [stash(0, "On main: a0")]],
["/p/b", [stash(0, "On dev: first"), stash(1, "On dev: second"), stash(2, "On dev: third")]],
]);
mocks.drops = [];
mocks.diffs = [];
mocks.applies = [];
mocks.confirm.mockReset().mockResolvedValue(true);
useVcs.setState({ root: "/p", roots: ["/p/a", "/p/b"], repo: "/p/a", available: false });
});
afterEach(() => {
// Dialogs live in a module store: close what a test left open.
for (let open = screen.queryAllByRole("dialog"); open.length; open = screen.queryAllByRole("dialog")) {
const before = open.length;
fireEvent.keyDown(open[open.length - 1]!, { key: "Escape" });
if (screen.queryAllByRole("dialog").length === before) break;
}
});
const radio = (name: string) => screen.getByRole("radio", { name: new RegExp(name.replace(/[{}@]/g, "\\$&")) });
it("disables Show Changes and Drop Stash when there is no stash", async () => {
mocks.stashes.set("/p/a", []);
render(<VcsDialogHost />);
act(() => showUnstashDialog(0, "/p/a"));
expect(await screen.findByText("No stashes")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Show Changes" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Drop Stash" })).toBeDisabled();
});
it("views the changes of the selected stash in the dialog's repository", async () => {
render(<VcsDialogHost />);
act(() => showUnstashDialog(0, "/p/b"));
await screen.findByText("stash@{0}: On dev: first");
fireEvent.click(radio("stash@{1}"));
fireEvent.click(screen.getByRole("button", { name: "Show Changes" }));
await waitFor(() => expect(mocks.diffs).toEqual([{ repo: "/p/b", from: "stash@{1}^", to: "stash@{1}" }]));
expect(await screen.findByText(/Changes between stash@\{1\}\^ and stash@\{1\}/)).toBeInTheDocument();
// The Unstash dialog stays open behind the changes, nothing applied or dropped.
expect(screen.getByText("stash@{2}: On dev: third")).toBeInTheDocument();
expect(mocks.applies).toEqual([]);
expect(mocks.drops).toEqual([]);
});
it("drops the selected stash after confirming, refreshes the list and selects the next one", async () => {
render(<VcsDialogHost />);
act(() => showUnstashDialog(0, "/p/b"));
await screen.findByText("stash@{0}: On dev: first");
fireEvent.click(radio("stash@{1}"));
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
await waitFor(() => expect(mocks.drops).toEqual([{ repo: "/p/b", index: 1 }]));
expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Drop Stash", danger: true }));
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
// The older stash moved up into the dropped one's place and is selected.
expect(screen.getByText("stash@{1}: On dev: third")).toBeInTheDocument();
expect(radio("stash@{1}")).toBeChecked();
expect(radio("stash@{0}")).not.toBeChecked();
// The dialog stays open and acts on the refreshed list.
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
await waitFor(() => expect(mocks.applies).toEqual([{ repo: "/p/b", index: 1 }]));
});
it("selects the new last stash after dropping the last one, and disables both when none is left", async () => {
mocks.stashes.set("/p/b", [stash(0, "On dev: first"), stash(1, "On dev: second")]);
render(<VcsDialogHost />);
act(() => showUnstashDialog(1, "/p/b"));
await screen.findByText("stash@{1}: On dev: second");
expect(radio("stash@{1}")).toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
expect(radio("stash@{0}")).toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
expect(await screen.findByText("No stashes")).toBeInTheDocument();
expect(mocks.drops).toEqual([
{ repo: "/p/b", index: 1 },
{ repo: "/p/b", index: 0 },
]);
expect(screen.getByRole("button", { name: "Show Changes" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Drop Stash" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
});
it("keeps the stash when the drop is not confirmed", async () => {
mocks.confirm.mockResolvedValue(false);
render(<VcsDialogHost />);
act(() => showUnstashDialog(0, "/p/a"));
await screen.findByText("stash@{0}: On main: a0");
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
expect(mocks.drops).toEqual([]);
expect(screen.getByText("stash@{0}: On main: a0")).toBeInTheDocument();
expect(radio("stash@{0}")).toBeChecked();
});
+2
Переглянути файл
@@ -431,6 +431,8 @@ export function registerVcsActions(): () => void {
useChangelists.getState().state,
state.roots,
useCommit.getState().groupByStaging,
undefined,
useCommit.getState().groupByRepo,
);
// The modal interface has one front diff window (#1863): a file with its group
// as the F7 chain, or several selected files as the chain.
+18
Переглянути файл
@@ -132,6 +132,24 @@ async function performCheckout(
options = { ...options, diverged: r.button };
continue;
}
case "checkedOutInWorktree": {
const { branch, path } = outcome;
const r = await ask({
title: "Worktree Conflict",
body: tx`Branch '${branch}' is already checked out in a worktree at:\n${path}`,
buttons: [
{ id: "anyway", label: "Checkout Anyway", primary: true },
{ id: "open", label: "Open Existing Worktree" },
{ id: "cancel", label: "Cancel" },
],
});
if (r.button === "anyway") {
options = { ...options, ignoreOtherWorktrees: true };
continue;
}
if (r.button === "open") await executeAction("file.openProjectPath", path);
return false;
}
}
}
}
+41 -10
Переглянути файл
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react";
import type { FileStatus, Stash } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, Input, T, fileIconName } from "@/ui";
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { groupOf, remainingOverrides, renamedFromPath } from "./changes";
import { runCommitChecks } from "./commitChecks";
@@ -11,8 +11,10 @@ import { forgetAmendDraft, keepMessageAfterCommit, rememberMessage, useCommit }
import { workflowSettings } from "@/platform/workflowSettings";
import { notifyFileOperation } from "@/platform/fileOps";
import { confirmDialog, openDialog } from "./dialogs";
import { RepoPicker, useBranchInfo } from "./gitMenuDialogs";
import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, stripSlash } from "./model";
import { logConsole, runOp, saveAll } from "./ops";
import { showCompareRevisions } from "./operations";
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
@@ -304,11 +306,16 @@ export async function addToVcs(paths: readonly string[]) {
);
}
/** Stash Changes dialog: message, Keep index (staged changes stay), include untracked files. */
/**
* Stash Changes dialog: message, Keep index (staged changes stay), include untracked files.
* `repo`: the repository it starts on; selected `paths` stash in the repositories holding them.
*/
export function stashChanges(paths: readonly string[] = [], repo = currentRepo()): Promise<void> {
return new Promise((resolve) => {
const close = openDialog(() => (
<StashDialog
initialRepo={repo}
pickRepo={!paths.length}
onDone={async (r) => {
close();
if (r) {
@@ -318,7 +325,7 @@ export function stashChanges(paths: readonly string[] = [], repo = currentRepo()
() =>
call(
commands.vcsStashPush(
repo,
r.repo,
r.message || null,
r.includeUntracked,
r.keepIndex,
@@ -337,15 +344,20 @@ export function stashChanges(paths: readonly string[] = [], repo = currentRepo()
}
function StashDialog({
initialRepo,
pickRepo,
onDone,
}: {
onDone: (r: { message: string; keepIndex: boolean; includeUntracked: boolean } | null) => void;
initialRepo: string | null;
pickRepo: boolean;
onDone: (r: { repo: string | null; message: string; keepIndex: boolean; includeUntracked: boolean } | null) => void;
}) {
const [repo, setRepo] = useState(initialRepo);
const [message, setMessage] = useState("");
const [keepIndex, setKeepIndex] = useState(false);
const [includeUntracked, setIncludeUntracked] = useState(false);
const branch = useVcs((s) => s.branch?.head ?? null);
const submit = () => onDone({ message: message.trim(), keepIndex, includeUntracked });
const branch = useBranchInfo(repo)?.head ?? null;
const submit = () => onDone({ repo, message: message.trim(), keepIndex, includeUntracked });
return (
<Dialog
open
@@ -364,6 +376,7 @@ function StashDialog({
submit();
}}
>
{pickRepo && <RepoPicker repo={repo} onChange={setRepo} />}
{branch && <div className={styles.hint}>{tx`Current branch: ${branch}`}</div>}
<label className={styles.fieldLabel}>
<T>Message:</T>
@@ -415,13 +428,14 @@ export function applyStash(index: number, pop: boolean, repo = currentRepo()) {
return unstash({ index, pop, reinstateIndex: false, branch: null }, repo);
}
/** Unstash Changes dialog: pick a stash; Pop, Reinstate index, or As new branch. */
/** Unstash Changes dialog: pick a stash; Pop, Reinstate index, or As new branch; view or drop it. */
export function showUnstashDialog(index = 0, repo = currentRepo()) {
openDialog((close) => <UnstashDialog initial={index} repo={repo} onClose={close} />);
}
function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: string | null; onClose: () => void }) {
const [stashes, setStashes] = useState<Stash[]>([]);
const [tick, setTick] = useState(0);
useEffect(() => {
let live = true;
void call(commands.vcsStashes(repo))
@@ -430,13 +444,24 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
return () => {
live = false;
};
}, [repo]);
}, [repo, tick]);
const [index, setIndex] = useState(initial);
const [pop, setPop] = useState(false);
const [reinstateIndex, setReinstateIndex] = useState(false);
const [branch, setBranch] = useState("");
const asBranch = branch.trim();
const chosen = stashes.find((s) => s.index === index) ?? stashes[0];
const view = () => {
if (!chosen) return;
const ref = `stash@{${chosen.index}}`;
showCompareRevisions(`${ref}^`, ref, `${ref}^`, ref, repo);
};
const drop = async () => {
if (!chosen || !(await dropStash(chosen.index, chosen.message, repo))) return;
// The older stashes move up: the next one takes the dropped one's index, else the new last one.
setIndex(Math.max(0, Math.min(chosen.index, stashes.length - 2)));
setTick((n) => n + 1);
};
const submit = () => {
if (!chosen) return;
onClose();
@@ -465,6 +490,10 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
submit();
}}
>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Stashes")}>
<IconButton icon="diff" title="Show Changes" size="small" disabled={!chosen} onClick={view} />
<IconButton icon="trash" title="Drop Stash" size="small" disabled={!chosen} onClick={() => void drop()} />
</div>
<div className={styles.choiceList} role="radiogroup" aria-label={tx("Stashes")}>
{stashes.length === 0 && (
<div className={styles.hint}>
@@ -496,7 +525,8 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
);
}
export async function dropStash(index: number, message: string, repo = currentRepo()) {
/** Drops the stash once confirmed; whether it was confirmed. */
export async function dropStash(index: number, message: string, repo = currentRepo()): Promise<boolean> {
const ok = await confirmDialog({
title: "Drop Stash",
message: message
@@ -505,9 +535,10 @@ export async function dropStash(index: number, message: string, repo = currentRe
okLabel: "Drop",
danger: true,
});
if (!ok) return;
if (!ok) return false;
await runOp(tx`Drop ${`stash@{${index}}`}`, () => call(commands.vcsStashDrop(repo, index)), {
success: tx`Dropped ${`stash@{${index}}`}`,
});
void loadStashes().catch((e) => logConsole("err", String(e)));
return true;
}
+17 -8
Переглянути файл
@@ -122,6 +122,8 @@ function fileNode(fs: FileStatus, root: string, group: GroupId, flat: boolean, s
interface Trie {
dirs: Map<string, Trie>;
files: FileStatus[];
/** Absolute path of the directory. */
path?: string;
}
function dirNodes(trie: Trie, prefix: string, root: string, group: GroupId, scope: string = group): ChangeNode[] {
@@ -147,7 +149,7 @@ function dirNodes(trie: Trie, prefix: string, root: string, group: GroupId, scop
group,
children,
files,
path: `${root}/${rel}`,
path: node.path!,
});
}
const files = [...trie.files].sort((a, b) => baseName(a.path).localeCompare(baseName(b.path)));
@@ -165,13 +167,18 @@ function childNodes(files: readonly FileStatus[], root: string, group: GroupId,
if (groupByDir) {
const trie: Trie = { dirs: new Map(), files: [] };
for (const f of files) {
const rel = relTo(root, stripSlash(f.path));
const path = stripSlash(f.path);
const rel = relTo(root, path);
const parts = rel.split("/");
parts.pop();
// Outside the root (a repository elsewhere, not grouped by repository): from its absolute path.
if (rel === path && parts[0] === "" && parts.length > 1) parts.splice(0, 2, `/${parts[1]}`);
let t = trie;
let at = rel === path ? "" : `${root}/`;
for (const p of parts) {
at += t === trie ? p : `/${p}`;
let next = t.dirs.get(p);
if (!next) t.dirs.set(p, (next = { dirs: new Map(), files: [] }));
if (!next) t.dirs.set(p, (next = { dirs: new Map(), files: [], path: at }));
t = next;
}
t.files.push(f);
@@ -236,8 +243,8 @@ function tagList(nodes: ChangeNode[], id: string): ChangeNode[] {
* children. With change lists, "Changes" is split into one group per list
* (`ChangelistState.files` keys are project-relative paths). With several
* repositories (`repos`), each group's files are grouped by repository first, with
* each repository's branch (`heads`) beside its name. With `byStaging`, "Changes"
* becomes "Staged Changes" and "Unstaged Changes" instead.
* each repository's branch (`heads`) beside its name, unless `byRepo` is off. With
* `byStaging`, "Changes" becomes "Staged Changes" and "Unstaged Changes" instead.
*/
export function buildChangeTree(
status: readonly FileStatus[],
@@ -247,7 +254,9 @@ export function buildChangeTree(
repos: readonly string[] = [],
byStaging = false,
heads: Readonly<Record<string, RepoHead>> = {},
byRepo = true,
): ChangeNode[] {
const repoRoots = byRepo ? repos : [];
const byGroup = new Map<GroupId, FileStatus[]>();
for (const fs of status) {
const g = groupOf(fs);
@@ -267,7 +276,7 @@ export function buildChangeTree(
];
for (const [side, own] of sides) {
if (!own.length) continue;
const children = repoNodes(own, root, side, groupByDir, side, repos, heads);
const children = repoNodes(own, root, side, groupByDir, side, repoRoots, heads);
roots.push({
key: `group:${side}`,
type: "group",
@@ -295,7 +304,7 @@ export function buildChangeTree(
type: "group",
label: l.name,
group: g,
children: tagList(repoNodes(own, root, g, groupByDir, scope, repos, heads), l.id),
children: tagList(repoNodes(own, root, g, groupByDir, scope, repoRoots, heads), l.id),
files: own,
changelist: l.id,
active: l.id === lists.active,
@@ -305,7 +314,7 @@ export function buildChangeTree(
continue;
}
if (!files.length) continue;
const children = repoNodes(files, root, g, groupByDir, g, repos, heads);
const children = repoNodes(files, root, g, groupByDir, g, repoRoots, heads);
roots.push({ key: `group:${g}`, type: "group", label: GROUP_LABEL[g], group: g, children, files });
}
return roots;
+12
Переглянути файл
@@ -17,6 +17,8 @@ interface CommitState {
groupByDir: boolean;
/** Group the changes into Staged / Unstaged instead of one "Changes" group. */
groupByStaging: boolean;
/** With several repositories, a node per repository above their files. */
groupByRepo: boolean;
/** Whether the Git window's Local Changes tab previews the selection's diff. */
diffPreview: boolean;
/** Whether the Commit tool window previews the selection's diff beside the changes (#1599). */
@@ -54,6 +56,7 @@ export const useCommit = create<CommitState>(() => ({
runHooks: true,
groupByDir: readBool("openidea.vcs.groupByDir", false),
groupByStaging: readBool("openidea.vcs.groupByStaging", false),
groupByRepo: readBool("openidea.vcs.groupByRepo", true),
diffPreview: readBool("openidea.vcs.diffPreview", true),
commitDiffPreview: readBool("openidea.vcs.commitDiffPreview", false),
checks: new Map(),
@@ -104,6 +107,15 @@ export function setGroupByStaging(v: boolean) {
}
}
export function setGroupByRepo(v: boolean) {
useCommit.setState({ groupByRepo: v });
try {
localStorage.setItem("openidea.vcs.groupByRepo", String(v));
} catch {
// ignore
}
}
export function setDiffPreview(v: boolean) {
useCommit.setState({ diffPreview: v });
try {
+2 -2
Переглянути файл
@@ -135,7 +135,7 @@ export function showPullDialog(repo?: string | null) {
}
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
export function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
const [roots] = useState(() => useVcs.getState().roots);
if (roots.length < 2) return null;
return (
@@ -149,7 +149,7 @@ function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root:
}
/** The repository's branch info: the store's for the selected repository, else read from git. */
function useBranchInfo(repo: string | null) {
export function useBranchInfo(repo: string | null) {
const [initial] = useState(() => ({ repo: currentRepo(), info: useVcs.getState().branch }));
const [loaded, setLoaded] = useState<{ repo: string | null; info: BranchInfo | null } | null>(null);
useEffect(() => {
+28 -11
Переглянути файл
@@ -27,6 +27,7 @@ import { buildFileTree, type FileTreeNode } from "./fileTree";
import { tx } from "@/platform/i18n";
import { displayPath } from "./compareData";
import { repositoryPath } from "./repositoryPaths";
import { RepoPicker } from "./gitMenuDialogs";
// ---------------------------------------------------------------------------
// Operation in progress
@@ -437,15 +438,27 @@ export function showTagDialog() {
}
function TagDialog({ onClose }: { onClose: () => void }) {
const [repo] = useState(currentRepo);
const [repo, setRepo] = useState(currentRepo);
const [name, setName] = useState("");
const [commit, setCommit] = useState("HEAD");
const [message, setMessage] = useState("");
const [force, setForce] = useState(false);
const [existing, setExisting] = useState<string[]>([]);
useEffect(() => {
void call(commands.vcsTags(repo)).then(setExisting, () => undefined);
}, []);
let live = true;
void call(commands.vcsTags(repo)).then(
(tags) => live && setExisting(tags),
() => undefined,
);
return () => {
live = false;
};
}, [repo]);
const chooseRepo = (root: string) => {
if (root === repo) return;
setRepo(root);
setExisting([]);
};
const error = validateTagName(name, force ? [] : existing);
const run = async () => {
if (error) return;
@@ -470,6 +483,7 @@ function TagDialog({ onClose }: { onClose: () => void }) {
]}
>
<div className={styles.form}>
<RepoPicker repo={repo} onChange={chooseRepo} />
<label className={styles.fieldLabel} htmlFor="openidea-tag-name">
<T>Tag name:</T>
</label>
@@ -518,21 +532,21 @@ export function showCompareVersions(older: Commit, newer: Commit) {
showComparison({ rev: older.id, label: short(older.id) }, { rev: newer.id, label: short(newer.id) });
}
/** Files that differ between two revisions (e.g. two branches from Compare with Current). */
export function showCompareRevisions(from: string, to: string, fromLabel = from, toLabel = to) {
showComparison({ rev: from, label: fromLabel }, { rev: to, label: toLabel });
/** Files that differ between two revisions (e.g. two branches from Compare with Current) of `repo`. */
export function showCompareRevisions(from: string, to: string, fromLabel = from, toLabel = to, repo = currentRepo()) {
showComparison({ rev: from, label: fromLabel }, { rev: to, label: toLabel }, undefined, repo);
}
export function showPathComparison(paths: string[], rev: string, repositories: string[] | null) {
showComparison({ rev, label: rev }, null, { paths, repositories });
}
function showComparison(from: Revision, to: Revision | null, scope?: ScopedComparison) {
function showComparison(from: Revision, to: Revision | null, scope?: ScopedComparison, repo = currentRepo()) {
if (!isTauri()) {
openDialog((close) => <ChangesBetweenDialog from={from} to={to} scope={scope} onClose={close} />);
openDialog((close) => <ChangesBetweenDialog from={from} to={to} scope={scope} repo={repo} onClose={close} />);
return;
}
const comparison = { from, to, scope: scope ?? null, repo: currentRepo() };
const comparison = { from, to, scope: scope ?? null, repo };
void call(commands.windowOpenComparison(comparison, windowBackgroundHex())).catch((error) =>
notifications().notify({ level: "error", title: "Could not open comparison", body: String(error) }),
);
@@ -596,6 +610,7 @@ export function ChangesBetweenDialog({
from,
to,
scope,
repo: givenRepo,
onClose,
native = false,
onCaption,
@@ -607,6 +622,8 @@ export function ChangesBetweenDialog({
from: Revision;
to: Revision | null;
scope?: ScopedComparison;
/** The repository compared (the selected one when omitted). */
repo?: string | null;
onClose: () => void;
/** Content of the comparison window rather than a dialog: its caption goes to `onCaption`. */
native?: boolean;
@@ -619,8 +636,8 @@ export function ChangesBetweenDialog({
/** Files only, each diff opening in the editor (the Compare tool window's narrow sidebar). */
listOnly?: boolean;
}) {
const [root] = useState(currentRepoRoot);
const [repo] = useState(currentRepo);
const [repo] = useState(() => (givenRepo === undefined ? currentRepo() : givenRepo));
const [root] = useState(() => repo ?? currentRepoRoot());
const [files, setFiles] = useState<ComparisonFile[] | null>(null);
const [result, setResult] = useState<CompareResult | null>(null);
const [error, setError] = useState<string | null>(null);
+14 -2
Переглянути файл
@@ -130,7 +130,11 @@
margin: 1.5em 0;
}
.preview :global(img) {
max-width: 100%;
max-width: calc(100% * var(--markdown-zoom-scale, 1));
}
.preview :global(img[data-natural-width]) {
width: calc(min(var(--image-width), 100%) * var(--markdown-zoom-scale, 1));
height: auto;
}
.preview :global(ul.contains-task-list) {
list-style: none;
@@ -155,10 +159,18 @@
display: none;
}
.preview :global(.mermaid-output) {
overflow: hidden;
overflow-x: auto;
overflow-y: hidden;
text-align: center;
}
.preview :global(.mermaid-output svg[data-natural-width]) {
display: block;
margin: 0 auto;
width: calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1));
height: auto;
}
.preview :global(.mermaid-output[data-zoomed="true"]) {
overflow: hidden;
cursor: grab;
touch-action: none;
user-select: none;
+30 -4
Переглянути файл
@@ -51,6 +51,7 @@ import {
resolveLink,
slugify,
} from "./render";
import { applyImageZoomWidth, svgDataUrlSize } from "./svgSize";
import styles from "./Markdown.module.css";
import { tx } from "@/platform/i18n";
@@ -110,6 +111,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const text = useLiveMarkdown((s) => s[path]?.text);
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
const fontSize = useMarkdownPreviewFontSize();
const zoomScale = Number((Math.max(4, fontSize + fontZoom) / fontSize).toFixed(4));
const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0);
const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0);
const caretLine = useLiveMarkdown((s) => s[path]?.caretLine ?? 0);
@@ -161,10 +163,32 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const root = ref.current;
if (!root) return;
let live = true;
root.querySelectorAll<HTMLImageElement>("img[data-src]").forEach((img) => {
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
const svgSize = svgDataUrlSize(url);
if (svgSize && applyImageZoomWidth(img, svgSize) && asyncLoad) {
setDiagramsDrawn((n) => n + 1);
}
img.onload = () => {
if (!live) return;
if (!img.hasAttribute("data-natural-width") && img.naturalWidth > 0 && img.naturalHeight > 0) {
if (applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight })) {
setDiagramsDrawn((n) => n + 1);
}
} else if (asyncLoad) {
setDiagramsDrawn((n) => n + 1);
}
};
img.src = url;
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight });
}
};
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
imgs.forEach((img) => {
applyImageZoomWidth(img);
const src = img.dataset.src ?? "";
if (/^data:image\//i.test(src)) {
img.src = src;
bindImageUrl(img, src, false);
return;
}
const target = resolveLink(path, src);
@@ -174,7 +198,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
return;
}
imageUrl(target.path).then(
(url) => live && (img.src = url),
(url) => live && bindImageUrl(img, url, true),
() => live && img.classList.add(styles.blocked!),
);
});
@@ -187,6 +211,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
});
return () => {
live = false;
for (const img of imgs) img.onload = null;
};
}, [html, path]);
@@ -195,7 +220,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const root = ref.current;
if (!root || !sync) return;
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocksOf(root), topLine, root.scrollHeight);
}, [html, topLine, scrollSeq, sync, diagramsDrawn]);
}, [html, topLine, scrollSeq, sync, diagramsDrawn, fontZoom, fontSize]);
// The preview's own scroll offset: tab switches and mode toggles unmount the
// preview, so Preview Only would otherwise start over at the top. Writes made
@@ -376,6 +401,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
{
"--markdown-preview-font-size": `${fontSize}px`,
"--markdown-font-zoom": `${fontZoom}px`,
"--markdown-zoom-scale": String(zoomScale),
} as CSSProperties
}
tabIndex={-1}
+9
Переглянути файл
@@ -396,6 +396,15 @@ describe("mermaid in the markdown preview", () => {
expect(root.querySelector("[data-mermaid]")?.getAttribute("data-mermaid-state")).toBe("pending");
});
it("records a diagram's natural width so preview font zoom scales it without clamping", async () => {
const svg = await renderedSvg(
'<svg id="openidea-mermaid-1" width="100%" style="max-width: 540px;" viewBox="0 0 540 320"><text>flow</text></svg>',
);
expect(svg.hasAttribute("data-natural-width")).toBe(true);
expect(svg.style.getPropertyValue("--diagram-width")).toBe("540px");
expect(svg.style.maxWidth).toBe("calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1))");
});
it("puts full-screen and download tools on a drawn diagram", async () => {
const root = preview(SEQ);
await renderMermaidIn(root).done;
+10 -1
Переглянути файл
@@ -11,6 +11,7 @@ import { attachPanZoom } from "../panZoom";
import { attachDiagramTools, TOOLS_ATTR } from "./mermaidTools";
import { localSvg } from "./localSvg";
import { reid } from "./svgIds";
import { svgElementSize } from "./svgSize";
export const MERMAID_SELECTOR = "[data-mermaid]";
const OUTPUT_CLASS = "mermaid-output";
@@ -250,7 +251,15 @@ function show(block: HTMLElement, result: Result | null, stale?: Node) {
if (block.getAttribute(RENDERED_ATTR) === "ok") {
attachPanZoom(out);
const svg = out.querySelector("svg");
if (svg) attachDiagramTools(block, svg);
if (svg) {
const size = svgElementSize(svg);
if (size) {
svg.dataset.naturalWidth = "";
svg.style.setProperty("--diagram-width", `${Number(size.w.toFixed(2))}px`);
svg.style.maxWidth = "calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1))";
}
attachDiagramTools(block, svg);
}
}
}
+3 -5
Переглянути файл
@@ -11,6 +11,7 @@ import { openLayer, trapTab } from "@/ui/popupState";
import { notifications } from "@/workbench/contributions";
import { attachPanZoom } from "../panZoom";
import { reid } from "./svgIds";
import { svgElementSize } from "./svgSize";
import styles from "./MermaidTools.module.css";
/** Marks the tool strip, so a redrawing block replaces it rather than stacking one. */
@@ -161,11 +162,8 @@ function fittedCopy(svg: SVGSVGElement, availW: number, availH: number): SVGSVGE
}
function naturalSize(svg: SVGSVGElement): { w: number; h: number } {
const box = (svg as SVGSVGElement & { viewBox?: SVGAnimatedRect }).viewBox?.baseVal;
if (box && box.width > 0 && box.height > 0) return { w: box.width, h: box.height };
const width = Number(svg.getAttribute("width"));
const height = Number(svg.getAttribute("height"));
if (width > 0 && height > 0) return { w: width, h: height };
const declared = svgElementSize(svg);
if (declared) return declared;
const rect = svg.getBoundingClientRect();
return { w: rect.width > 0 ? rect.width : 800, h: rect.height > 0 ? rect.height : 600 };
}
+147
Переглянути файл
@@ -0,0 +1,147 @@
/**
* Intrinsic CSS pixel dimensions of SVGs and Markdown preview images, so
* diagrams and embedded `.svg` / raster assets scale with `--markdown-zoom-scale`.
*/
const UNIT_PX: Record<string, number> = {
"": 1,
px: 1,
pt: 96 / 72,
pc: 16,
in: 96,
cm: 96 / 2.54,
mm: 96 / 25.4,
};
/** Parses an absolute SVG/HTML length into CSS pixels (ignoring `%`, `em`, etc.). */
export function parseLengthPx(raw: string | null | undefined): number | null {
if (!raw) return null;
const m = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([a-z%]*)\s*$/i.exec(raw);
if (!m) return null;
const factor = UNIT_PX[m[2]!.toLowerCase()];
if (!factor) return null;
const n = Number(m[1]) * factor;
return Number.isFinite(n) && n > 0 ? n : null;
}
function parsePercent(raw: string | null | undefined): number | null {
if (!raw) return null;
const m = /^\s*(\d+(?:\.\d+)?|\.\d+)%\s*$/.exec(raw);
if (!m) return null;
const n = Number(m[1]);
return Number.isFinite(n) && n > 0 ? n : null;
}
/** Parses `viewBox="minX minY width height"` into `{ w, h }`. */
export function parseViewBoxSize(raw: string | null | undefined): { w: number; h: number } | null {
if (!raw) return null;
const parts = raw
.trim()
.split(/[\s,]+/)
.map(Number);
if (parts.length !== 4) return null;
const w = parts[2]!;
const h = parts[3]!;
return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 ? { w, h } : null;
}
function resolveSvgDims(
style: string | null | undefined,
widthAttr: string | null | undefined,
heightAttr: string | null | undefined,
viewBoxAttr: string | null | undefined,
): { w: number; h: number } | null {
const vb = parseViewBoxSize(viewBoxAttr);
const storedW = parseLengthPx(/(?:^|;)\s*--diagram-width\s*:\s*([^;]+)/i.exec(style ?? "")?.[1]);
const inlineMaxW = parseLengthPx(/(?:^|;)\s*max-width\s*:\s*([^;]+)/i.exec(style ?? "")?.[1]);
const attrW = parseLengthPx(widthAttr);
const attrH = parseLengthPx(heightAttr);
const w = storedW ?? inlineMaxW ?? attrW ?? (attrH && vb ? (attrH * vb.w) / vb.h : (vb?.w ?? null));
if (!w) return null;
const h = attrH ?? (vb ? (w * vb.h) / vb.w : w * 0.75);
return { w, h };
}
/** Intrinsic CSS pixel size of an in-DOM `<svg>`, when declared on the element. */
export function svgElementSize(svg: SVGSVGElement): { w: number; h: number } | null {
const fromAttrs = resolveSvgDims(
svg.getAttribute("style"),
svg.getAttribute("width"),
svg.getAttribute("height"),
svg.getAttribute("viewBox"),
);
if (fromAttrs) return fromAttrs;
const box = (svg as SVGSVGElement & { viewBox?: SVGAnimatedRect }).viewBox?.baseVal;
if (box && box.width > 0 && box.height > 0) return { w: box.width, h: box.height };
return null;
}
function readAttr(tag: string, name: string): string | null {
const re = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i");
const m = re.exec(tag);
return m ? (m[1] ?? m[2] ?? m[3] ?? null) : null;
}
/**
* Intrinsic CSS pixel size of a `data:image/svg+xml` URL from its `<svg>` header.
* Decodes only the leading chunk so large `.excalidraw.svg` scenes stay cheap.
*/
export function svgDataUrlSize(url: string): { w: number; h: number } | null {
const comma = url.indexOf(",");
if (comma < 0) return null;
const header = url.slice(0, comma);
if (!/^data:image\/svg\+xml\b/i.test(header)) return null;
const payload = url.slice(comma + 1, comma + 1 + 16384);
let head: string;
try {
if (/;base64\b/i.test(header)) {
const clean = payload.replace(/\s+/g, "");
const aligned = clean.slice(0, clean.length - (clean.length % 4));
head = atob(aligned);
} else {
const safe = payload.replace(/%[0-9a-f]?$/i, "");
head = decodeURIComponent(safe);
}
} catch {
return null;
}
const withoutComments = head.replace(/<!--[\s\S]*?-->/g, "");
const open = /<svg\b((?:"[^"]*"|'[^']*'|[^'">])*)>/i.exec(withoutComments);
if (!open) return null;
const attrs = open[1]!;
return resolveSvgDims(
readAttr(attrs, "style"),
readAttr(attrs, "width"),
readAttr(attrs, "height"),
readAttr(attrs, "viewBox"),
);
}
const formatPx = (n: number) => `${Number(n.toFixed(2))}px`;
/**
* Sets an `<img>`'s 1× base width so CSS scales it by `--markdown-zoom-scale`,
* respecting explicit HTML `width` / `height` attributes when present.
*/
export function applyImageZoomWidth(img: HTMLImageElement, intrinsic?: { w: number; h: number } | null): boolean {
const rawWidth = img.getAttribute("width");
const pct = parsePercent(rawWidth);
if (pct !== null) {
img.style.width = `calc(${pct}% * var(--markdown-zoom-scale, 1))`;
img.style.height = "auto";
return true;
}
const attrW = parseLengthPx(rawWidth);
if (attrW !== null) {
img.style.setProperty("--image-width", formatPx(attrW));
img.dataset.naturalWidth = "";
return true;
}
if (!intrinsic || intrinsic.w <= 0 || intrinsic.h <= 0) return false;
const attrH = parseLengthPx(img.getAttribute("height"));
const baseW = attrH !== null ? (attrH * intrinsic.w) / intrinsic.h : intrinsic.w;
img.style.setProperty("--image-width", formatPx(baseW));
img.dataset.naturalWidth = "";
return true;
}
+88
Переглянути файл
@@ -101,14 +101,102 @@ describe("editor font size actions", () => {
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
await act(() => executeAction("editor.increaseFontSize"));
await act(() => executeAction("editor.increaseFontSize"));
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("2px");
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1.1538");
await act(() => executeAction("editor.decreaseFontSize"));
await act(() => executeAction("editor.decreaseFontSize"));
await act(() => executeAction("editor.decreaseFontSize"));
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("-1px");
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("0.9231");
await act(() => executeAction("editor.resetFontSize"));
expect(zoom(md)).toBe(0);
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
});
it("sizes embedded excalidraw.svg, graph SVGs and raster images so they scale with font zoom", async () => {
const excalidrawSvg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 940" width="1280" height="940"><!-- svg-source:excalidraw --></svg>';
const excalidrawUrl = `data:image/svg+xml;base64,${btoa(excalidrawSvg)}`;
const graphvizUrl = `data:image/svg+xml;utf8,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="300pt" height="150pt" viewBox="0 0 300 150"></svg>')}`;
const wordmarkUrl = `data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 280 56"></svg>')}`;
const pngUrl = "data:image/png;base64,iVBORw0KGgo=";
const ipc = await import("@/platform/ipc");
const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (p: string) => {
if (p.endsWith("architecture.excalidraw.svg")) return { status: "ok", data: excalidrawUrl };
if (p.endsWith("wordmark.svg")) return { status: "ok", data: wordmarkUrl };
if (p.endsWith("shot.png")) return { status: "ok", data: pngUrl };
return { status: "error", error: { kind: "notFound", message: p } } as never;
});
try {
const doc = [
"![Architecture](./architecture.excalidraw.svg)",
"",
`![Graph](${graphvizUrl})`,
"",
'<img src="./wordmark.svg" alt="Wordmark" height="56">',
"",
'<img src="./wordmark.svg" alt="Icon" width="80">',
"",
"![Shot](./shot.png)",
].join("\n");
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const view = new EditorView({
state: EditorState.create({ doc, extensions: [fontZoom, live.extensions(mdCtx)] }),
});
const handle = { view, ctx: mdCtx };
_addEditor(handle);
disposers.push(() => _removeEditor(handle));
views.push(view);
activate(view);
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, [mdCtx.path]: "preview" } })));
render(
<MarkdownEditor path={mdCtx.path} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await vi.waitFor(() => {
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]');
expect(arch?.getAttribute("src")).toBe(excalidrawUrl);
});
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]')!;
expect(arch.hasAttribute("data-natural-width")).toBe(true);
expect(arch.style.getPropertyValue("--image-width")).toBe("1280px");
const graph = preview.querySelector<HTMLImageElement>('img[alt="Graph"]')!;
expect(graph.hasAttribute("data-natural-width")).toBe(true);
expect(graph.style.getPropertyValue("--image-width")).toBe("400px");
const wordmark = preview.querySelector<HTMLImageElement>('img[alt="Wordmark"]')!;
expect(wordmark.hasAttribute("data-natural-width")).toBe(true);
expect(wordmark.style.getPropertyValue("--image-width")).toBe("280px");
const icon = preview.querySelector<HTMLImageElement>('img[alt="Icon"]')!;
expect(icon.hasAttribute("data-natural-width")).toBe(true);
expect(icon.style.getPropertyValue("--image-width")).toBe("80px");
const shot = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
Object.defineProperty(shot, "naturalWidth", { value: 960, configurable: true });
Object.defineProperty(shot, "naturalHeight", { value: 600, configurable: true });
act(() => {
shot.dispatchEvent(new Event("load"));
});
expect(shot.hasAttribute("data-natural-width")).toBe(true);
expect(shot.style.getPropertyValue("--image-width")).toBe("960px");
} finally {
fsReadImage.mockRestore();
}
});
it("scales a configured editor font size", () => {
+5
Переглянути файл
@@ -50,6 +50,11 @@ export function attachPanZoom(viewport: HTMLElement, options: PanZoomOptions = {
(e) => {
if (!(e.metaKey || e.ctrlKey) || !e.deltaY) return;
e.preventDefault();
if (view.z === origin.z && (viewport.scrollLeft || viewport.scrollTop)) {
view = { ...view, x: view.x - viewport.scrollLeft, y: view.y - viewport.scrollTop };
viewport.scrollLeft = 0;
viewport.scrollTop = 0;
}
const rect = viewport.getBoundingClientRect();
// One wheel notch (~100 px, 3 lines or a page) zooms about 15%; a trackpad
// sends small pixel deltas, so zooming follows the gesture continuously.
+12
Переглянути файл
@@ -94,6 +94,18 @@ export const CLIENT_SETTINGS_KEYS = [
"vcs.commit.nonModal",
"vcs.commit.doubleClickOpensDiff",
"vcs.commit.showRightMargin",
"agents.showContextUsage",
"agents.showWorkTime",
"agents.showUsageLimits",
"agents.showCost",
"agents.foldTurns",
"agents.smoothText",
"agents.fitWindowWidth",
"agents.thinking",
"agents.toolCalls",
"agents.expandToolOutput",
"agents.sendWith",
"agents.whileRunning",
] as const;
export function isClientSetting(key: string): boolean {
+14
Переглянути файл
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
effectiveBindings,
formatBinding,
installKeyboardDispatcher,
isAltGrTyping,
@@ -20,6 +21,19 @@ describe("keymap", () => {
expect(normalizeBinding("meta+K meta+c")).toBe("Meta+K Meta+C");
});
it("serves the effective pairs from cache until the keymap changes", () => {
const initial = useKeymap.getState();
useKeymap.setState({ overrides: { "t.cached": ["Meta+K"] } });
const first = effectiveBindings();
expect(effectiveBindings()).toBe(first);
expect(first).toContainEqual(["Meta+K", "t.cached"]);
useKeymap.setState({ overrides: { "t.cached": ["Meta+L"] } });
const second = effectiveBindings();
expect(second).not.toBe(first);
expect(second).toContainEqual(["Meta+L", "t.cached"]);
useKeymap.setState({ overrides: initial.overrides, extensions: initial.extensions });
});
it("formats macOS style", () => {
expect(formatBinding("Meta+Shift+O")).toBe("⇧⌘O");
expect(formatBinding("Alt+Enter")).toBe("⌥↵");
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more