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

...
Автор SHA1 Повідомлення Дата
l0ng-ai f4daa664f6 fix(agents): clarify settings page names 2026-11-23 16:26:05 +08:00
l0ng-ai eabe4e1a22 fix(agents): align and shorten the Import Sessions dialog 2026-11-23 16:04:20 +08:00
l0ng-ai e662c915a2 fix(agents): show the changes scope as compact tool window tabs (#5393)
The Whole Task / Last Turn switch in the agent Changes pane was a full-width
segmented pill. It now uses the compact Tabs strip that tool window sub-views
use elsewhere.
2026-11-23 15:45:07 +08:00
l0ng-ai f57a17ec14 fix(vcs): group stashes by repository (#5380) 2026-11-23 15:45:02 +08:00
l0ng-ai 0b8d9135aa fix(github): keep the review composer readable (#5375) 2026-11-23 15:44:50 +08:00
l0ng-ai 290ef6956e fix(diff): align original and modified line numbers (#5370)
Unified Diff shows original line numbers in the first column and modified line numbers in the second. Matching rows show both. Removed and inserted rows show the number for their own revision.

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 13:47:56 +08:00
128 змінених файлів з 5702 додано та 758 видалено

No files matched your search

+7 -2
Переглянути файл
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
@@ -139,7 +139,7 @@ pub(crate) fn search_project(
&remaining,
Some(&filter),
Some(&literals),
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback },
cancel,
&|mut file| {
if let Some(prefix) = &prefix {
@@ -188,6 +188,11 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
#[test]
fn search_leaves_unread_the_texts_the_parser_does_not_take() {
assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES);
}
#[test]
fn masks_follow_the_root_they_search() {
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
+8 -1
Переглянути файл
@@ -646,7 +646,10 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Generated Maven sources are attached first, so that recheck sees them.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -663,6 +666,10 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
+26
Переглянути файл
@@ -3165,6 +3165,32 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
eventually(|| refreshed() == expected).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_semantic_tokens() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
let refreshes = || {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(refreshes(), 0);
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
let mut caps = incremental_caps();
+59 -4
Переглянути файл
@@ -1365,8 +1365,15 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
_ => {}
}
}
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server.
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
let vue_pkg = vue::server_package(&vue_command, &search_path());
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server, whose plugin
// host goes away with it. The Vue language server's `@vue/typescript-plugin` loads into
// that host, so a Vue project that has the server keeps the vtsls route and its `.vue`
// support; elsewhere the native server still wins.
if matches!(name, "vtsls" | "typescript-language-server")
&& !(name == "vtsls" && vue_pkg.is_some() && (vue::vue_project(server_root) || vue::vue_project(root)))
&& let Some(native) = native_tsdk(server_root, s).or_else(|| native_tsdk(root, s))
{
cfg.command = native.to_string_lossy().into_owned();
@@ -1380,10 +1387,8 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
cfg.tsserver_project = false;
return;
}
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
if name == "vtsls"
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
&& let Some(vue) = vue_pkg
{
let plugin = vue::tsserver_plugin(&vue);
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
@@ -2453,6 +2458,56 @@ mod maven_linkage_tests {
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
}
#[test]
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
// The Vue server, as the hybrid block finds it through the tool's package dir.
let bin = root.join("tools/node_modules/.bin/vue-language-server");
let pkg = root.join("tools/node_modules/@vue/language-server/package.json");
std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
std::fs::create_dir_all(pkg.parent().unwrap()).unwrap();
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
std::fs::write(&pkg, "{}").unwrap();
let mut s = Settings::default();
s.tools
.insert(vue::SERVER.into(), ide_core::settings::ToolSettings { path: bin.to_string_lossy().into_owned() });
// A Vue project whose TypeScript is 7: the native executable would take over.
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^3.0.0"}}"#).unwrap();
let modules = root.join("node_modules");
let os = match std::env::consts::OS {
"macos" => "darwin",
"windows" => "win32",
os => os,
};
let arch = match std::env::consts::ARCH {
"aarch64" => "arm64",
"x86_64" => "x64",
arch => arch,
};
std::fs::create_dir_all(modules.join("typescript/lib")).unwrap();
std::fs::write(modules.join("typescript/package.json"), r#"{"name":"typescript","version":"7.0.2"}"#).unwrap();
let native = modules.join(format!("@typescript/typescript-{os}-{arch}/lib")).join(crate::exe("tsc"));
std::fs::create_dir_all(native.parent().unwrap()).unwrap();
std::fs::write(&native, "").unwrap();
s.languages.typescript.version = "workspace".into();
// vtsls hosts the Vue plugin's tsserver; the native server cannot, so it loses.
let mut cfg = crate::tests::server("vtsls");
configure_server(&mut cfg, root, root, &s);
assert_eq!(cfg.command, "vtsls");
assert_eq!(
serde_json::to_value(cfg.initialization_options).unwrap().pointer("/vtsls/tsserver/globalPlugins/0/name"),
Some(&json!("@vue/typescript-plugin"))
);
assert_eq!(cfg.tsserver_project_extras.extensions, [vue::EXTENSION.to_string()]);
// typescript-language-server gets no plugin route: the native server still applies.
let mut cfg = crate::tests::server("typescript-language-server");
configure_server(&mut cfg, root, root, &s);
assert_eq!(Path::new(&cfg.command), native);
}
#[test]
fn hybrid_without_a_config_keeps_type_acquisition_and_plain_vtsls_stays_default() {
let tmp = tempfile::tempdir().unwrap();
+10
Переглянути файл
@@ -42,6 +42,16 @@ pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
package_dir(&find_command(command, path)?, PACKAGE)
}
/// Whether `root`'s manifest depends on Vue or `@vue/cli-service`, i.e. it is a Vue project.
/// The tsserver plugin host that `vtsls` carries cannot be loaded into the native TS7
/// server, so this decides whether the tsserver route stays for a Vue project.
pub(crate) fn vue_project(root: &Path) -> bool {
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else {
return false;
};
package_dependencies(&manifest).iter().any(|d| d == "vue" || d == CLI_SERVICE)
}
/// vtsls `globalPlugins` entry loading the Vue plugin shipped with `package`.
pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
serde_json::json!({
+68 -21
Переглянути файл
@@ -24,6 +24,11 @@ const CANCEL_CHECK_LINES: u32 = 256;
/// How many matches a file keeps before claiming them from the shared budget: each file
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
const CLAIM_BATCH: u32 = 64;
/// Bytes at the start of a text that the searcher checks for binary content up front.
const BINARY_HEAD_LEN: usize = 64 * 1024;
/// Files longer than this hold no text the parser takes, whatever their encoding (UTF-16 halves
/// the bytes of ASCII text, nothing else comes close): their comments and strings are not looked for.
const MAX_LITERALS_FILE_BYTES: u64 = 2 * crate::MAX_LITERALS_TEXT_BYTES as u64;
pub(crate) struct Request<'a> {
pub root: &'a Path,
@@ -63,9 +68,11 @@ impl Control<'_> {
/// Also polls the cancellation token (which takes a lock).
fn should_stop(&self) -> bool {
if self.stopped() {
return true;
}
self.stopped() || self.cancel_requested()
}
/// Polls the cancellation token only: a search stopped by its match limit is not cancelled.
fn cancel_requested(&self) -> bool {
if self.cancel.is_cancelled() {
self.cancelled.store(true, Relaxed);
self.stop.store(true, Relaxed);
@@ -302,22 +309,37 @@ impl Ctx<'_> {
{
return;
}
// The search context needs the whole text to find comments and string literals.
// The search context needs the whole text to find comments and string literals. A file
// whose text is past the longest the parser takes has none, so it is not read for them.
let in_context = match self.literals {
Some(literals) => {
Some(literals) => 'context: {
let text = match (self.text.overlay)(path) {
Some(text) => text,
None => match std::fs::read(path) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => text,
// Binary content has nothing to classify.
Err(e) => match (self.text.decode)(path, e.as_bytes()) {
Some(text) => text,
None => return,
None => {
match std::fs::metadata(path) {
Ok(meta) if meta.len() > MAX_LITERALS_FILE_BYTES => {
if self.context.needs_literals() {
return;
}
break 'context None;
}
Ok(_) => {}
Err(_) => return,
}
match std::fs::read(path) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => text,
// Binary content has nothing to classify.
Err(e) => {
match ide_vfs::decode_text(e.as_bytes(), (self.text.fallback)(path).as_deref()) {
Some(text) => text,
None => return,
}
}
},
},
Err(_) => return,
},
Err(_) => return,
}
}
};
let ranges = literals(path, &text);
if ranges.is_none() && self.context.needs_literals() {
@@ -354,7 +376,8 @@ impl Ctx<'_> {
}
/// Streams the file's bytes; a file that turns out not to be UTF-8 (GBK,
/// UTF-16 …) is searched again in the text `decode` gives it.
/// UTF-16 …) is searched again in its text decoded as the editor opens it,
/// which is decoded as it is read.
fn search_disk<'s>(
&'s self,
path: &Path,
@@ -362,7 +385,7 @@ impl Ctx<'_> {
searcher: &mut Searcher,
sink: &mut FileSink<'s>,
) -> io::Result<()> {
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl });
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: true });
let result = searcher.search_reader(matcher, &mut reader, &mut *sink);
// NUL bytes in the head of UTF-16 text stop the byte search; later ones mark binary.
let decode = if sink.binary {
@@ -374,14 +397,29 @@ impl Ctx<'_> {
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
return result;
}
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
// Only cancellation ends the reading: a search that hit the match limit still fills its claim.
let open = || Ok(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: false });
let Some(text) = ide_vfs::decode_stream(open, (self.text.fallback)(path).as_deref())? else {
sink.binary = true;
return Ok(());
};
let mut text = text;
// Text held whole gets the searcher's binary check only on its first 64 KiB and on the
// lines that match; this keeps that for the text read piece by piece.
let mut head = Vec::with_capacity(BINARY_HEAD_LEN);
(&mut text).take(BINARY_HEAD_LEN as u64).read_to_end(&mut head)?;
if head.contains(&0) {
sink.binary = true;
return Ok(());
}
let claimed = sink.claimed;
*sink = FileSink::new(matcher, &self.ctl, None);
sink.claimed = claimed;
searcher.search_slice(matcher, text.as_bytes(), sink)
sink.binary_in_matches = true;
searcher.set_binary_detection(BinaryDetection::none());
let result = searcher.search_reader(matcher, io::Cursor::new(head).chain(text), sink);
searcher.set_binary_detection(BinaryDetection::quit(0));
result
}
}
@@ -404,6 +442,8 @@ struct FileSink<'a> {
/// file is searched again under the claim of its byte search.
claimed: u32,
binary: bool,
/// A NUL byte in a matching line marks the file binary (the searcher's own check is off).
binary_in_matches: bool,
ticks: u32,
/// Scratch buffers reused across lines.
found: Vec<(usize, usize)>,
@@ -425,6 +465,7 @@ impl<'a> FileSink<'a> {
count: 0,
claimed: 0,
binary: false,
binary_in_matches: false,
ticks: 0,
found: Vec::new(),
ranges: Vec::new(),
@@ -467,6 +508,10 @@ impl Sink for FileSink<'_> {
type Error = io::Error;
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
if self.binary_in_matches && memchr::memchr(0, m.bytes()).is_some() {
self.binary = true;
return Ok(false);
}
self.ticks += 1;
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
// Unless cancelled, a decoded file still fills the claim its byte search took.
@@ -534,15 +579,17 @@ impl Sink for FileSink<'_> {
}
}
/// Aborts disk reads once the search is stopped or cancelled.
/// Aborts disk reads once the search is cancelled, or with `hard` once it is stopped.
struct StopReader<'a, R> {
inner: R,
ctl: &'a Control<'a>,
hard: bool,
}
impl<R: Read> Read for StopReader<'_, R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.ctl.should_stop() {
let stop = if self.hard { self.ctl.should_stop() } else { self.ctl.cancel_requested() };
if stop {
return Err(io::Error::other("search stopped"));
}
self.inner.read(buf)
+14 -6
Переглянути файл
@@ -112,8 +112,14 @@ impl SearchContext {
}
}
/// The longest file text, in bytes, that is searched for comments and string literals: the
/// parser's limit (`ide_language::MAX_PARSE_BYTES`), above which a [`Literals`] finds none.
/// The search leaves a longer text unread by it.
pub const MAX_LITERALS_TEXT_BYTES: usize = 16 * 1024 * 1024;
/// Comments and string literals of a file's text (sorted, non-overlapping),
/// or `None` when its language has no syntax tree.
/// or `None` when its language has no syntax tree or the text is longer than
/// [`MAX_LITERALS_TEXT_BYTES`].
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -198,21 +204,23 @@ pub struct SearchSummary {
/// Text of unsaved open documents takes precedence over disk content.
pub type Overlay<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
/// Text of a file whose bytes are not UTF-8 (GBK, UTF-16 …); `None` for binary content.
pub type Decode<'a> = &'a (dyn Fn(&Path, &[u8]) -> Option<String> + Sync);
/// The encoding to read a file with when it is not UTF-8 and the encoding detected for it is not
/// trusted to be right (GBK, UTF-16 …): its label, or `None` to go by what is detected.
pub type FallbackEncoding<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
/// Where a search reads file text from: the open document when `overlay` has
/// it, else the file on disk, decoded by `decode` when it is not UTF-8.
/// it, else the file on disk, decoded as the editor opens it when it is not UTF-8
/// (`fallback` picks the encoding that [`ide_vfs::decode_text`] takes).
#[derive(Clone, Copy)]
pub struct TextSource<'a> {
pub overlay: Overlay<'a>,
pub decode: Decode<'a>,
pub fallback: FallbackEncoding<'a>,
}
impl<'a> TextSource<'a> {
/// Non-UTF-8 files decode as detected, without a configured fallback encoding.
pub fn detected(overlay: Overlay<'a>) -> Self {
Self { overlay, decode: &|_, bytes| ide_vfs::decode_text(bytes, None) }
Self { overlay, fallback: &|_| None }
}
}
+159
Переглянути файл
@@ -0,0 +1,159 @@
//! Searching a big file holds a bounded amount of it in memory, whatever its encoding and the
//! search context. Allocations of the whole process are counted, so this is one test with
//! sequential scenarios.
use ide_core::CancellationToken;
use ide_search::{
FileMatches, Literals, SearchContext, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context,
};
use std::alloc::{GlobalAlloc, Layout, System};
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
struct Counting;
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
fn grow(by: usize) {
let live = LIVE.fetch_add(by, Relaxed) + by;
PEAK.fetch_max(live, Relaxed);
}
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size(), Relaxed);
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
if new_size >= layout.size() {
grow(new_size - layout.size());
} else {
LIVE.fetch_sub(layout.size() - new_size, Relaxed);
}
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOC: Counting = Counting;
const MIB: usize = 1024 * 1024;
/// What a search may hold at once: a few buffers of the reader and the decoder. The files are
/// 16 to 40 MiB, so a search that reads one whole (or decodes it whole) is far over.
const BOUND: usize = 4 * MIB;
fn query(context: SearchContext) -> SearchQuery {
SearchQuery {
pattern: "needle".into(),
is_regex: false,
case_sensitive: true,
whole_word: false,
include: vec![],
exclude: vec![],
scope: SearchScope::Project,
max_matches: 1_000_000,
context,
include_excluded: false,
}
}
/// Runs a search and returns its result with the most memory it held over what was live before.
fn measured(
root: &Path,
context: SearchContext,
literals: Option<Literals<'_>>,
) -> (Vec<FileMatches>, SearchSummary, usize) {
let out = Mutex::new(Vec::new());
let before = LIVE.load(Relaxed);
PEAK.store(before, Relaxed);
let summary = search_in_context(
root,
&query(context),
None,
literals,
TextSource::detected(&|_| None),
&CancellationToken::new(),
&|f| out.lock().unwrap().push(f),
)
.unwrap();
let held = PEAK.load(Relaxed).saturating_sub(before);
// The results are in `out` and count against the search; they are small.
(out.into_inner().unwrap(), summary, held)
}
fn write_repeated(path: &Path, bom: &[u8], block: &[u8], size: usize) {
use std::io::Write;
let mut file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
file.write_all(bom).unwrap();
for _ in 0..size / block.len() + 1 {
file.write_all(block).unwrap();
}
}
fn utf16le(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
#[test]
fn searching_a_big_file_holds_a_bounded_part_of_it() {
let block = "2026-11-22 13:00:01 INFO caf\u{e9} \u{4e2d}\u{6587} request ok\n".repeat(50)
+ "2026-11-22 13:00:02 ERROR needle marker found\n";
let latin_text = block.replace(['\u{4e2d}', '\u{6587}'], "x");
let (latin1, _, _) = encoding_rs::WINDOWS_1252.encode(&latin_text);
let (gbk, _, _) = encoding_rs::GBK.encode(&block);
let parsed = Mutex::new(Vec::new());
let literals = |path: &Path, _: &str| {
parsed.lock().unwrap().push(path.file_name().unwrap().to_string_lossy().into_owned());
None
};
let dir = tempfile::tempdir().unwrap();
let mut expected = Vec::new();
for (name, bom, bytes, size) in [
("latin1.log", &b""[..], &latin1[..], 16 * MIB),
("gbk.log", &b""[..], &gbk[..], 16 * MIB),
("utf16.log", &[0xFF, 0xFE][..], &utf16le(&block)[..], 24 * MIB),
("utf8.log", &b""[..], block.as_bytes(), 40 * MIB),
] {
let one = tempfile::tempdir_in(dir.path()).unwrap();
write_repeated(&one.path().join(name), bom, bytes, size);
// Plain search: the byte search, then the decoded search of a non-UTF-8 file.
let (files, summary, held) = measured(one.path(), SearchContext::Any, None);
assert_eq!(files.len(), 1, "{name}");
assert!(summary.matches > 100, "{name}");
assert!(held < BOUND, "{name}: plain search held {} MiB", held / MIB);
expected.push((name, summary.matches, one));
}
// Searching with a context reads a file whole only to find its comments and strings, and
// past the parser's limit it has none: the file is searched as it is read.
for (name, matches, one) in &expected {
for context in [SearchContext::ExceptComments, SearchContext::ExceptCommentsAndStringLiterals] {
let (files, summary, held) = measured(one.path(), context, Some(&literals));
if *name == "utf8.log" {
assert_eq!(summary.matches, *matches, "{name} {context:?}");
assert_eq!(files.len(), 1);
assert!(held < BOUND, "{name}: {context:?} held {} MiB", held / MIB);
}
}
}
let (_, only_in, held) = measured(expected[3].2.path(), SearchContext::InComments, Some(&literals));
assert_eq!(only_in.matches, 0, "a file without comments has no match in them");
assert!(held < BOUND, "held {} MiB", held / MIB);
let parsed = parsed.into_inner().unwrap();
assert!(parsed.iter().any(|name| name == "gbk.log"), "files within the limit are still analysed");
assert!(!parsed.iter().any(|name| name == "utf8.log"), "a 40 MiB text is never handed to the parser");
}
+1 -2
Переглянути файл
@@ -890,8 +890,7 @@ fn non_utf8_files_use_the_given_decoder() {
// Text too short to detect reliably decodes with the configured encoding.
let p = project(&[("a.txt", &gbk("中文\n"))]);
let out = Mutex::new(Vec::new());
let decode = |_: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, Some("gbk"));
let source = TextSource { overlay: &|_| None, decode: &decode };
let source = TextSource { overlay: &|_| None, fallback: &|_| Some("gbk".into()) };
ide_search::search_in_context(p.path(), &query("中文"), None, None, source, &CancellationToken::new(), &|f| {
out.lock().unwrap().push(f)
})
+200
Переглянути файл
@@ -0,0 +1,200 @@
//! Files that are not UTF-8 are decoded while they are searched. Searching the text decoded whole
//! (what an unsaved editor buffer of the file is) is the reference: the matches must be the same.
use ide_core::CancellationToken;
use ide_search::{FileMatches, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context};
use std::path::Path;
use std::sync::Mutex;
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
SearchQuery {
pattern: pattern.into(),
is_regex,
case_sensitive: false,
whole_word: false,
include: vec![],
exclude: vec![],
scope: SearchScope::Project,
max_matches: 1_000_000,
context: Default::default(),
include_excluded: false,
}
}
fn run(root: &Path, q: &SearchQuery, source: TextSource<'_>) -> (Vec<FileMatches>, SearchSummary) {
let out = Mutex::new(Vec::new());
let summary =
search_in_context(root, q, None, None, source, &CancellationToken::new(), &|f| out.lock().unwrap().push(f))
.unwrap();
let mut files = out.into_inner().unwrap();
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
(files, summary)
}
/// The matches of every file in `root`, read from disk and from its whole decoded text.
fn both_ways(root: &Path, q: &SearchQuery, fallback: Option<&str>) -> (String, String) {
let streamed = run(root, q, TextSource { overlay: &|_| None, fallback: &|_| fallback.map(str::to_owned) });
let whole = run(
root,
q,
TextSource {
overlay: &|path| ide_vfs::decode_text(&std::fs::read(path).unwrap(), fallback),
fallback: &|_| None,
},
);
let show = |(files, summary): (Vec<FileMatches>, SearchSummary)| {
format!("{:#?}\nmatches {} limit {}", files, summary.matches, summary.limit_hit)
};
(show(streamed), show(whole))
}
fn first_difference(a: &str, b: &str) -> String {
let (a, b): (Vec<_>, Vec<_>) = (a.lines().collect(), b.lines().collect());
let at = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
format!(
"line {at}:\nstreamed {:?}\nwhole {:?}",
&a[at.saturating_sub(3)..a.len().min(at + 3)],
&b[at.saturating_sub(3)..b.len().min(at + 3)]
)
}
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
let mut bytes = if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
for unit in text.encode_utf16() {
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
}
bytes
}
/// Lines of mixed width: ASCII, accents, CJK, astral characters (surrogate pairs), CRLF.
fn lines(count: usize) -> String {
let mut text = String::new();
for i in 0..count {
match i % 6 {
0 => text.push_str(&format!("{i} needle in plain ascii\n")),
1 => text.push_str(&format!("{i} caf\u{e9} needle cr\u{e8}me\n")),
2 => text.push_str(&format!("{i} \u{4e2d}\u{6587} needle \u{6d4b}\u{8bd5}\n")),
3 => text.push_str(&format!("{i} \u{1f600} needle \u{1f4a9}\n")),
4 => text.push_str(&format!("{i} crlf needle\r\n")),
_ => text.push_str(&format!("{i} nothing here\n")),
}
}
text
}
fn write(dir: &Path, name: &str, bytes: &[u8]) {
std::fs::write(dir.join(name), bytes).unwrap();
}
#[test]
fn decoded_files_give_the_matches_of_their_whole_text() {
let wide = lines(12_000);
let gbk_text = wide.replace(['\u{1f600}', '\u{1f4a9}', '\u{e9}', '\u{e8}'], "");
let latin_text = wide.replace(|c: char| c as u32 > 0xff, "");
let dir = tempfile::tempdir().unwrap();
// (BOM-less UTF-16 is not searched in decoded text, and not covered here: only the byte search sees it.)
// Each file is well past the sizes the decoder reads at a time (64 KiB).
assert!(wide.len() > 250_000);
write(dir.path(), "utf16le_bom.txt", &utf16(&wide, true, false));
write(dir.path(), "utf16be_bom.txt", &utf16(&wide, true, true));
write(dir.path(), "gbk.txt", &encoding_rs::GBK.encode(&gbk_text).0);
write(dir.path(), "latin1.txt", &encoding_rs::WINDOWS_1252.encode(&latin_text).0);
write(dir.path(), "utf8.txt", wide.as_bytes());
let queries = [
query("needle", false),
query("caf\u{e9}", false),
query("\u{1f600}", false),
query("\u{4e2d}\u{6587} needle", false),
query(r"\d+ \S+ needle", true),
query(r"needle\r?$", true),
// A multi-line pattern reads the whole text, however it arrives.
query("needle in plain ascii\n1 caf", false),
SearchQuery { case_sensitive: true, whole_word: true, ..query("needle", false) },
];
for q in &queries {
for fallback in [None, Some("gbk"), Some("windows-1252")] {
let (streamed, whole) = both_ways(dir.path(), q, fallback);
assert!(
streamed == whole,
"{:?} fallback {fallback:?}\n{}",
q.pattern,
first_difference(&streamed, &whole)
);
assert!(streamed.len() > 100, "{:?} found nothing", q.pattern);
}
}
// The match limit keeps the first matches of a file, and files take their share in any order:
// one file at a time.
for name in ["utf16le_bom.txt", "utf16be_bom.txt", "gbk.txt", "latin1.txt"] {
for max_matches in [7, 64, 65, 5_000] {
let q = SearchQuery { max_matches, include: vec![name.into()], ..query("needle", false) };
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{name} limit {max_matches}\n{}", first_difference(&streamed, &whole));
assert!(streamed.contains(&format!("matches {max_matches} limit true")), "{name} {max_matches}");
}
}
}
#[test]
fn decoded_files_keep_their_multibyte_characters_across_every_read_boundary() {
// A character sits on each of the 64 KiB read boundaries, at all alignments.
let dir = tempfile::tempdir().unwrap();
for pad in 0..8usize {
let mut gbk = "x".repeat(64 * 1024 - 5 + pad);
let mut utf16_text = gbk.clone();
for i in 0..40 {
gbk.push_str("\u{4e2d}\u{6587}");
utf16_text.push_str(if i % 2 == 0 { "\u{1f600}" } else { "\u{4e2d}" });
gbk.push_str(&"y".repeat(i % 3));
utf16_text.push_str(&"y".repeat(i % 3));
}
gbk.push_str("yy needle\n");
utf16_text.push_str("yy needle\n");
write(dir.path(), &format!("gbk{pad}.txt"), &encoding_rs::GBK.encode(&gbk).0);
write(dir.path(), &format!("utf16_{pad}.txt"), &utf16(&utf16_text, true, pad % 2 == 0));
write(
dir.path(),
&format!("latin{pad}.txt"),
&[gbk.as_bytes()[..64 * 1024 - 7 + pad].to_vec(), b"\xe9\xe8 needle\n".to_vec()].concat(),
);
}
for pattern in ["needle", "y+ needle", "\u{4e2d}\u{6587}"] {
let q = query(pattern, pattern.contains('+'));
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{pattern}\n{}", first_difference(&streamed, &whole));
assert!(streamed.len() > 100, "{pattern} found nothing");
}
}
#[test]
fn nul_characters_in_decoded_text_mark_it_binary_as_in_the_whole_text() {
// Text held whole is binary when a NUL is in its first 64 KiB or in a line that matches,
// which is not the same as a NUL anywhere.
let text = lines(20_000);
let with_nul = |at: &str| text.replacen(at, &format!("\0{at}"), 1);
let cases = [
("early", with_nul("5 nothing here"), false),
("late in a line that does not match", with_nul("19997 nothing here"), true),
("late in a line that matches", with_nul("19998 needle"), false),
];
for (name, text, found) in cases {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", &utf16(&text, true, false));
let (streamed, whole) = both_ways(dir.path(), &query("needle", false), None);
assert!(streamed == whole, "{name}\n{}", first_difference(&streamed, &whole));
assert_eq!(streamed.contains("a.txt"), found, "{name}");
}
}
#[test]
fn a_file_is_decoded_when_its_search_reaches_the_byte_that_is_not_utf8() {
// Valid UTF-8 up to the last line: the whole file is read as the detected Windows-1252.
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "late.txt", &[lines(1500).as_bytes(), b"caf\xe9 needle\n"].concat());
for q in [query("needle", false), query("caf", false)] {
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{}", first_difference(&streamed, &whole));
assert!(streamed.contains("café"), "decoded as Windows-1252");
}
}
+22
Переглянути файл
@@ -81,6 +81,12 @@ fn npm_package(tool: &str) -> &str {
}
impl Tools {
/// The IDE's own installation of `tool` outside `node_modules` (Ruff's private virtualenv).
fn managed_executable(&self, tool: &str) -> Option<PathBuf> {
let spec = crate::registry::find(tool)?;
self.exe_in(&crate::managed_bin_dir(&self.root, spec, self.platform)?, spec.commands[0])
}
/// Explicit executable/script, then the nearest project package, then managed tools and PATH.
pub fn formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
self.resolve_formatter_command(tool, file, custom).map_err(|e| e.with_tool(tool))
@@ -100,6 +106,8 @@ impl Tools {
(package_bin(manifest.parent().unwrap(), tool)?, true)
} else if self.root.join(&manifest).is_file() {
(package_bin(&self.root.join(&package), tool)?, true)
} else if let Some(path) = self.managed_executable(tool) {
(path, false)
} else {
(self.which(tool).ok_or_else(|| IdeError::missing_tool(tool))?, false)
};
@@ -241,6 +249,20 @@ mod tests {
assert_eq!(failure.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: false }));
}
#[cfg(unix)]
#[test]
fn a_formatter_the_ide_installed_in_its_virtualenv_is_found() {
let dir = tempfile::tempdir().unwrap();
let tools = Tools::with_paths(dir.path().join("tools"), OsString::new(), crate::platform::Platform::current());
let file = dir.path().join("main.py");
assert!(tools.formatter_command("ruff", &file, None).is_err());
let bin = dir.path().join("tools/ruff/venv/bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(bin.join("ruff"), "").unwrap();
let command = tools.formatter_command("ruff", &file, None).unwrap();
assert_eq!(Path::new(command.get_program()), bin.join("ruff"));
}
#[cfg(unix)]
#[test]
fn stderr_is_preserved_verbatim_even_when_longer_than_four_thousand_characters() {
+366
Переглянути файл
@@ -0,0 +1,366 @@
//! [`decode_text`](crate::decode_text) for files too large to hold: the same
//! decisions, taken while reading a chunk at a time.
use crate::encoding::{SNIFF_LEN, sniff_utf16};
use encoding_rs::{Decoder, Encoding, UTF_8, UTF_16BE, UTF_16LE};
use std::io::{self, Read};
/// Raw bytes read per step; a step holds this plus its UTF-8 expansion (at most 3x).
const CHUNK: usize = 64 * 1024;
/// The text of a file as UTF-8 bytes, decoded as it is read.
pub struct DecodedReader<R> {
reader: R,
decoder: Decoder,
raw: Vec<u8>,
/// Decoded bytes of the last step; `out[pos..len]` is unread.
out: Vec<u8>,
pos: usize,
len: usize,
done: bool,
}
/// Decodes the file `open` reads like [`decode_text`](crate::decode_text) does (BOM, UTF-8 and
/// UTF-16 as detected, other text as `fallback` or else the detected encoding) without holding
/// it: `None` for binary content, else a reader of the text as UTF-8.
///
/// Deciding the encoding of text that is neither BOM-marked nor UTF-8 needs a pass over the whole
/// file before the decoding pass, so `open` gives a fresh reader of the file up to twice.
pub fn decode_stream<R: Read>(
open: impl FnMut() -> io::Result<R>,
fallback: Option<&str>,
) -> io::Result<Option<DecodedReader<R>>> {
decode_stream_in(open, fallback, CHUNK)
}
fn decode_stream_in<R: Read>(
mut open: impl FnMut() -> io::Result<R>,
fallback: Option<&str>,
chunk: usize,
) -> io::Result<Option<DecodedReader<R>>> {
let Some((detected, bom_len, has_bom)) = detect(&mut open, chunk)? else { return Ok(None) };
let fallback = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes()));
let encoding = match fallback {
Some(enc)
if !has_bom && enc != detected && detected != UTF_8 && detected != UTF_16LE && detected != UTF_16BE =>
{
enc
}
_ => detected,
};
let mut reader = open()?;
io::copy(&mut (&mut reader).take(bom_len as u64), &mut io::sink())?;
let decoder = encoding.new_decoder_without_bom_handling();
let out = vec![0; decoder.max_utf8_buffer_length(chunk).unwrap_or(chunk * 3)];
Ok(Some(DecodedReader { reader, decoder, raw: vec![0; chunk], out, pos: 0, len: 0, done: false }))
}
/// The encoding [`decode`](crate::encoding::decode) finds for the file, its BOM length and
/// whether it has a BOM; `None` for binary content.
fn detect<R: Read>(
open: &mut impl FnMut() -> io::Result<R>,
chunk: usize,
) -> io::Result<Option<(&'static Encoding, usize, bool)>> {
let mut reader = open()?;
let mut head = vec![0; SNIFF_LEN];
let n = read_full(&mut reader, &mut head)?;
head.truncate(n);
if let Some((enc, bom_len)) = Encoding::for_bom(&head) {
return Ok(Some((enc, bom_len, true)));
}
if head.contains(&0) {
return Ok(sniff_utf16(&head).map(|enc| (enc, 0, false)));
}
let mut detector = chardetng::EncodingDetector::new();
let mut utf8 = Utf8Check::default();
detector.feed(&head, false);
utf8.feed(&head);
if n == SNIFF_LEN {
let mut buf = vec![0; chunk];
loop {
let n = read_retry(&mut reader, &mut buf)?;
if n == 0 {
break;
}
detector.feed(&buf[..n], false);
utf8.feed(&buf[..n]);
}
}
detector.feed(&[], true);
let encoding = if utf8.is_valid() { UTF_8 } else { detector.guess(None, true) };
Ok(Some((encoding, 0, false)))
}
/// Reads until `buf` is full or the reader ends.
fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
let mut filled = 0;
while filled < buf.len() {
match read_retry(reader, &mut buf[filled..])? {
0 => break,
n => filled += n,
}
}
Ok(filled)
}
fn read_retry(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
loop {
match reader.read(buf) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
result => return result,
}
}
}
/// Checks that bytes fed in pieces form valid UTF-8, as `std::str::from_utf8` does for the whole.
#[derive(Default)]
struct Utf8Check {
/// The start of a character cut by the end of the previous piece.
tail: Vec<u8>,
invalid: bool,
}
impl Utf8Check {
fn feed(&mut self, mut bytes: &[u8]) {
if self.invalid {
return;
}
while !self.tail.is_empty() && !bytes.is_empty() {
self.tail.push(bytes[0]);
bytes = &bytes[1..];
match std::str::from_utf8(&self.tail) {
Ok(_) => self.tail.clear(),
Err(e) if e.error_len().is_none() => {}
Err(_) => {
self.invalid = true;
return;
}
}
}
if !self.tail.is_empty() {
return;
}
match std::str::from_utf8(bytes) {
Ok(_) => {}
Err(e) if e.error_len().is_none() => self.tail.extend_from_slice(&bytes[e.valid_up_to()..]),
Err(_) => self.invalid = true,
}
}
/// Whether everything fed so far was UTF-8 (a truncated final character is not).
fn is_valid(&self) -> bool {
!self.invalid && self.tail.is_empty()
}
}
impl<R: Read> Read for DecodedReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while self.pos == self.len {
if self.done {
return Ok(0);
}
let n = read_retry(&mut self.reader, &mut self.raw)?;
let last = n == 0;
let needed = self.decoder.max_utf8_buffer_length(n).unwrap_or(n * 3 + 16);
if self.out.len() < needed {
self.out.resize(needed, 0);
}
// Malformed input becomes U+FFFD, as in `decode_without_bom_handling`.
let (_, _, written, _) = self.decoder.decode_to_utf8(&self.raw[..n], &mut self.out, last);
self.pos = 0;
self.len = written;
self.done = last;
}
let n = buf.len().min(self.len - self.pos);
buf[..n].copy_from_slice(&self.out[self.pos..self.pos + n]);
self.pos += n;
Ok(n)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::decode_text;
/// Hands out at most `step` bytes per read, so chunk edges fall everywhere.
struct Trickle<'a> {
bytes: &'a [u8],
step: usize,
}
impl Read for Trickle<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = buf.len().min(self.step).min(self.bytes.len());
buf[..n].copy_from_slice(&self.bytes[..n]);
self.bytes = &self.bytes[n..];
Ok(n)
}
}
fn streamed(bytes: &[u8], fallback: Option<&str>, chunk: usize, step: usize) -> Option<Vec<u8>> {
let reader = decode_stream_in(|| Ok(Trickle { bytes, step }), fallback, chunk).unwrap()?;
let mut out = Vec::new();
let mut reader = reader;
// Small reads too: the consumer's buffer is not the chunk either.
let mut buf = [0; 7];
loop {
let n = reader.read(&mut buf).unwrap();
if n == 0 {
return Some(out);
}
out.extend_from_slice(&buf[..n]);
}
}
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
let mut bytes =
if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
for unit in text.encode_utf16() {
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
}
bytes
}
/// Text with multi-byte characters and surrogate pairs at every alignment.
fn sample(len: usize) -> String {
let mut text = String::new();
let pieces = [
"ascii line\n",
"caf\u{e9} cr\u{e8}me\n",
"\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\n",
"\u{1f600}\u{1f4a9} x\n",
"\u{20ac}5\r\n",
];
let mut i = 0;
while text.len() < len {
text.push_str(pieces[i * 7 % pieces.len()]);
i += 1;
}
text
}
fn inputs() -> Vec<(String, Vec<u8>)> {
let text = sample(1500);
let mut inputs = vec![
("utf8".to_string(), text.clone().into_bytes()),
("utf8 bom".to_string(), [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat()),
("utf16le bom".to_string(), utf16(&text, true, false)),
("utf16be bom".to_string(), utf16(&text, true, true)),
("utf16le".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, false)),
("utf16be".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, true)),
(
"gbk".to_string(),
encoding_rs::GBK
.encode(&sample(1500).replace(['\u{1f600}', '\u{1f4a9}', '\u{20ac}'], ""))
.0
.into_owned(),
),
(
"latin1".to_string(),
encoding_rs::WINDOWS_1252
.encode(&sample(1500).replace(|c: char| c as u32 > 0xff && c != '\u{20ac}', ""))
.0
.into_owned(),
),
("empty".to_string(), Vec::new()),
("binary".to_string(), b"\x7FELF\x02\x01\x01\x00\x00\x00 and text".repeat(100)),
("late nul".to_string(), [&b"abc caf\xe9 ".repeat(1200)[..], b"\0 tail"].concat()),
("truncated utf8".to_string(), text.as_bytes()[..text.len() - 1].to_vec()),
("truncated utf16".to_string(), utf16(&text, true, false)[..utf16(&text, true, false).len() - 1].to_vec()),
(
"lone surrogate".to_string(),
[&[0xFF, 0xFE][..], &[0x3D, 0xD8, b'a', 0][..], &utf16(&text, false, false)[..]].concat(),
),
("invalid in the middle".to_string(), [text.as_bytes(), b"\xff\xfe\xc3", text.as_bytes()].concat()),
(
"shift jis".to_string(),
encoding_rs::SHIFT_JIS
.encode(
"\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{ff76}\u{ff85}\n"
.repeat(200)
.as_str(),
)
.0
.into_owned(),
),
];
// The evidence for the encoding comes long after the sniffed head.
let chinese = "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\u{4e00}\u{6bb5}\u{6587}\u{672c}\n".repeat(300);
let gbk = encoding_rs::GBK.encode(&chinese).0.into_owned();
let head = "plain ascii line\n".repeat(1500);
inputs.push(("gbk after a long ascii head".to_string(), [head.as_bytes(), &gbk].concat()));
// Characters at every alignment against the sniffing head and the chunks.
for pad in 0..5 {
let mut bytes = "x".repeat(SNIFF_LEN - 3 + pad).into_bytes();
bytes.extend("\u{4e2d}\u{1f600}\u{e9}".as_bytes());
inputs.push((format!("utf8 at the head edge {pad}"), bytes));
let mut bytes = "y".repeat(SNIFF_LEN - 2 + pad).into_bytes();
bytes.extend([0xE9, b'z', 0xFF, b'e']);
inputs.push((format!("latin1 at the head edge {pad}"), bytes));
}
inputs
}
#[test]
fn streamed_text_equals_the_whole_file_decode() {
for (name, bytes) in inputs() {
for fallback in [None, Some("gbk"), Some("windows-1252"), Some("utf-16le"), Some("nonsense")] {
let expected = decode_text(&bytes, fallback).map(String::into_bytes);
for chunk in [1, 2, 3, 4, 5, 16, 255, 4096, CHUNK] {
for step in [1, 3, 8192, usize::MAX] {
assert_eq!(
streamed(&bytes, fallback, chunk, step),
expected,
"{name}, fallback {fallback:?}, chunk {chunk}, step {step}"
);
}
}
}
}
}
#[test]
fn utf8_check_matches_from_utf8_for_any_split() {
let samples: [&[u8]; 6] = [
"a\u{e9}\u{4e2d}\u{1f600}z".as_bytes(),
b"ab\xe4\xb8",
b"\xe4\xb8a",
b"\xf0\x9f\x98",
b"ok\xc3(",
b"\xed\xa0\x80",
];
for bytes in samples {
for first in 0..=bytes.len() {
for second in first..=bytes.len() {
let mut check = Utf8Check::default();
check.feed(&bytes[..first]);
check.feed(&bytes[first..second]);
check.feed(&bytes[second..]);
assert_eq!(check.is_valid(), std::str::from_utf8(bytes).is_ok(), "{bytes:?} {first} {second}");
}
}
}
}
#[test]
fn reads_at_most_a_bounded_number_of_bytes_per_step() {
// A reader that fails if asked for more than one chunk shows nothing is read whole.
struct Capped<'a>(&'a [u8]);
impl Read for Capped<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
assert!(buf.len() <= SNIFF_LEN.max(1024), "asked for {} bytes", buf.len());
let n = buf.len().min(self.0.len());
buf[..n].copy_from_slice(&self.0[..n]);
self.0 = &self.0[n..];
Ok(n)
}
}
let bytes = encoding_rs::WINDOWS_1252.encode(&"caf\u{e9}\n".repeat(50_000)).0.into_owned();
let mut reader = decode_stream_in(|| Ok(Capped(&bytes)), None, 1024).unwrap().unwrap();
let mut text = String::new();
reader.read_to_string(&mut text).unwrap();
assert_eq!(text, "caf\u{e9}\n".repeat(50_000));
assert!(reader.out.len() <= 4 * 1024 + 16 && reader.raw.len() == 1024);
}
}
+1 -1
Переглянути файл
@@ -103,7 +103,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult<f64> {
}
/// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text.
fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
pub(crate) fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
if sample.len() < 4 {
return None;
}
+2
Переглянути файл
@@ -3,6 +3,7 @@
mod archive;
mod bytes;
mod compare;
mod decode_stream;
mod encoding;
mod ops;
mod private;
@@ -30,6 +31,7 @@ pub use compare::{
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge,
};
pub use decode_stream::{DecodedReader, decode_stream};
use encoding::SNIFF_LEN;
pub use encoding::{
LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
+3 -3
Переглянути файл
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
## Manage agents
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
### External MCP servers
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
+1
Переглянути файл
@@ -69,6 +69,7 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
Selecting an item shows tabs in the detail pane:
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
- **Volume** and **network**: **Dashboard** and **Inspect**.
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ A file holds only the values that differ from the layer below. Tables merge key
Some settings are ignored in the project file: `mcpServer`, imported color schemes (`editor.customSchemes`) and `agents.newTaskApprovals` are global only. Project trust is never read from settings.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › External MCP Servers**, and again after its definition changes.
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › MCP Connections**, and again after its definition changes.
## File format
+3 -3
Переглянути файл
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
## 管理 agent
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
**设置 › 智能体 › MCP 连接** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
+1
Переглянути файл
@@ -69,6 +69,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
选中某项后,详情区会显示以下标签页:
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ description: "OpenIDEA 的设置保存在哪里、全局文件与项目文件如
有些设置在项目文件中会被忽略:`mcpServer`、导入的配色方案(`editor.customSchemes`)和 `agents.newTaskApprovals` 只能全局配置。项目信任状态永远不会从设置文件中读取。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › 外部 MCP 服务器** 中将其开启;服务器定义改变后也需要重新开启。
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › MCP 连接** 中将其开启;服务器定义改变后也需要重新开启。
## 文件格式
+8 -4
Переглянути файл
@@ -308,11 +308,15 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
await sessionPopup.getByRole("button", { name: "Reset" }).click();
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
// 2. Jump directly from the session MCP popover's gear button to Settings › Agents › MCP Connections.
await sessionPopup.getByRole("button", { name: "MCP Connections…", exact: true }).click();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
await expect(settingsDialog.getByRole("heading", { name: "MCP Connections", exact: true })).toBeVisible();
await expect(settingsDialog.getByRole("treeitem", { name: "MCP Connections", exact: true })).toHaveAttribute(
"aria-selected",
"true",
);
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
@@ -321,7 +325,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "External MCP Servers" })
.getByRole("heading", { name: "MCP Connections", exact: true })
.evaluate((el) => el.scrollIntoView({ block: "start" }));
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
+68 -7
Переглянути файл
@@ -1,11 +1,12 @@
import { expect, stubDesktop, test } from "./fixtures";
import type { Page } from "@playwright/test";
import { expect, PROJECT, stubDesktop, test } from "./fixtures";
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
workbench: page,
}) => {
async function importCoverage(page: Page, width: number) {
await page.setViewportSize({ width: 1050, height: 550 });
await expect(page.getByRole("tree", { name: "Project" }).getByRole("treeitem", { name: PROJECT })).toBeVisible();
await expect(page.locator("#splash")).toHaveCount(0);
await stubDesktop(page);
await page.evaluate(async () => {
await page.evaluate(async (width) => {
const projectModule = "/src/platform/project.ts";
const actionsModule = "/src/platform/actions.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
@@ -26,10 +27,15 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
hasBranches: path === "/tmp/coverage.lcov",
files,
});
setToolWindowSize("right", 280);
setToolWindowSize("right", width);
await executeAction("coverage.importReport", "/tmp/coverage.lcov");
});
}, width);
}
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
workbench: page,
}) => {
await importCoverage(page, 280);
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
const tree = coverage.getByRole("tree", { name: "Coverage" });
const line = coverage.getByRole("columnheader", { name: "Line, %" });
@@ -70,3 +76,58 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
await expect(line).toBeVisible();
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
});
test("Coverage column widths follow the dividers and survive a narrower dock and reload", async ({
workbench: page,
}) => {
await importCoverage(page, 460);
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
const line = coverage.getByRole("columnheader", { name: "Line, %" });
const branch = coverage.getByRole("columnheader", { name: "Branch, %" });
const lineDivider = coverage.getByRole("separator", { name: "Resize Line, % column" });
const branchDivider = coverage.getByRole("separator", { name: "Resize Branch, % column" });
const ready = coverage.getByRole("treeitem", { name: /^Ready\.ts/ });
const nameHeader = coverage.getByRole("columnheader", { name: "Element" });
await expect(lineDivider).toBeVisible();
const width = async (loc: typeof line) => (await loc.boundingBox())!.width;
const originalLine = await width(line);
const originalBranch = await width(branch);
const originalName = await width(nameHeader);
const drag = (await lineDivider.boundingBox())!;
await page.mouse.move(drag.x + drag.width / 2, drag.y + drag.height / 2);
await page.mouse.down();
await page.mouse.move(drag.x + drag.width / 2 + 32, drag.y + drag.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 32, 0);
await expect.poll(() => width(nameHeader)).toBeCloseTo(originalName + 32, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
await expect(line).toHaveAttribute("aria-sort", "none");
await branchDivider.press("ArrowRight");
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
const resizeDock = (size: number) =>
page.evaluate(async (size) => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
setToolWindowSize("right", size);
}, size);
await resizeDock(240);
await expect.poll(() => width(line)).toBeLessThan(originalLine - 22);
const tree = coverage.getByRole("tree", { name: "Coverage" });
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
await expect(branchDivider).toBeInViewport({ ratio: 1 });
await resizeDock(460);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await page.reload();
await importCoverage(page, 460);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await branchDivider.dblclick();
await expect.poll(() => width(line)).toBeCloseTo(originalLine, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
});
+106
Переглянути файл
@@ -0,0 +1,106 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const className = "com.example.billing.SettlementSnapshot";
const amountField = "crossBorderSettlementAmountInMinorUnitsBeforeExchangeRateAdjustment";
const amount = "125486.75";
const referenceField = "externalSettlementProcessorReconciliationReferenceForMonthlyReport";
const reference = "EU-West / settlement batch 701 / reconciliation complete";
test("Memory Instances leaves room for field values and referrer actions in a narrow dock", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1180, height: 720 });
await stubDesktop(page);
await page.evaluate(
async ({ className, amountField, amount, referenceField, reference }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const h = window.__ipc.handlers;
h.debug_jvm_memory_classes = () => ({
status: "ready",
snapshot: {
rows: [{ name: className, instances: 1, bytes: 48, deltaInstances: null, deltaBytes: null, module: null }],
totalInstances: 1,
totalBytes: 48,
hasBaseline: false,
elapsedMs: 2,
source: "debugger",
javaVersion: "21",
takenWhileSuspended: true,
},
});
h.debug_jvm_memory_instances = () => ({
status: "ready",
generation: 1,
instances: [{ kind: "object", typeName: className, id: 12 }],
truncated: false,
});
h.debug_jvm_memory_fields = ({ object }) => ({
status: "ready",
fields:
(object as { id: number }).id === 12
? [
{ name: amountField, value: { kind: "primitive", typeName: "double", text: amount } },
{ name: referenceField, value: { kind: "string", text: reference, length: reference.length, id: 16 } },
]
: [],
});
h.debug_jvm_memory_referrers = () => ({
status: "ready",
referrers: [{ value: { kind: "object", id: 12, typeName: className }, via: [referenceField] }],
truncated: false,
});
adoptSession(91, {
name: "Billing Service",
adapter: "java-debug",
status: "paused",
stops: 1,
caps: { jvmMemory: true, jvmInstances: true },
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 330);
showToolWindow("debug", true);
},
{ className, amountField, amount, referenceField, reference },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Memory", exact: true }).click();
await debug.getByRole("row").filter({ hasText: className }).dblclick();
const title = `Instances of ${className}`;
const instances = debug.getByRole("region", { name: title, exact: true });
const tree = instances.getByRole("tree", { name: title });
const root = tree.getByRole("treeitem", { name: /SettlementSnapshot@12/ });
await root.locator("[data-tree-toggle]").click();
const fieldName = instances.getByText(amountField, { exact: true });
const fieldValue = instances.getByText(amount, { exact: true });
const fits = (el: Element) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1;
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
await expect.poll(() => fieldName.evaluate(fits)).toBe(false);
await expect(fieldName).toHaveAttribute("title", amountField);
await expect(fieldValue).toHaveAttribute("title", amount);
await expect(instances.getByText(title, { exact: true })).toHaveCSS(
"font-family",
await instances.evaluate((el) => getComputedStyle(el).fontFamily),
);
const referrerRow = tree.getByRole("treeitem").filter({ hasText: referenceField });
const showReferrers = referrerRow.getByRole("button", { name: "Show Referrers" });
await referrerRow.hover();
await expect(showReferrers).toBeInViewport({ ratio: 1 });
await showReferrers.press("Enter");
await expect(tree.getByText("Referrers", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "debug_jvm_memory_referrers")).toHaveLength(1);
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
setToolWindowSize("bottom", 400);
});
await expect.poll(() => fieldName.evaluate(fits)).toBe(true);
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
});
+85
Переглянути файл
@@ -629,6 +629,91 @@ test("single-line selection stays on its own row when font glyphs exceed line he
expect(Math.abs(selBox!.height - lineBox!.height)).toBeLessThanOrEqual(1);
});
test("find and occurrence highlights stay on their own row when font glyphs exceed line height", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({
settings: { ...base, editor: { ...base.editor, fontSize: 18, lineHeight: 18 } },
});
const root = document.documentElement.style;
root.setProperty("--bg-editor", "#ffffff");
root.setProperty("--bg-current-line", "#ffffff");
root.setProperty("--bg-identifier-under-caret", "#cc0000");
root.setProperty("--bg-search-match", "#cc00cc");
root.setProperty("--bg-search-match-current", "#cc8800");
await document.fonts.ready;
});
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(
[" ", "description", " ", "description", " "].join("\n"),
);
const lines = editor.locator(".cm-line");
await expect(lines).toHaveCount(5);
const blankRowsAreUnpainted = async () => {
const [editorBox, b0, b2, b4, matchBox] = await Promise.all([
editor.boundingBox(),
lines.nth(0).boundingBox(),
lines.nth(2).boundingBox(),
lines.nth(4).boundingBox(),
lines.nth(1).boundingBox(),
]);
const png = await editor.screenshot();
const base64 = png.toString("base64");
return page.evaluate(
async ({ base64, editorBox, blanks, probeX }) => {
const img = new Image();
img.src = `data:image/png;base64,${base64}`;
await img.decode();
const scale = img.width / editorBox!.width;
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d")!;
ctx.drawImage(img, 0, 0);
const x = Math.round((probeX - editorBox!.x) * scale);
for (const row of blanks) {
const yStart = Math.ceil((row!.y - editorBox!.y) * scale) + 1;
const yEnd = Math.floor((row!.y + row!.height - editorBox!.y) * scale) - 1;
for (let y = yStart; y <= yEnd; y++) {
const [r, g, b] = ctx.getImageData(x, y, 1, 1).data;
if (r !== 255 || g !== 255 || b !== 255) return { ok: false, x, y, rgb: [r, g, b] };
}
}
return { ok: true };
},
{ base64, editorBox, blanks: [b0, b2, b4], probeX: matchBox!.x + 30 },
);
};
// Selection match on line 4 (`description`) when line 2 is selected.
await lines.nth(1).dblclick();
await expect(editor.locator(".cm-selectionMatch")).toHaveCount(1);
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
// Find matches: line 2 is `.cm-openidea-findMatch-current` (with 1px frame), line 4 is `.cm-openidea-findMatch`.
await page.keyboard.press("Meta+f");
const find = page.getByRole("textbox", { name: "Find" });
await expect(find).toBeFocused();
await find.fill("description");
await expect(editor.locator(".cm-openidea-findMatch-current")).toHaveCount(1);
await expect(editor.locator(".cm-openidea-findMatch")).toHaveCount(2);
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
});
test("vertical tabs leave a narrow editor group most of its width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 900, height: 600 });
await openFromTree(page, "settings.gradle.kts");
+44
Переглянути файл
@@ -0,0 +1,44 @@
import { expect, openFromTree, test } from "./fixtures";
test("multiline editor search keeps three visible lines and replaces with the full text", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
await page.setViewportSize({ width: 540, height: 500 });
const content = editor.locator(".cm-content");
const query = "currency=EUR\nregion=eu-west\npipeline=clearing\nmode=batch\ntimeout=30\nretries=2";
const replacement = query.replace("clearing", "settlement").replace("timeout=30", "timeout=45");
await content.press("Meta+a");
await page.keyboard.insertText(`[ledger]\n${query}\n\n[reporting]\n${query}\n`);
await content.press("Escape");
await content.press("Meta+r");
const bar = page.getByRole("search", { name: "Replace in file" });
const find = bar.getByRole("textbox", { name: "Find", exact: true });
const replace = bar.getByRole("textbox", { name: "Replace", exact: true });
await find.fill(query);
await replace.fill(replacement);
for (const field of [find, replace]) {
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
expect(visibleLines).toBeCloseTo(3);
await field.press("Control+End");
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
}
await expect(find).toHaveValue(query);
await expect(replace).toHaveValue(replacement);
const count = bar.locator("[aria-live]");
await expect(count).toHaveText(/\/2$/);
const selected = await count.innerText();
const next = bar.getByRole("button", { name: /Next Occurrence/ });
await next.click();
await expect(count).toHaveText(/^[12]\/2$/);
await expect(count).not.toHaveText(selected);
await bar.getByRole("button", { name: "Replace All", exact: true }).click();
await expect(editor.locator(".cm-line", { hasText: "timeout=45" })).toHaveCount(2);
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(0);
await bar.getByRole("button", { name: "Close", exact: true }).click();
await expect(content).toBeFocused();
await content.press("Meta+z");
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(2);
});
+83
Переглянути файл
@@ -0,0 +1,83 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("New Worktree keeps form fields aligned and creates the selected worktree in a short window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 740 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/acme-api";
const service = `${root}/service`;
window.__ipc.handlers.vcs_branches = () => [{ name: "main", current: true, remote: false }];
window.__ipc.handlers.vcs_tags = () => [];
window.__ipc.handlers.vcs_worktrees = ({ repo }) => [{ path: repo, branch: "main", main: true, submodule: false }];
window.__ipc.handlers.vcs_worktree_include = () => ({ exists: true });
window.__ipc.handlers.vcs_add_worktree = () => ({ copyWarning: null, setupWarning: null });
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ root, roots: [root, service], repo: root, available: true });
const context = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ context);
setContext("vcsAvailable", true);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("vcs.newWorktree");
});
const dialog = page.getByRole("dialog", { name: "New Worktree" });
const name = dialog.getByRole("textbox", { name: "Name:" });
const branch = dialog.getByRole("textbox", { name: "New branch name" });
const location = dialog.getByRole("textbox", { name: "Location:" });
const repository = dialog.getByRole("button", { name: "Repository", exact: true });
const checkout = dialog.getByRole("button", { name: "Check out", exact: true });
const setup = dialog.getByRole("checkbox", { name: "Run setup script" });
const script = dialog.getByRole("textbox", { name: "Setup script:" });
await expect(name).toHaveValue("acme-api-main-wt");
await branch.fill("review/ledger-batch");
await name.fill("ledger-review");
await location.fill("/dev/reviews");
await setup.check();
await script.fill("/dev/setup.sh");
const preview = dialog.getByText("Worktree location: /dev/reviews/ledger-review", { exact: true });
await expect(preview).toBeVisible();
for (const size of [
{ width: 1120, height: 740 },
{ width: 440, height: 520 },
]) {
await page.setViewportSize(size);
const column = (await name.boundingBox())!.x;
for (const [label, field] of [
["Name:", name],
["Location:", location],
["Repository:", repository],
["Check out:", checkout],
["Create a new branch", branch],
["Setup script:", script],
] as const) {
const caption = dialog.getByText(label, { exact: true });
await expect(caption).toBeVisible();
const captionBox = (await caption.boundingBox())!;
const fieldBox = (await field.boundingBox())!;
expect(fieldBox.x, label).toBeCloseTo(column, 0);
expect(captionBox.x + captionBox.width, label).toBeLessThanOrEqual(fieldBox.x);
expect(captionBox.y + captionBox.height / 2, label).toBeCloseTo(fieldBox.y + fieldBox.height / 2, 0);
}
expect((await preview.boundingBox())!.x).toBeCloseTo(column, 0);
}
await setup.uncheck();
await expect(script).toHaveCount(0);
await dialog.getByRole("button", { name: "Create", exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(await ipcCalls(page, "vcs_add_worktree")).toEqual([
{
repo: "/dev/acme-api",
path: "/dev/reviews/ledger-review",
commitish: "refs/heads/main",
newBranch: "review/ledger-batch",
copyConfig: true,
setup: null,
},
]);
});
+4 -1
Переглянути файл
@@ -122,7 +122,10 @@ test("Find in Files streams matches by file and opens the chosen one at its line
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const own = getComputedStyle(el);
return own.backgroundColor === expected && own.color === getComputedStyle(el.parentElement!).color;
return (
(own.backgroundColor === expected || own.backgroundImage.includes(expected)) &&
own.color === getComputedStyle(el.parentElement!).color
);
}),
).toBe(true);
const originalPreview = await preview.textContent();
+30 -1
Переглянути файл
@@ -3,7 +3,7 @@
* header on screen: titles stay on one line and every header control lies inside the popup.
*/
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
@@ -118,6 +118,35 @@ test.describe("search popups at the minimum window width", () => {
await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true });
});
test("multi-line search and replacement leave room for matches and scroll inside their fields", async ({
workbench: page,
}) => {
await stubFindMatches(page);
await run(page, "find.replaceInPath");
const dialog = page.getByRole("dialog", { name: "Replace in Files" });
const search = dialog.getByRole("textbox", { name: "Text to find" });
const replacement = dialog.getByRole("textbox", { name: "Replace with" });
const query = "base=http://localhost:8080\nregion=eu-west\nmode=batch\nverify=true\nretry=2\ntimeout=30";
const changed = query.replace("localhost:8080", "localhost:9443").replace("retry=2", "retry=4");
await search.fill(query);
await replacement.fill(changed);
for (const field of [search, replacement]) {
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
expect(visibleLines).toBeCloseTo(3);
await field.press("Control+End");
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
}
await expect(search).toHaveValue(query);
await expect(replacement).toHaveValue(changed);
await expect(dialog.getByRole("listbox", { name: "Matches" }).getByRole("option").first()).toBeInViewport();
const calls = await ipcCalls(page, "search_start");
expect(calls.some(({ query: sent }) => (sent as { pattern: string }).pattern === query)).toBe(true);
await expect(dialog.getByRole("button", { name: "Replace All", exact: true })).toBeInViewport({ ratio: 1 });
await replacement.fill("updated");
await expect(replacement).toHaveAttribute("rows", "1");
});
test("Replace in Files keeps its footer actions together as the window narrows", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 750 });
await openFromTree(page, "settings.gradle.kts");
+439 -1
Переглянути файл
@@ -1,5 +1,5 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
/** Supply detected configurations without launching desktop processes. */
async function configure(page: Page, extra = 0) {
@@ -241,3 +241,441 @@ test("the Services detail pane adds no second scrollbar over a console", async (
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
expect(result.scrollers.length).toBeGreaterThan(0);
});
test("Docker dashboard keeps multi-line container commands bounded and collapsible", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const script = Array.from({ length: 18 }, (_, i) => ` export STEP_${i}="/persist/slot-${i}"`).join("\n");
const inspectJson = JSON.stringify([
{
Created: "2026-11-22T01:41:28Z",
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
Config: {
Entrypoint: ["/bin/bash", "-ec", `set -euo pipefail\n${script}\nexec /entrypoint.sh "$@"\n`, "--"],
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
WorkingDir: "/actions-runner",
Env: [],
Labels: {},
},
Mounts: [],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
const containerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
const snapshot = {
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
executable: "/usr/local/bin/docker",
containers: [
{
id: containerId,
name: "runner-1",
image: "myoung34/github-runner:latest",
command: '"/bin/bash -ec \'set…"',
state: "running",
status: "Up 2 hours",
ports: "",
createdAt: "2026-11-22 01:41:28 +0000 UTC",
composeProject: "selfhost",
composeService: "github-runner",
composeWorkingDir: "/Users/dev/selfhost",
composeFiles: ["/Users/dev/selfhost/docker-compose.yml"],
},
],
images: [],
volumes: [],
networks: [],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_inspect = () => inspectJson;
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "1.20%",
memUsage: "256MiB / 8GiB",
memPerc: "3.12%",
netIo: "1MB / 1MB",
blockIo: "0B / 0B",
pids: "12",
});
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.cancel_request = () => null;
const storeModule = "/src/features/services/store.ts";
const treeModule = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeModule);
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
useServices.setState({
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { local: { snapshot, loading: false, error: null } },
detailTab: "dashboard",
});
useServicesTree.setState({
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
selectedKey: `docker:local:container:${containerId}`,
selectedKeys: new Set([`docker:local:container:${containerId}`]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
await expect(services.getByText("Container Overview")).toBeVisible();
const toggle = services.getByRole("button", { name: /^\d+ lines$/ });
await expect(toggle).toHaveAttribute("aria-expanded", "false");
const preview = services.locator("code[data-no-tooltip]");
await expect(preview).toContainText("↵");
// Hovering the truncated command preview must not spawn a giant auto-ellipsis tooltip.
await preview.hover();
await page.waitForTimeout(700);
await expect(page.getByRole("tooltip")).toHaveCount(0);
// Collapsed row stays strictly between Started and Working directory (no upward overlap).
const startedLabel = services.getByText("Started", { exact: true });
const commandLabel = services.getByText("Command", { exact: true });
const workingDirLabel = services.getByText("Working directory", { exact: true });
const collapsedStartedBox = (await startedLabel.boundingBox())!;
const collapsedPreviewBox = (await preview.boundingBox())!;
const collapsedWorkingBox = (await workingDirLabel.boundingBox())!;
expect(collapsedPreviewBox.y).toBeGreaterThan(collapsedStartedBox.y + collapsedStartedBox.height);
expect(collapsedWorkingBox.y).toBeGreaterThan(collapsedPreviewBox.y + collapsedPreviewBox.height);
// Expanding reveals Entrypoint + Command arguments inside a bounded scroll box growing downward.
await toggle.click();
const collapseBtn = services.getByRole("button", { name: "Collapse", exact: true });
await expect(collapseBtn).toHaveAttribute("aria-expanded", "true");
await expect(services.getByText("Entrypoint", { exact: true })).toBeVisible();
await expect(services.getByText("Command arguments", { exact: true })).toBeVisible();
const expandedStartedBox = (await startedLabel.boundingBox())!;
const expandedCommandLabelBox = (await commandLabel.boundingBox())!;
const entrypointPre = services.locator("pre").first();
const scrollContainer = entrypointPre.locator("xpath=ancestor::div[1]/parent::div");
const scrollBox = (await scrollContainer.boundingBox())!;
const expandedWorkingBox = (await workingDirLabel.boundingBox())!;
expect(expandedCommandLabelBox.y).toBeGreaterThan(expandedStartedBox.y + expandedStartedBox.height);
expect(scrollBox.y).toBeGreaterThan(expandedCommandLabelBox.y);
expect(scrollBox.height).toBeLessThanOrEqual(182);
expect(expandedWorkingBox.y).toBeGreaterThanOrEqual(scrollBox.y + scrollBox.height - 1);
await collapseBtn.click();
await expect(services.getByRole("button", { name: /^\d+ lines$/ })).toHaveAttribute("aria-expanded", "false");
});
test("Docker Compose container Jump to Source opens the Compose file at the command or the service", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const composePath = "/dev/acme-api/docker-compose.yml";
const composeYaml = [
"services:",
" postgres:",
" image: postgres:16",
" github-runner:",
" image: myoung34/github-runner:latest",
" entrypoint:",
" - /bin/bash",
" - -ec",
" - |",
" mkdir -p /persist/slots",
' exec /entrypoint.sh "$@"',
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
"",
].join("\n");
const backendModule = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
docBackend().files.set(composePath, composeYaml);
window.__ipc.handlers.fs_read_text = ({ path }) => {
if (path === composePath) return composeYaml;
throw { kind: "notFound", message: `not found: ${String(path)}`, detail: null };
};
const runnerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
const dbId = "98ab76cd54ef3210fedcba9876543210abcdef0123456789abcdef0123456789";
const snapshot = {
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
executable: "/usr/local/bin/docker",
containers: [
{
id: runnerId,
name: "selfhost-github-runner-1",
image: "myoung34/github-runner:latest",
command: '"/bin/bash -ec \'mkdir…"',
state: "running",
status: "Up 2 hours",
ports: "",
createdAt: "2026-11-22 01:41:28 +0000 UTC",
composeProject: "selfhost",
composeService: "github-runner",
composeWorkingDir: "/dev/acme-api",
composeFiles: [composePath],
},
{
id: dbId,
name: "selfhost-postgres-1",
image: "postgres:16",
command: "postgres",
state: "running",
status: "Up 2 hours",
ports: "",
createdAt: "2026-11-22 01:41:28 +0000 UTC",
composeProject: "selfhost",
composeService: "postgres",
composeWorkingDir: "/dev/acme-api",
composeFiles: [composePath],
},
],
images: [],
volumes: [],
networks: [],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_inspect = () =>
JSON.stringify([
{
Created: "2026-11-22T01:41:28Z",
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
Config: {
Entrypoint: ["/bin/bash", "-ec", 'mkdir -p /persist/slots\nexec /entrypoint.sh "$@"'],
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
WorkingDir: "/actions-runner",
Env: [],
Labels: {},
},
Mounts: [],
NetworkSettings: { Ports: {}, Networks: {} },
},
]);
window.__ipc.handlers.docker_container_stats = () => ({
cpuPerc: "0.50%",
memUsage: "128MiB / 8GiB",
memPerc: "1.56%",
netIo: "0B / 0B",
blockIo: "0B / 0B",
pids: "4",
});
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.cancel_request = () => null;
const storeModule = "/src/features/services/store.ts";
const treeModule = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeModule);
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
useServices.setState({
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { local: { snapshot, loading: false, error: null } },
detailTab: "dashboard",
});
useServicesTree.setState({
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
selectedKey: `docker:local:container:${runnerId}`,
selectedKeys: new Set([`docker:local:container:${runnerId}`]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
await expect(services.getByText("Container Overview")).toBeVisible();
// Clicking Jump to Source on the Command row opens docker-compose.yml with caret on `command:` value
await services.getByRole("button", { name: "Jump to Source", exact: true }).click();
const editor = page.locator(".cm-editor");
await expect(editor.locator(".cm-activeLine")).toHaveText(
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
);
const caret = await page.evaluate(async () => {
const api = await import(/* @vite-ignore */ "/src/editor/api.ts" as string);
const view = api.activeEditor()?.view;
if (!view) return null;
const head = view.state.selection.main.head;
const line = view.state.doc.lineAt(head);
return { line: line.number - 1, col: head - line.from };
});
expect(caret).toEqual({ line: 11, col: 13 });
// F4 on a Compose container node jumps to its service declaration
const tree = services.getByRole("tree", { name: "Services", exact: true });
await tree.getByRole("treeitem", { name: /github-runner/ }).click();
await page.keyboard.press("F4");
await expect(editor.locator(".cm-activeLine")).toHaveText(" github-runner:");
await tree.getByRole("treeitem", { name: /postgres/ }).click();
await page.keyboard.press("F4");
await expect(editor.locator(".cm-activeLine")).toHaveText(" postgres:");
});
test("Docker Compose dashboard shows per-service resource usage and named project volumes", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
(window as unknown as { __cpuPerc: string }).__cpuPerc = "6.25%";
const anonName = "37cc33a7d603260a82a378d7d3eeb835b748b5712614e2e5b4a3d6572f5e1e71";
const snapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: null },
executable: "/usr/bin/docker",
containers: [
{
id: "db-1",
name: "shop-db-1",
image: "postgres:16",
command: "postgres",
state: "running",
status: "Up 15 minutes",
ports: "127.0.0.1:5432->5432/tcp",
createdAt: "2026-04-20T05:00:00Z",
composeProject: "shop",
composeService: "db",
composeWorkingDir: "/work/shop",
composeFiles: ["/work/shop/docker-compose.yml"],
mounts: ["shop_pgdata"],
networks: ["shop_default"],
},
{
id: "api-1",
name: "shop-api-1",
image: "node:22",
command: "node server.js",
state: "exited",
status: "Exited (0) 2 minutes ago",
ports: "",
createdAt: "2026-04-20T05:00:00Z",
composeProject: "shop",
composeService: "api",
composeWorkingDir: "/work/shop",
composeFiles: ["/work/shop/docker-compose.yml"],
mounts: [],
networks: ["shop_default"],
},
],
images: [],
volumes: [
{
name: anonName,
driver: "local",
mountpoint: `/var/lib/docker/volumes/${anonName}/_data`,
composeProject: "shop",
scope: "local",
labels: { "com.docker.volume.anonymous": "" },
},
{
name: "shop_pgdata",
driver: "local",
mountpoint: "/var/lib/docker/volumes/shop_pgdata/_data",
composeProject: "shop",
scope: "local",
labels: {
"com.docker.compose.project": "shop",
"com.docker.compose.volume": "pgdata",
},
},
{
name: "other_cache",
driver: "local",
mountpoint: "/var/lib/docker/volumes/other_cache/_data",
composeProject: "other",
scope: "local",
labels: {
"com.docker.compose.project": "other",
"com.docker.compose.volume": "cache",
},
},
],
networks: [{ id: "net-1", name: "shop_default", driver: "bridge", scope: "local", composeProject: "shop" }],
errors: [],
};
window.__ipc.handlers.docker_settings = () => ({
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
registries: [],
});
window.__ipc.handlers.docker_snapshot = () => snapshot;
window.__ipc.handlers.docker_events = () => new Promise(() => {});
window.__ipc.handlers.docker_inspect = () => "[]";
window.__ipc.handlers.docker_container_stats = ({ id }) => {
if (id !== "db-1") throw { kind: "notFound", message: "container not running", detail: null };
return {
cpuPerc: (window as unknown as { __cpuPerc: string }).__cpuPerc,
memUsage: "128MiB / 2GiB",
memPerc: "6.25%",
netIo: "2.4MB / 980kB",
blockIo: "12MB / 4.1MB",
pids: "17",
};
};
const storeMod = "/src/features/services/store.ts";
const treeMod = "/src/features/services/tree.ts";
const { useServices } = await import(/* @vite-ignore */ storeMod);
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
useServices.setState({
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
conns: { default: { snapshot, loading: false, error: null } },
});
useServicesTree.setState({
expanded: new Set(["docker:default"]),
selectedKey: "docker:default:compose:shop",
selectedKeys: new Set(["docker:default:compose:shop"]),
});
});
await page.keyboard.press("Meta+8");
const services = page.getByRole("region", { name: "Services", exact: true });
const detail = services.locator("[data-panel][id=services-detail]");
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
const dbRow = detail.locator("tr", { hasText: "shop-db-1" });
const apiRow = detail.locator("tr", { hasText: "shop-api-1" });
await expect(dbRow).toContainText("6.25%");
await expect(dbRow).toContainText("128MiB / 2GiB (6.25%)");
await expect(dbRow).toContainText("2.4MB / 980kB");
await expect(dbRow).toContainText("12MB / 4.1MB");
await expect(dbRow).toContainText("17");
await expect(apiRow).toContainText("Exited (0) 2 minutes ago");
// Stopped service container is never queried for live stats, and no manual Refresh button is shown.
const queriedIds = (await ipcCalls(page, "docker_container_stats")).map((c) => c.id);
expect(new Set(queriedIds)).toEqual(new Set(["db-1"]));
await expect(detail.getByRole("button", { name: "Refresh", exact: true })).toHaveCount(0);
// Running service metrics auto-refresh in place without user action.
await page.evaluate(() => {
(window as unknown as { __cpuPerc: string }).__cpuPerc = "18.50%";
});
await expect(dbRow).toContainText("18.50%", { timeout: 5000 });
// Named Compose volume appears with logical name + driver; anonymous and other-project volumes do not.
const volumeButton = detail.getByRole("button", { name: /shop_pgdata/ });
await expect(volumeButton).toContainText("pgdata · local");
await expect(detail.getByText("other_cache")).toHaveCount(0);
await expect(detail.getByText(/37cc33a7/)).toHaveCount(0);
// Clicking the named volume opens its Volume dashboard and links back to the Compose project.
await volumeButton.click();
await expect(detail.getByText("Volume Overview")).toBeVisible();
await detail.getByRole("button", { name: "shop", exact: true }).click();
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
// Clicking a service in the table navigates to its Container dashboard, which auto-refreshes live stats.
await detail.getByRole("button", { name: "shop-db-1", exact: true }).click();
await expect(detail.getByText("Container Overview")).toBeVisible();
await expect(detail).toContainText("18.50%");
await page.evaluate(() => {
(window as unknown as { __cpuPerc: string }).__cpuPerc = "27.40%";
});
await expect(detail).toContainText("27.40%", { timeout: 5000 });
});
+2
Переглянути файл
@@ -385,6 +385,8 @@ test("edits and stages from the index in unified diffs of read-only files", asyn
const index = modal.locator('.cm-content[aria-label="Staged (index)"]');
await expect(index).toBeEditable();
await expect(index).toHaveText(/val alpha = "index"\s+val alpha = "local"/, { useInnerText: true });
await expect(modal.locator(".cm-diffNumbers-modified .cm-diffWidgetNumber")).toHaveText(["1", "3"]);
await expect(modal.locator(".cm-diffNumbers-original .cm-diffWidgetNumber")).toHaveCount(0);
const setReadOnly = (readOnly: boolean) =>
page.evaluate((readOnly) => window.__ipc.handlers.test_set_readonly?.({ readOnly }), readOnly);
await setReadOnly(false);
+79
Переглянути файл
@@ -0,0 +1,79 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("groups stashes by repository and keeps the selected stash actions scoped", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(async () => {
const main = "/dev/acme-api";
const service = `${main}/warehouse-api`;
const stash = (index: number, id: string, title: string) => ({
index,
id,
message: `On main: ${title}`,
base: "base",
timeMs: new Date(2025, 4, 14, 10, 30).getTime(),
});
const handlers = window.__ipc.handlers;
handlers.vcs_stashes = ({ repo }) =>
repo === service
? [stash(0, "warehouse-stash", "Review warehouse routing")]
: [stash(0, "ledger-stash", "Check totals"), stash(1, "invoice-stash", "Match invoice balances")];
handlers.vcs_commit_files = ({ repo }) => [
{ path: repo === service ? "routing.txt" : "totals.txt", kind: "modified", oldPath: null },
];
const store = "/src/features/vcs/store.ts";
const context = "/src/platform/context.ts";
const actions = "/src/platform/actions.ts";
const toolWindows = "/src/workbench/toolwindows/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
const { setContext } = await import(/* @vite-ignore */ context);
const { executeAction } = await import(/* @vite-ignore */ actions);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ toolWindows);
useVcs.setState({ available: true, root: main, repo: main, roots: [main, service] });
setContext("vcsAvailable", true);
moveToolWindow("commit", "bottom");
await executeAction("vcs.showStashes");
setToolWindowSize("bottom", 310);
});
const tree = page.getByRole("tree", { name: "Stashes", exact: true });
const main = tree.getByRole("treeitem").filter({ has: page.getByText("acme-api", { exact: true }) });
const service = tree.getByRole("treeitem", { name: /warehouse-api/ });
const apply = page
.getByRole("toolbar", { name: "Stashes", exact: true })
.getByRole("button", { name: "Apply Stash" });
const first = tree.getByRole("treeitem", { name: /Check totals/ });
await expect(service, "repository group starts expanded").toHaveAttribute("aria-expanded", "true");
await expect(main).toHaveAccessibleName(/acme-api\s*2/);
await expect(first).toHaveAttribute("aria-level", "2");
await expect(first).toHaveAttribute("aria-selected", "true");
for (const width of [1100, 440]) {
await page.setViewportSize({ width, height: 720 });
const subject = first.getByText("Check totals", { exact: true });
const date = subject.locator("xpath=following-sibling::*[1]");
await expect(date).toHaveText(/2025/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(date).toHaveCSS("font-size", await subject.evaluate((el) => getComputedStyle(el).fontSize));
const titleBox = (await subject.boundingBox())!;
const dateBox = (await date.boundingBox())!;
expect(dateBox.x - titleBox.x - titleBox.width).toBeCloseTo(6, 0);
}
await tree.focus();
await tree.press("Home");
await tree.press("ArrowLeft");
await expect(main).toHaveAttribute("aria-expanded", "false");
await expect(first).toHaveCount(0);
await expect(apply).toBeDisabled();
await expect(page.getByText("Select a stash to view its changes.")).toBeVisible();
await tree.press("ArrowRight");
await expect(first).toBeVisible();
await tree.getByText("Review warehouse routing", { exact: true }).click();
await expect(apply).toBeEnabled();
await expect(page.getByRole("tree", { name: "Changed files" }).getByText("routing.txt")).toBeVisible();
expect((await ipcCalls(page, "vcs_commit_files")).at(-1)).toEqual({
repo: "/dev/acme-api/warehouse-api",
commit: "warehouse-stash",
});
});
+123
Переглянути файл
@@ -0,0 +1,123 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function seedReview(page: Page) {
await stubDesktop(page);
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const context = "/src/platform/context.ts";
const repositoryStore = "/src/features/github/data/repository.ts";
const pullRequests = "/src/features/github/data/pullRequest.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { setContext } = await import(/* @vite-ignore */ context);
const { useGhRepository } = await import(/* @vite-ignore */ repositoryStore);
const { setPullRequestData } = await import(/* @vite-ignore */ pullRequests);
useProject.setState((s: { settings: { editor: unknown } }) => ({
settings: {
...s.settings,
editor: { ...(s.settings?.editor as object), fontFamily: "Courier New", fontSize: 17, lineHeight: 25 },
},
}));
const coordinates = { owner: "sample", name: "settlement" };
useGhRepository.setState({
connection: {
coordinates,
repository: { id: "repository", nameWithOwner: "sample/settlement" },
currentUser: { id: "reviewer", login: "reviewer" },
root: null,
remotes: [],
},
});
setContext("githubConnected", true);
setContext("githubCurrentBranchPullRequest", true);
setPullRequestData(7, "details", () => ({ number: 7, viewerDidAuthor: false }));
setPullRequestData(7, "pendingReview", () => ({ id: "draft-seven", state: "PENDING", commentsCount: 12 }));
});
}
async function openReview(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("github.pullRequest.submitReview", 7);
});
}
test("centers the unanchored composer, follows the editor font and reflows its review actions", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 840 });
await seedReview(page);
await openReview(page);
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const verticalCenter = () =>
popup.evaluate((el) => {
const { top, height } = el.getBoundingClientRect();
return Math.abs(top + height / 2 - innerHeight / 2);
});
await expect.poll(verticalCenter, { message: "verticalCenter at standard size" }).toBeLessThan(1);
await expect(editor).toBeFocused();
await expect(editor).toHaveCSS("font-size", "17px");
await expect(editor).toHaveCSS("line-height", "25px");
await expect(editor).toHaveCSS("font-family", /Courier New/);
await editor.fill("Please double-check the rounding step.");
const grip = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 56, grip.y + grip.height / 2 + 32);
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(540);
await page.setViewportSize({ width: 300, height: 400 });
await expect.poll(verticalCenter, { message: "verticalCenter after shrinking" }).toBeLessThan(1);
const approve = (await popup.getByRole("button", { name: "Approve", exact: true }).boundingBox())!;
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
expect(comment.y).toBeGreaterThan(approve.y);
expect(comment.x + comment.width).toBeLessThan(300);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await editor.press("Escape");
await expect(popup).toHaveCount(0);
await openReview(page);
await expect(editor).toHaveValue("Please double-check the rounding step.");
});
test("keeps anchored review controls and the comment visible after a long submission error", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 355, height: 390 });
await seedReview(page);
await page.evaluate(async () => {
const path = "/src/features/github/details/SubmitReviewPopup.tsx";
const { showSubmitReview } = await import(/* @vite-ignore */ path);
const anchor = document.createElement("button");
anchor.style.cssText = "position:fixed;top:350px;left:275px;";
anchor.textContent = "Review anchor";
document.body.append(anchor);
window.__ipc.handlers.gh_api = ({ request }) => {
const { query } = JSON.parse((request as { body: string }).body);
if (!query.includes("submitPullRequestReview")) throw Error("Unexpected GitHub request");
return JSON.stringify({ errors: [{ message: "Review request failed. " + "outdated-reference-".repeat(35) }] });
};
void showSubmitReview(7, anchor);
});
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const button = popup.getByRole("button", { name: "Comment", exact: true });
await editor.fill("Check the batch limit.");
await button.click();
const error = popup.getByRole("alert");
await expect(error).toContainText("Review request failed.");
await expect(button).toBeEnabled();
await expect(editor).toHaveValue("Check the batch limit.");
const box = (await popup.boundingBox())!;
const buttonBox = (await button.boundingBox())!;
expect(box.y + box.height).toBeLessThan(350);
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(box.y + box.height);
expect(box.x + box.width).toBeLessThanOrEqual(355);
await expect.poll(() => error.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
const calls = await ipcCalls(page, "gh_api");
expect(calls).toHaveLength(1);
const { variables } = JSON.parse((calls[0]!.request as { body: string }).body);
expect(variables).toEqual({ reviewId: "draft-seven", event: "COMMENT", body: "Check the batch limit." });
});
+88
Переглянути файл
@@ -0,0 +1,88 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openDiff(page: Page, left: string, right: string, options: Record<string, unknown> = {}) {
await page.evaluate(
async ({ left, right, options }) => {
localStorage.setItem(
"openidea.vcs.diffOptions",
JSON.stringify({ mode: "unified", collapse: false, ...options }),
);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("diff.compareTexts", {
path: "SettlementRules.txt",
left: { text: left, label: "Original" },
right: { text: right, label: "Modified" },
});
},
{ left, right, options },
);
return page.getByRole("toolbar", { name: "Diff" });
}
async function rowNumbers(page: Page, text: string, deleted = false) {
return page
.locator(deleted ? ".cm-deletedLine" : ".cm-line")
.filter({ hasText: text })
.evaluate((row) => {
const top = row.getBoundingClientRect().top;
const editor = row.closest(".cm-editor")!;
const read = (side: string) =>
[...editor.querySelectorAll(`.cm-diffNumbers-${side} :is(.cm-gutterElement, .cm-diffWidgetNumber)`)].find(
(number) =>
getComputedStyle(number).visibility === "visible" && Math.abs(number.getBoundingClientRect().top - top) < 1,
)?.textContent ?? null;
return [read("original"), read("modified")];
});
}
test("Unified Diff keeps original and modified numbers aligned with wrapped and removed lines", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1000, height: 640 });
const oldRule = "Obsolete settlement rule " + "requires review for each exceptional invoice. ".repeat(3);
const toolbar = await openDiff(
page,
["Settlement rules", oldRule, "Retire legacy routing", "Report totals", "Finish batch"].join("\n"),
["Settlement rules", "Validate settlement currency", "Report totals", "Finish batch"].join("\n"),
{ softWrap: true },
);
await expect(toolbar).toContainText("1 difference");
for (const width of [1000, 440]) {
await page.setViewportSize({ width, height: 640 });
await expect.poll(() => rowNumbers(page, "Obsolete settlement rule", true)).toEqual(["2", null]);
await expect.poll(() => rowNumbers(page, "Retire legacy routing", true)).toEqual(["3", null]);
await expect.poll(() => rowNumbers(page, "Validate settlement currency")).toEqual([null, "2"]);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["4", "3"]);
}
const removed = page.locator(".cm-deletedLine").filter({ hasText: "Obsolete settlement rule" });
const lineHeight = await removed.evaluate((el) => parseFloat(getComputedStyle(el).lineHeight));
expect((await removed.boundingBox())!.height).toBeGreaterThan(lineHeight * 2);
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(toolbar).toContainText("1 of 1 differences");
});
test("Unified Diff numbers account for ignored empty lines and a removal at EOF without a newline", async ({
workbench: page,
}) => {
await openDiff(
page,
"Settlement rules\n\nReport totals\nFinish batch\nRemove final rule",
"Settlement rules\nReport totals\nFinish batch",
{ ignore: "whitespaceAndLines" },
);
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["3", "2"]);
await expect.poll(() => rowNumbers(page, "Finish batch")).toEqual(["4", "3"]);
await expect.poll(() => rowNumbers(page, "Remove final rule", true)).toEqual(["5", null]);
});
test("Unified Diff follows vertical scrolling inside one large removal", async ({ workbench: page }) => {
const removed = Array.from({ length: 250 }, (_, i) => `Retired workflow ${i + 1}.`);
await openDiff(page, ["Start batch", ...removed, "Finish batch"].join("\n"), "Start batch\nFinish batch");
const target = page.locator(".cm-deletedLine").filter({ hasText: "Retired workflow 229." });
await target.scrollIntoViewIfNeeded();
await expect.poll(() => rowNumbers(page, "Retired workflow 229.", true)).toEqual(["230", null]);
});
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@
"@floating-ui/react-dom": "^2.1.9",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lezer/common": "^1.5.3",
"@lezer/common": "^1.5.6",
"@lezer/highlight": "^1.2.5",
"@lezer/lr": "^1.4.11",
"@mathjax/mathjax-tex-font": "4.1.3",
Створено
+44 -44
Переглянути файл
@@ -76,8 +76,8 @@ importers:
specifier: ^5.3.0
version: 5.3.0
'@lezer/common':
specifier: ^1.5.3
version: 1.5.3
specifier: ^1.5.6
version: 1.5.6
'@lezer/highlight':
specifier: ^1.2.5
version: 1.2.5
@@ -473,8 +473,8 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@lezer/[email protected].3':
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
'@lezer/[email protected].6':
resolution: {integrity: sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==}
'@lezer/[email protected]':
resolution: {integrity: sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==}
@@ -2481,21 +2481,21 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@codemirror/[email protected]':
dependencies:
'@codemirror/lang-html': 6.4.12
'@codemirror/lang-javascript': 6.2.5
'@codemirror/language': 6.13.1
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -2509,7 +2509,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/css': 1.3.9
'@codemirror/[email protected]':
@@ -2517,7 +2517,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/go': 1.0.1
'@codemirror/[email protected]':
@@ -2528,7 +2528,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/css': 1.3.9
'@lezer/html': 1.3.13
@@ -2544,7 +2544,7 @@ snapshots:
'@codemirror/lint': 6.9.7
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/javascript': 1.5.6
'@codemirror/[email protected]':
@@ -2554,7 +2554,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -2567,7 +2567,7 @@ snapshots:
dependencies:
'@codemirror/lang-css': 6.3.1
'@codemirror/language': 6.13.1
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -2578,7 +2578,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -2589,7 +2589,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/markdown': 1.8.0
'@codemirror/[email protected]':
@@ -2597,7 +2597,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/php': 1.0.6
'@codemirror/[email protected]':
@@ -2605,7 +2605,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/python': 1.1.19
'@codemirror/[email protected]':
@@ -2618,7 +2618,7 @@ snapshots:
'@codemirror/lang-css': 6.3.1
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/sass': 1.1.0
'@codemirror/[email protected]':
@@ -2626,7 +2626,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -2635,14 +2635,14 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/lang-javascript': 6.2.5
'@codemirror/language': 6.13.1
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -2652,7 +2652,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/xml': 1.0.6
'@codemirror/[email protected]':
@@ -2660,7 +2660,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/yaml': 1.0.4
@@ -2696,7 +2696,7 @@ snapshots:
'@codemirror/state': 6.7.6
'@codemirror/streamparser': 6.0.0
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
style-mod: 4.1.4
@@ -2832,101 +2832,101 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0
'@lezer/[email protected].3': {}
'@lezer/[email protected].6': {}
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected](patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
@@ -3200,12 +3200,12 @@ snapshots:
dependencies:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@plutojl/lezer-julia': 1.2.0
'@plutojl/[email protected]':
dependencies:
'@lezer/common': 1.5.3
'@lezer/common': 1.5.6
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
+61
Переглянути файл
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
import { javascript } from "@codemirror/lang-javascript";
import { EditorState } from "@codemirror/state";
import { TreeFragment } from "@lezer/common";
/** Functions with long doc comments: re-parsing reuses a whole comment as one node. */
const source = Array.from(
@@ -25,3 +26,63 @@ describe("incremental parsing (#4468)", () => {
expect(tree.topNode.firstChild?.from).toBe(0);
});
});
/** `count` documented classes: as many top-level statements, each after a doc comment longer than the parser's look-ahead margin. */
function documentedClasses(count: number): string {
return Array.from(
{ length: count },
(_, i) =>
`/** Repository for entity ${i}, with a comment long enough to look ahead of. */\n` +
`export class Repository${i}<T extends { id: number }> {\n` +
` find(id: number): T | undefined {\n return this.items.get(id)\n }\n}\n\n`,
).join("");
}
const parser = javascript({ typescript: true }).language.parser;
/** Inserts `insert` at `at`, re-parsing incrementally from `tree`; returns the new tree and how many parser steps that took. */
function reparse(doc: string, tree: ReturnType<typeof parser.parse>, at: number, insert: string) {
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
{ fromA: at, toA: at, fromB: at, toB: at + insert.length },
]);
const edited = doc.slice(0, at) + insert + doc.slice(at);
const parse = parser.startParse(edited, fragments);
let steps = 0;
let result = null;
while (!(result = parse.advance())) steps++;
return { doc: edited, tree: result, steps };
}
describe("incremental parsing of long statement lists", () => {
// A repeat group's look-ahead was that of the whole list, ending at the last doc comment: no group before an
// edit could be reused, so typing cost grew with the position in the file, one statement at a time.
it("takes as many parser steps in a long file as in a short one", () => {
const steps = (count: number) => {
const doc = documentedClasses(count);
const at = doc.indexOf("return", doc.length >> 1);
return reparse(doc, parser.parse(doc), at, "a").steps;
};
const short = steps(100);
const long = steps(1600);
expect(long).toBeLessThan(short * 2);
});
it("matches a fresh parse wherever the edit is", () => {
const doc = documentedClasses(300);
const tree = parser.parse(doc);
const edits: Array<[string, string]> = [
["/**", "a"],
["return", "a"],
["export class Repository150", "// "],
["}\n\n/** Repository for entity 299", "}"],
["find(id", "static "],
];
for (const [anchor, insert] of edits) {
const at = doc.indexOf(anchor) + (anchor.startsWith("}") ? 0 : 0);
const result = reparse(doc, tree, at, insert);
expect(result.tree.toString(), `after inserting ${JSON.stringify(insert)} before ${JSON.stringify(anchor)}`).toBe(
parser.parse(result.doc).toString(),
);
}
});
});
+37
Переглянути файл
@@ -0,0 +1,37 @@
/**
* Paints an inline mark's background capped at `1lh` so a font taller than the line height
* does not bleed into the rows above and below. When the inline box is shorter than `1lh`,
* its own border box clips the gradient. Safari before 16.4 has no `lh` and drops the
* shorthand, keeping the plain colour before it.
*/
export function inlineBackground(color: string) {
return {
backgroundColor: color,
background: `linear-gradient(${color}, ${color}) center / 100% 1lh no-repeat`,
WebkitBoxDecorationBreak: "clone",
boxDecorationBreak: "clone",
};
}
/** Fallback style for an inline mark with a 1px frame (`inlineFramedModern` caps it at `1lh`). */
export function inlineFramedFallback(fill: string, frame: string) {
return {
backgroundColor: fill,
outline: `1px solid ${frame}`,
outlineOffset: "-1px",
WebkitBoxDecorationBreak: "clone",
boxDecorationBreak: "clone",
};
}
/** `@supports (height: 1lh)` override for `inlineFramedFallback`: caps both fill and 1px frame at `1lh`. */
export function inlineFramedModern(fill: string, frame: string) {
return {
outline: "none",
background: [
`linear-gradient(to bottom, ${frame} 0 1px, transparent 1px calc(100% - 1px), ${frame} calc(100% - 1px) 100%) center / 100% min(100%, 1lh) no-repeat`,
`linear-gradient(to right, ${frame} 0 1px, transparent 1px calc(100% - 1px), ${frame} calc(100% - 1px) 100%) center / 100% min(100%, 1lh) no-repeat`,
`linear-gradient(${fill}, ${fill}) center / calc(100% - 2px) calc(min(100%, 1lh) - 2px) no-repeat`,
].join(", "),
};
}
+96
Переглянути файл
@@ -0,0 +1,96 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { StreamLanguage } from "@codemirror/language";
import { javascript } from "@codemirror/lang-javascript";
import { kotlin } from "@codemirror/legacy-modes/mode/clike";
import { highlightTree } from "@lezer/highlight";
import { lineLiteralAt, literalAt, literalsExtension } from "./literals";
import { setSyntaxHighlights } from "./syntaxHighlight";
vi.mock("@lezer/highlight", async (importOriginal) => {
const original = await importOriginal<typeof import("@lezer/highlight")>();
return { ...original, highlightTree: vi.fn(original.highlightTree) };
});
const highlighted = vi.mocked(highlightTree);
beforeEach(() => {
highlighted.mockClear();
});
/** The `[from, to]` window of every `highlightTree` call since the last `beforeEach`. */
const windows = () => highlighted.mock.calls.map(([tree, , , from = 0, to = tree.length]) => [from, to]);
const code = (lines: number) =>
Array.from({ length: lines }, (_, i) => `const v${i} = "value ${i}"; // note ${i}\nlet n${i} = ${i};`).join("\n") +
"\nconst text = `first\nsecond`;\n";
const typescript = () => [javascript({ typescript: true })];
describe("lineLiteralAt", () => {
it("finds the string literal or comment at a position, as literalAt does", () => {
const state = EditorState.create({ doc: code(20), extensions: typescript() });
const at = (needle: string, shift = 0) => state.doc.toString().indexOf(needle) + shift;
for (const [pos, kind] of [
[at('"value 7"', 3), "string"],
[at("// note 7", 4), "comment"],
[at("const v7", 2), null],
[at("n7 = 7", 4), null],
] as const) {
expect(lineLiteralAt(state, pos)?.kind ?? null).toBe(kind);
expect(lineLiteralAt(state, pos)).toEqual(literalAt(state, pos));
}
});
it("returns a literal that goes on past the line cut at the line break", () => {
const state = EditorState.create({ doc: code(3), extensions: typescript() });
const doc = state.doc.toString();
const open = doc.indexOf("`first");
const lit = lineLiteralAt(state, open + 2)!;
expect(lit.kind).toBe("string");
expect(lit.from).toBe(open);
expect(state.doc.lineAt(lit.to).number).not.toBe(state.doc.lineAt(lit.from).number);
const second = doc.indexOf("second");
const rest = lineLiteralAt(state, second + 2)!;
expect(state.doc.lineAt(rest.from).number).not.toBe(state.doc.lineAt(rest.to).number);
});
it("highlights the line and its line breaks, not the document", () => {
// `literalAt` asks for the whole document: a rebuilt scan of every line for each Enter typed.
const sizes = [200, 4000].map((lines) => {
const state = EditorState.create({ doc: code(lines), extensions: typescript() });
const pos = state.doc.toString().indexOf('"value 150"') + 3;
const line = state.doc.lineAt(pos);
highlighted.mockClear();
expect(lineLiteralAt(state, pos)?.kind).toBe("string");
const covered = windows().map(([from, to]) => to! - from!);
expect(Math.max(...covered)).toBeLessThanOrEqual(line.length + 2);
return covered.length;
});
expect(sizes[1]).toBe(sizes[0]);
});
it("finds literals of languages with a stream parser", () => {
const doc = 'val a = 1\nval s = "hi there" // done\n';
const state = EditorState.create({ doc, extensions: [StreamLanguage.define(kotlin)] });
expect(lineLiteralAt(state, doc.indexOf("hi") + 1)).toEqual({
from: doc.indexOf('"hi'),
to: doc.indexOf(" //"),
kind: "string",
});
expect(lineLiteralAt(state, doc.indexOf("done"))?.kind).toBe("comment");
expect(lineLiteralAt(state, doc.indexOf("val a"))).toBeNull();
});
it("falls back to the highlights of the backend for languages without a parser", () => {
const doc = "plain\nx = 'quoted'\n";
const state = EditorState.create({ doc, extensions: [literalsExtension] }).update({
effects: setSyntaxHighlights.of({ kinds: ["string"], data: [doc.indexOf("'q"), doc.indexOf("'\n") + 1, 0] }),
}).state;
expect(lineLiteralAt(state, doc.indexOf("quoted"))).toEqual({
from: doc.indexOf("'q"),
to: doc.indexOf("'\n") + 1,
kind: "string",
});
expect(lineLiteralAt(state, 2)).toBeNull();
});
});
+34 -6
Переглянути файл
@@ -6,6 +6,7 @@
*/
import { StateField, type EditorState } from "@codemirror/state";
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
import type { Tree } from "@lezer/common";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import type { SyntaxHighlightKind } from "@/platform/ipc";
import type { LiteralKind } from "@/platform/search";
@@ -64,17 +65,29 @@ const cache = new WeakMap<object, readonly LiteralRange[]>();
/** How long counting may wait for the parser to reach the end of the document. */
const PARSE_BUDGET_MS = 50;
/** Comments and string literals of `tree` between `from` and `to`; a literal reaching past either end is cut there. */
function highlightedLiterals(tree: Tree, from: number, to: number): LiteralRange[] {
const out: LiteralRange[] = [];
highlightTree(
tree,
highlighter,
(start, end, cls) => {
const kind: LiteralKind | null = cls.includes("comment") ? "comment" : cls.includes("string") ? "string" : null;
if (kind) push(out, start, end, kind);
},
from,
to,
);
return out;
}
/** Comments and string literals of `state` (cached per syntax tree). */
export function literalRanges(state: EditorState): readonly LiteralRange[] {
const tree = ensureSyntaxTree(state, state.doc.length, PARSE_BUDGET_MS) ?? syntaxTree(state);
if (tree.length === 0) return state.field(treeSitterLiterals, false) ?? [];
const hit = cache.get(tree);
if (hit) return hit;
const out: LiteralRange[] = [];
highlightTree(tree, highlighter, (from, to, cls) => {
const kind: LiteralKind | null = cls.includes("comment") ? "comment" : cls.includes("string") ? "string" : null;
if (kind) push(out, from, to, kind);
});
const out = highlightedLiterals(tree, 0, tree.length);
cache.set(tree, out);
return out;
}
@@ -86,7 +99,22 @@ export function literalKindAt(state: EditorState, pos: number): LiteralKind | nu
/** The comment or string literal `pos` lies in, if any. */
export function literalAt(state: EditorState, pos: number): LiteralRange | null {
const ranges = literalRanges(state);
return rangeAt(literalRanges(state), pos);
}
/**
* Like `literalAt`, for a caller that only wants literals within one line: it parses and highlights
* the line of `pos` and the line breaks around it, not the document. A literal that goes on past
* the line comes back cut at the line break, so it still reaches into another line.
*/
export function lineLiteralAt(state: EditorState, pos: number): LiteralRange | null {
const line = state.doc.lineAt(pos);
const tree = ensureSyntaxTree(state, line.to, PARSE_BUDGET_MS) ?? syntaxTree(state);
if (tree.length === 0) return literalAt(state, pos);
return rangeAt(highlightedLiterals(tree, Math.max(0, line.from - 1), Math.min(tree.length, line.to + 1)), pos);
}
function rangeAt(ranges: readonly LiteralRange[], pos: number): LiteralRange | null {
let lo = 0;
let hi = ranges.length - 1;
while (lo <= hi) {
+19
Переглянути файл
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, Prec, type Extension } from "@codemirror/state";
import { Decoration, EditorView } from "@codemirror/view";
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "./inlineBg";
import { selectionMarks } from "./selectionMarks";
const views: EditorView[] = [];
@@ -54,4 +55,22 @@ describe("selectionMarks", () => {
v.dispatch({ selection: EditorSelection.cursor(3) });
expect(v.contentDOM.querySelector(".cm-openidea-selected")).toBeNull();
});
it("caps inline highlight backgrounds and 1px frames at 1lh with pre-16.4 fallbacks", () => {
expect(inlineBackground("var(--editor-search)")).toEqual({
backgroundColor: "var(--editor-search)",
background: "linear-gradient(var(--editor-search), var(--editor-search)) center / 100% 1lh no-repeat",
WebkitBoxDecorationBreak: "clone",
boxDecorationBreak: "clone",
});
expect(inlineFramedFallback("var(--fill)", "var(--frame)")).toMatchObject({
backgroundColor: "var(--fill)",
outline: "1px solid var(--frame)",
outlineOffset: "-1px",
});
const modern = inlineFramedModern("var(--fill)", "var(--frame)");
expect(modern.outline).toBe("none");
expect(modern.background).toContain("100% min(100%, 1lh)");
expect(modern.background).toContain("calc(100% - 2px) calc(min(100%, 1lh) - 2px)");
});
});
+8 -6
Переглянути файл
@@ -1,5 +1,6 @@
import { Prec, RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { inlineBackground } from "./inlineBg";
/**
* `drawSelection` paints the selection in a layer behind the text, so any mark with its own
@@ -38,12 +39,7 @@ const plugin = ViewPlugin.fromClass(
const theme = EditorView.baseTheme({
".cm-openidea-selected": {
"--openidea-selected-bg": "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
// Capped at `1lh` so a font taller than the line height does not bleed into the rows above and below.
// Safari before 16.4 has no `lh` and drops the shorthand, keeping the plain colour before it.
backgroundColor: "var(--openidea-selected-bg)",
background: "linear-gradient(var(--openidea-selected-bg), var(--openidea-selected-bg)) center / 100% 1lh no-repeat",
WebkitBoxDecorationBreak: "clone",
boxDecorationBreak: "clone",
...inlineBackground("var(--openidea-selected-bg)"),
// Unset (the default `inherit`): the declaration drops and the syntax colours show through.
color: "var(--fg-editor-selection)",
WebkitTextFillColor: "var(--fg-editor-selection)",
@@ -51,6 +47,12 @@ const theme = EditorView.baseTheme({
"&.cm-focused .cm-openidea-selected": {
"--openidea-selected-bg": "var(--editor-selection, var(--bg-editor-selection))",
},
// Leave the 1px frame painted by `inlineFramedModern` visible around selected text inside it.
"@supports (height: 1lh)": {
":is(.cm-openidea-findMatch-current, .cm-lsp-inplace-primary) .cm-openidea-selected": {
backgroundSize: "calc(100% - 2px) calc(min(100%, 1lh) - 2px)",
},
},
});
export const selectionMarks: Extension = [Prec.highest(plugin), theme];
+8
Переглянути файл
@@ -101,6 +101,14 @@ describe("Enter in a string literal", () => {
expect(enter("char c = 'a|';", "java", java())).toBeNull();
});
it("splits a string of a language without a Lezer string node, and not a multi-line one", () => {
const kt = StreamLanguage.define(interpolationParser(kotlin, "Kotlin"));
expect(enter('fun f() {\n val t = "hello|world"\n}', "kotlin", kt)).toBe(
'fun f() {\n val t = "hello" +\n "|world"\n}',
);
expect(enter('val t = """\n a|b\n """', "kotlin", kt)).toBeNull();
});
it("splits after an escaped backslash", () => {
expect(enter('String t = "a\\\\|b";', "java", java())).toBe('String t = "a\\\\" +\n "|b";');
});
+2 -2
Переглянути файл
@@ -23,7 +23,7 @@ import {
import type { SyntaxNode } from "@lezer/common";
import { indentMore } from "@codemirror/commands";
import { visibleColumn } from "./visibleColumn";
import { literalAt } from "./literals";
import { lineLiteralAt, literalAt } from "./literals";
import { SEMICOLON_LANGS, codeEnd, lineCommentToken } from "./editing";
// --- Tab -------------------------------------------------------------------------------
@@ -552,7 +552,7 @@ const PLUS_CONCAT_LANGS = new Set([
function stringLiteralAt(state: EditorState, pos: number): { from: number; to: number } | null {
for (let n: SyntaxNode | null = syntaxTree(state).resolveInner(pos, -1); n; n = n.parent)
if (/^(StringLiteral|String)$/.test(n.name)) return { from: n.from, to: n.to };
const lit = literalAt(state, pos);
const lit = lineLiteralAt(state, pos);
return lit?.kind === "string" ? lit : null;
}
+16 -13
Переглянути файл
@@ -9,6 +9,7 @@ import { EditorView } from "@codemirror/view";
import { BRACKET_COLORS } from "./rainbowBrackets";
import { LINE_INSET } from "./lineInset";
import { GUIDE_COLORS } from "./indentGuides";
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "./inlineBg";
/** How much of its palette colour a rainbow indent guide takes. */
const RAINBOW_GUIDE_STRENGTH = "55%";
@@ -19,10 +20,12 @@ export const findLocals = {
"--editor-search-current": "var(--bg-search-match-current, color-mix(in srgb, var(--warning) 48%, transparent))",
};
const FIND_CURRENT_FRAME = "color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))";
/** Find in file highlights (cm/find.ts), also for viewers with their own theme (diff). */
export const findStyles = {
".cm-openidea-findMatch": {
backgroundColor: "var(--editor-search)",
...inlineBackground("var(--editor-search)"),
color: "var(--fg-search-match, inherit)",
// Its own colour, over the text fill of an identifier highlight around the match.
WebkitTextFillColor: "currentcolor",
@@ -32,13 +35,13 @@ export const findStyles = {
textDecoration: "line-through",
textDecorationColor: "var(--fg-muted)",
},
".cm-openidea-findScope": {
backgroundColor: "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
},
".cm-openidea-findScope": inlineBackground("var(--editor-selection-inactive, var(--bg-editor-selection-inactive))"),
".cm-openidea-findMatch-current": {
backgroundColor: "var(--editor-search-current)",
...inlineFramedFallback("var(--editor-search-current)", FIND_CURRENT_FRAME),
color: "var(--fg-search-match, inherit)",
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
},
"@supports (height: 1lh)": {
".cm-openidea-findMatch-current": inlineFramedModern("var(--editor-search-current)", FIND_CURRENT_FRAME),
},
};
@@ -222,25 +225,25 @@ export const openideaTheme = EditorView.theme({
background: "var(--openidea-line-bg)",
pointerEvents: "none",
},
".cm-selectionMatch": {
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
},
".cm-selectionMatch": inlineBackground(
"var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
),
// IDEA paints these with IDENTIFIER_UNDER_CARET_ATTRIBUTES, except the selection itself.
".cm-selectionMatch:not(.cm-selectionMatch-main)": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
// IDEA's MATCHED_BRACE_ATTRIBUTES (bold in dark schemes only) and MATCHED_TAG_NAME (never bold).
".cm-matchingBracket, &.cm-focused .cm-matchingBracket": {
backgroundColor: "var(--editor-brace)",
...inlineBackground("var(--editor-brace)"),
color: "inherit",
fontWeight: "var(--matched-brace-weight, var(--fw-code-bold, 700))",
borderRadius: "1px",
},
".cm-matchingTag, &.cm-focused .cm-matchingTag": {
backgroundColor: "var(--bg-matched-tag, var(--editor-brace))",
...inlineBackground("var(--bg-matched-tag, var(--editor-brace))"),
fontWeight: "inherit",
},
".cm-nonmatchingBracket, &.cm-focused .cm-nonmatchingBracket": {
color: "var(--danger)",
backgroundColor: "color-mix(in srgb, var(--danger) 14%, transparent)",
...inlineBackground("color-mix(in srgb, var(--danger) 14%, transparent)"),
},
".cm-specialChar": { color: "var(--danger)" },
@@ -363,7 +366,7 @@ export const openideaTheme = EditorView.theme({
...findStyles,
...markWidgetStyles,
// Find in Files preview matches (search/find/parts.tsx)
".cm-openidea-searchResult": { backgroundColor: "var(--bg-search-result)" },
".cm-openidea-searchResult": inlineBackground("var(--bg-search-result)"),
// Overlays
".cm-tooltip": {
+5
Переглянути файл
@@ -64,6 +64,11 @@
content-visibility: hidden;
z-index: -1;
}
/* WebKit leaves a stale selection highlight on a subtree whose rendering was skipped when the selection cleared. */
.keptHidden[data-selection] {
content-visibility: visible;
opacity: 0;
}
.host {
flex: 1;
min-height: 0;
+23 -1
Переглянути файл
@@ -6,7 +6,16 @@ import { useFilePresentations } from "@/ui/filePresentation";
* decorations, middle-click close, Alt+click close others, double-click to
* keep a preview / maximize the editor, context menu) and the active editor.
*/
import { Fragment, useEffect, useMemo, useRef, useState, type FocusEvent, type ReactNode } from "react";
import {
Fragment,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type FocusEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { executeAction } from "@/platform/actions";
@@ -46,6 +55,7 @@ import {
Tabs,
showContextMenu,
registerDropTarget,
useSelectionVisibility,
FILES_DRAG,
type TabItem,
type TabsDnd,
@@ -544,12 +554,24 @@ function keptTabs(tabs: Tab[], mru: string[], kinds: Map<string, EditorKindContr
* its content can't be focused or hit while skipped.
*/
function KindEditor({ tab, shown, kept = false }: { tab: Tab; shown: boolean; kept?: boolean }) {
const ref = useRef<HTMLDivElement>(null);
useSelectionVisibility(ref, kept);
useLayoutEffect(() => {
const el = ref.current;
if (!kept || shown || !el) return;
const sel = el.ownerDocument.getSelection();
if (sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el)) {
el.setAttribute("data-selection", "");
sel.removeAllRanges();
}
}, [kept, shown]);
const kinds = useContributions((s) => s.editorKinds);
const kind = kinds.get(tab.input.kind);
if (!kind) return <EmptyState icon="file" title={tx`No editor for “${tab.input.kind}”`} />;
const Component = kind.component;
return (
<div
ref={ref}
className={clsx(styles.kind, kept && styles.kept, !shown && styles.keptHidden)}
data-editor-focus={shown ? "" : undefined}
tabIndex={-1}
+2
Переглянути файл
@@ -640,6 +640,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
aria-label="Find"
invalid={invalid || none}
multiline
maxRows={3}
onHistory={() => setHistoryMenu("find")}
onKeyDown={(e) => onKeyDown(e, "find")}
className={styles.findInput}
@@ -710,6 +711,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
placeholder="Replace"
aria-label="Replace"
multiline
maxRows={3}
onHistory={() => setHistoryMenu("replace")}
onKeyDown={(e) => onKeyDown(e, "replace")}
toggles={[
+39
Переглянути файл
@@ -95,4 +95,43 @@ describe("keep-alive editor kinds", () => {
expect(shown("k2")).toBe(false);
expect(shown("k6")).toBe(true);
});
it("clears a kept tab's selection on hide while keeping data-selection for one frame so WebKit clears the highlight", () => {
const frames: FrameRequestCallback[] = [];
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => frames.push(cb));
const caf = vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {
frames.length = 0;
});
try {
const tabs = [tab("a", "kept"), tab("b", "plain")];
show(tabs, "a");
render(<EditorAreaView />);
const node = screen.getByTestId("a").firstChild!;
const wrapper = screen.getByTestId("a").parentElement!;
const sel = window.getSelection()!;
sel.setBaseAndExtent(node, 0, node, 1);
act(() => {
document.dispatchEvent(new Event("selectionchange"));
});
expect(wrapper).toHaveAttribute("data-selection");
show(tabs, "b");
expect(shown("a")).toBe(false);
expect(sel.rangeCount).toBe(0);
expect(wrapper).toHaveAttribute("data-selection");
act(() => {
document.dispatchEvent(new Event("selectionchange"));
});
expect(wrapper).toHaveAttribute("data-selection");
act(() => frames.shift()?.(performance.now()));
expect(wrapper).toHaveAttribute("data-selection");
act(() => frames.shift()?.(performance.now()));
expect(wrapper).not.toHaveAttribute("data-selection");
} finally {
raf.mockRestore();
caf.mockRestore();
window.getSelection()?.removeAllRanges();
}
});
});
+63
Переглянути файл
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
import { javascriptLanguage, typescriptLanguage } from "@codemirror/lang-javascript";
import { TreeFragment, type Tree } from "@lezer/common";
import { semanticRanges } from "../index";
import { decoratorRanges } from "./index";
// tsserver's legend (vtsls and typescript-language-server send the same one).
const tokenTypes = ["class", "variable", "function", "member", "property"];
@@ -85,3 +87,64 @@ describe("JavaScript and TypeScript semantic tokens (#4059)", () => {
expect(at(1, "parseInt")).toBe("cm-sem-function cm-sem-builtin");
});
});
describe("decorator names after an edit", () => {
const parser = typescriptLanguage.parser;
const decorated = "@Component({ selector: 'a' })\nexport class Home {\n @Input() title = ''\n}\n\n";
const plain = (count: number) =>
Array.from(
{ length: count },
(_, i) =>
`/** Service ${i}, documented. */\nexport class Service${i} {\n load(id: number) {\n return id\n }\n}\n\n`,
).join("");
/** The decorator names by walking the whole tree: what each edit used to cost. */
function everyDecorator(tree: Tree): Array<[number, number]> {
const out: Array<[number, number]> = [];
tree.iterate({
enter(ref) {
if (ref.name !== "Decorator") return;
let head = ref.node.firstChild?.nextSibling ?? null;
while (head) {
if (head.name === "CallExpression") head = head.firstChild;
else if (head.name === "MemberExpression") {
if (head.lastChild?.name === "PropertyName") out.push([head.lastChild.from, head.lastChild.to]);
head = head.firstChild;
} else {
if (head.name === "VariableName") out.push([head.from, head.to]);
head = null;
}
}
},
});
return out;
}
/** Scans the tree of a file that is `count` services after its decorated classes, then the tree of the same file after one typed letter. */
function scanAfterTyping(count: number) {
const doc = decorated + plain(count) + decorated;
const tree = parser.parse(doc);
decoratorRanges(tree);
const at = doc.indexOf("return", doc.length >> 1);
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
{ fromA: at, toA: at, fromB: at, toB: at + 1 },
]);
const edited = parser.parse(doc.slice(0, at) + "a" + doc.slice(at), fragments);
const probe = { visited: 0 };
const ranges = decoratorRanges(edited, probe);
return { edited, ranges, visited: probe.visited };
}
it("finds the decorators of the whole file", () => {
const { edited, ranges } = scanAfterTyping(50);
expect(ranges.map((r) => [r.from, r.to])).toEqual(everyDecorator(edited));
expect(ranges).toHaveLength(4);
});
it("looks at as many tree nodes in a long file as in a short one", () => {
// The nodes an edit leaves alone were already known to hold no decorator.
const short = scanAfterTyping(100).visited;
const long = scanAfterTyping(1600).visited;
expect(long).toBeLessThan(short * 2);
});
});
+61 -22
Переглянути файл
@@ -4,32 +4,71 @@
* function the server reports; a variable or function without tsserver's `local`
* modifier is a module-level global.
*/
import type { Tree } from "@lezer/common";
import { Tree, TreeBuffer, type NodeSet, type SyntaxNode } from "@lezer/common";
import { registerLanguageSemantics, type LanguageSemantics, type SemanticRange } from "../languages";
/** The names of decorators, left of their arguments: `@A`, `@a.B`, `@A()`, `@a.B<T>()`. */
export function decoratorRanges(tree: Tree): SemanticRange[] {
const decoratorTypes = new WeakMap<NodeSet, number>();
function decoratorType(set: NodeSet): number {
let id = decoratorTypes.get(set);
if (id === undefined) decoratorTypes.set(set, (id = set.types.find((t) => t.name === "Decorator")?.id ?? -1));
return id;
}
/**
* Subtrees without a decorator. An incremental parse keeps most of the old tree's nodes as they are,
* so after an edit only the nodes on the changed path are scanned again, not the whole file.
*/
const decoratorFree = new WeakSet<Tree | TreeBuffer>();
/** Appends the start of every `Decorator` node in `node` (which starts at `offset`) to `out`. */
function findDecorators(node: Tree | TreeBuffer, offset: number, out: number[], probe?: { visited: number }): void {
if (decoratorFree.has(node)) return;
if (probe) probe.visited++;
const before = out.length;
if (node instanceof Tree) {
if (node.type.name === "Decorator") out.push(offset);
for (let i = 0; i < node.children.length; i++)
findDecorators(node.children[i]!, offset + node.positions[i]!, out, probe);
} else {
// [type, from, to, end of children] per node; `from` is relative to the buffer.
const type = decoratorType(node.set);
if (type >= 0)
for (let i = 0; i < node.buffer.length; i += 4)
if (node.buffer[i] === type) out.push(offset + node.buffer[i + 1]!);
}
if (out.length === before) decoratorFree.add(node);
}
/**
* The names of decorators, left of their arguments: `@A`, `@a.B`, `@A()`, `@a.B<T>()`.
* `probe` counts the tree nodes looked at (tests).
*/
export function decoratorRanges(tree: Tree, probe?: { visited: number }): SemanticRange[] {
const starts: number[] = [];
findDecorators(tree, 0, starts, probe);
const out: SemanticRange[] = [];
tree.iterate({
enter(ref) {
if (ref.name !== "Decorator") return;
// The node after `@`.
let head = ref.node.firstChild?.nextSibling ?? null;
while (head) {
if (head.name === "CallExpression") head = head.firstChild;
else if (head.name === "MemberExpression") {
const name = head.lastChild;
if (name?.name === "PropertyName")
out.push({ from: name.from, to: name.to, className: "cm-sem-annotation", source: "syntax" });
head = head.firstChild;
} else {
if (head.name === "VariableName")
out.push({ from: head.from, to: head.to, className: "cm-sem-annotation", source: "syntax" });
head = null;
}
for (const from of starts) {
// The innermost node starting there is the `@` token.
let decorator: SyntaxNode | null = tree.resolve(from, 1);
while (decorator && decorator.name !== "Decorator") decorator = decorator.parent;
if (!decorator) continue;
// The node after `@`.
let head = decorator.firstChild?.nextSibling ?? null;
while (head) {
if (head.name === "CallExpression") head = head.firstChild;
else if (head.name === "MemberExpression") {
const name = head.lastChild;
if (name?.name === "PropertyName")
out.push({ from: name.from, to: name.to, className: "cm-sem-annotation", source: "syntax" });
head = head.firstChild;
} else {
if (head.name === "VariableName")
out.push({ from: head.from, to: head.to, className: "cm-sem-annotation", source: "syntax" });
head = null;
}
},
});
}
}
return out;
}
+11 -6
Переглянути файл
@@ -1,5 +1,6 @@
/** Editor-side styling for LSP features (CodeMirror theme; tokens only). */
import { EditorView } from "@codemirror/view";
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "@/editor/core/cm/inlineBg";
import { RAINBOW_COLORS } from "./semantic";
const tooltipSurface = {
@@ -402,7 +403,8 @@ export const lspTheme = EditorView.theme({
".cm-lsp-occurrence-write, .cm-lsp-occurrence-tail-write": {
"--lsp-occurrence-bg": "var(--bg-identifier-under-caret-write, color-mix(in srgb, var(--danger) 12%, transparent))",
},
".cm-lsp-occurrence": { backgroundColor: "var(--lsp-occurrence-bg)" },
".cm-line.cm-lsp-occurrence": { backgroundColor: "var(--lsp-occurrence-bg)" },
"span.cm-lsp-occurrence": inlineBackground("var(--lsp-occurrence-bg)"),
// Text fill, not `color`: it reaches the syntax and semantic spans nested inside, and with the
// variable unset the declaration drops, so they keep their own colours.
"span.cm-lsp-occurrence, .cm-lsp-occurrence-text": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
@@ -436,18 +438,21 @@ export const lspTheme = EditorView.theme({
borderBottomColor: "var(--bg-popup)",
},
// Chooser highlight (tempHighlight.ts): the expression / occurrences a choice would take.
".cm-lsp-chooser-highlight": { backgroundColor: "var(--bg-text-search-result)" },
".cm-lsp-chooser-removed": { backgroundColor: "var(--diff-deleted)" },
".cm-lsp-chooser-highlight": inlineBackground("var(--bg-text-search-result)"),
".cm-lsp-chooser-removed": inlineBackground("var(--diff-deleted)"),
// --- in-place rename (inplaceRename.ts) ------------------------------------
".cm-lsp-inplace": {
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
"--lsp-inplace-bg": "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
...inlineBackground("var(--lsp-inplace-bg)"),
},
".cm-lsp-inplace-primary": {
outline: "1px solid var(--focus-ring)",
outlineOffset: "-1px",
...inlineFramedFallback("var(--lsp-inplace-bg)", "var(--focus-ring)"),
borderRadius: "2px",
},
"@supports (height: 1lh)": {
".cm-lsp-inplace-primary": inlineFramedModern("var(--lsp-inplace-bg)", "var(--focus-ring)"),
},
".cm-lsp-inplace-hint": {
color: "var(--fg-secondary)",
fontSize: "var(--fs-small)",
+1 -1
Переглянути файл
@@ -1,5 +1,5 @@
/**
* Settings › Agents › Coding Agents: one searchable list of every agent, those this machine can run first
* Agent Setup lists every agent, with those this machine can run first
* (built in, installed from the ACP Registry, or defined in an agent file), then those it
* can install. The selected agent's page holds its actions, the settings its new tasks
* start with, and how it is launched. Launch edits are staged until Apply; installs run in
+2 -3
Переглянути файл
@@ -1,6 +1,5 @@
/**
* Settings › Tools › Agents › Command Permissions: whitelist (auto-approve)
* and blacklist (auto-reject) command patterns evaluated on agent permission requests.
* Command Rules defines the allow and block patterns for agent permission requests.
*/
import { useMemo, useState } from "react";
import { tx } from "@/platform/i18n";
@@ -47,7 +46,7 @@ export function AgentPolicyPage() {
};
return (
<section className={styles.body} aria-label="Command Permissions">
<section className={styles.body} aria-label={tx("Command Rules")}>
<p className={styles.notice}>
<T>
Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
/** Settings › Agents › Coding Agents. */
/** Settings › Agents › Agent Setup. */
import { AgentList } from "./AgentList";
import { tauriCommands, tauriRegistry, type CommandsBackend, type RegistryBackend } from "./registry";
import styles from "./AgentRegistry.module.css";
+2 -1
Переглянути файл
@@ -224,11 +224,12 @@
flex: none;
}
/* Import Sessions from Other Apps: filter above a fixed-height list, so the dialog doesn't grow. */
/* Keep the import list height stable while filtering. */
.chooser {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: var(--space-3) var(--space-4) 0;
}
.chooserList {
height: 312px;
+6 -5
Переглянути файл
@@ -281,8 +281,9 @@ describe("Agents docked view", () => {
]);
});
it("lists Import Sessions from Other Apps in Find Action", () => {
it("lists Import Sessions in Find Action", () => {
const action = taskActions.find((a) => a.id === "agents.importSessions");
expect(action?.title).toBe("Import Sessions…");
expect(action?.hidden).toBeFalsy();
expect(action?.when).toBe("projectOpen");
act(() => void action?.run({} as never));
@@ -502,17 +503,17 @@ describe("Agents pinned and grouped tasks", () => {
expect(rows.some((text) => text.includes("one"))).toBe(true);
});
it("offers the groups, a new one and a way out in Move to Group", () => {
it("offers the groups, a new one and a way out in the Group submenu", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: { two: "g1" }, pinned: [] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Move to Group");
const move = menu.find((item) => "label" in item && item.label === "Group");
expect(move).toBeDefined();
const submenu = (move as { submenu: { label?: string; checked?: boolean }[] }).submenu;
expect(submenu.map((item) => item.label ?? "separator")).toEqual([
"Frontend",
"separator",
"New Group…",
"Remove from Group",
"No Group",
]);
expect(submenu[0]).toMatchObject({ checked: true });
});
@@ -520,7 +521,7 @@ describe("Agents pinned and grouped tasks", () => {
it("moves a pinned task into a group, out of the pinned section", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: {}, pinned: ["two"] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Move to Group") as {
const move = menu.find((item) => "label" in item && item.label === "Group") as {
submenu: { label?: string; run?: () => void }[];
};
act(() => move.submenu.find((item) => item.label === "Frontend")!.run!());
+2 -2
Переглянути файл
@@ -1,4 +1,4 @@
/** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */
/** Pick external sessions and import them as agent tasks. */
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui";
import { useRowHeight } from "@/ui/density";
@@ -160,7 +160,7 @@ function ImportSessionsDialog() {
<Dialog
open
onClose={close}
title="Import Sessions from Other Apps"
title="Import Sessions"
width={560}
footerStart={
<span className={styles.chooserFooter}>
+2 -2
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Per-session MCP picker for the New Task and Session composers: shows inherited IDE, Project,
* Global, and Agent-Native CLI MCP servers, lets the user toggle servers for this session only,
* reset session overrides, or jump to Settings › Agents › External MCP Servers.
* reset session overrides, or jump to Settings › Agents › MCP Connections.
*/
import { useMemo, useState } from "react";
import type { McpExternalSource, McpServer } from "@/bindings";
@@ -110,7 +110,7 @@ export function McpPicker({
}}
triggerAriaLabel={tx("MCP servers")}
popupTitle={tx("Session MCP Servers")}
settingsTitle={tx("External MCP Servers…")}
settingsTitle={tx("MCP Connections…")}
settingsPage={MCP_PAGE}
counts={{ active: resolved.activeCount, total: resolved.totalCount, overrides: resolved.overrideCount }}
search={{ placeholder: tx("Filter MCP servers…"), ariaLabel: tx("Filter MCP servers"), shown: totalRows > 5 }}
+2 -2
Переглянути файл
@@ -1,5 +1,5 @@
/**
* Settings › Agents › External MCP Servers: multi-level MCP management across Global (`settings.toml`
* Settings › Agents › MCP Connections: multi-level MCP management across Global (`settings.toml`
* + Keychain), Project (`.openidea/settings.toml`), and Agent CLI config directories
* (`~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`,
* `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, `.vscode/mcp.json`), with
@@ -535,7 +535,7 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB
<div className={page.page}>
<div className={page.header}>
<h2 className={page.title}>
<T>External MCP Servers</T>
<T>MCP Connections</T>
</h2>
<div className={page.headerActions}>
<Button
+1 -1
Переглянути файл
@@ -1274,7 +1274,7 @@
}
.changesScope {
flex: none;
padding: 6px 10px 2px;
padding: 0 4px;
}
.changesSummary {
flex: none;
+3 -3
Переглянути файл
@@ -32,7 +32,7 @@ function FormWrapper({ children }: { children: ReactNode }) {
return <SettingsFormContext.Provider value={form}>{children}</SettingsFormContext.Provider>;
}
describe("Command Permissions sub-page", () => {
describe("Command Rules sub-page", () => {
it("registers under Agents group in settings", () => {
const dispose = activateSettingsPages();
try {
@@ -40,7 +40,7 @@ describe("Command Permissions sub-page", () => {
const agentsGroup = tree.find((n) => n.title === AGENTS_GROUP);
expect(agentsGroup).toBeDefined();
const policyNode = agentsGroup?.children.find((n) => n.key === POLICY_PAGE);
expect(policyNode?.title).toBe("Command Permissions");
expect(policyNode?.title).toBe("Command Rules");
// A project's settings file can't decide what agents run without asking.
expect(policyNode?.page?.projectScope).not.toBe(true);
} finally {
@@ -56,7 +56,7 @@ describe("Command Permissions sub-page", () => {
</FormWrapper>,
);
const policy = screen.getByRole("region", { name: "Command Permissions" });
const policy = screen.getByRole("region", { name: "Command Rules" });
expect(within(policy).getByText("rm -rf *")).toBeInTheDocument();
fireEvent.change(within(policy).getByRole("textbox", { name: "Allowed command pattern" }), {
+4 -5
Переглянути файл
@@ -313,7 +313,7 @@ export function activate(): () => void {
{
id: "agents.addAgent",
title: "More Agents…",
description: "Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.",
description: "Install, update, or remove agents from the ACP Registry.",
category: "Agents",
icon: "plugin",
keywords: ["agent", "acp", "registry", "install", "update"],
@@ -321,12 +321,11 @@ export function activate(): () => void {
},
{
id: "agents.mcpServers",
title: "External MCP Servers…",
description:
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
title: "MCP Connections…",
description: "Configure the MCP servers that agents can use.",
category: "Agents",
icon: "settings",
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
run: () => void executeAction("file.settings", MCP_PAGE),
},
{
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Shared MCP server model, multi-level inheritance resolution (IDE -> Project -> Global -> Agent CLI),
* and reactive cache for Settings › Agents › External MCP Servers and the Composer MCP picker.
* and reactive cache for Settings › Agents › MCP Connections and the Composer MCP picker.
*/
import { useEffect } from "react";
import { create } from "zustand";
+3 -3
Переглянути файл
@@ -7,15 +7,15 @@ export const HOME_KEY = "agent:new";
export const TOOL_WINDOW = "agents";
/** MIME of a dragged agent task (a tree row or the docked conversation bar): the payload is the task id. */
export const TASK_DRAG = "application/x-openidea-agent-task";
/** Settings › Agents › Coding Agents: the agents this machine runs. */
/** Settings › Agents › Agent Setup. */
export const REGISTRY_PAGE = "agents.list";
/** The Settings folder holding the agent pages. */
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
/** Settings › Agents › MCP Connections. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Command Permissions. */
/** Settings › Agents › Command Rules. */
export const POLICY_PAGE = "agents.policy";
export const sessionKey = (task: string) => `agent:${task}`;
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ import type { AgentProvider } from "@/bindings";
import type { tx as Tx } from "@/platform/i18n";
import type { SelectOption } from "@/ui";
/** Picker entry that opens Settings › Tools › Agents instead of choosing an agent. */
/** Picker entry that opens Settings › Agents › Agent Setup. */
export const ADD_AGENT = "__addAgent__";
/**
+16 -16
Переглянути файл
@@ -4,14 +4,13 @@ import { repositoryPath } from "@/features/vcs/repositoryPaths";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { basename, dirname, relativeDir } from "@/platform/project";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tree } from "@/ui";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tabs, Tree } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChangesResizer } from "../ChangesResizer";
import styles from "../Session.module.css";
import { setChangesOptions, type ChangesScope } from "../changesOptions";
import { SegmentedControl } from "../ConfigPickers";
import { formatSentAt } from "../conversation";
import { branchLabel } from "../model";
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
@@ -386,20 +385,21 @@ export function ChangesPane({
)}
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
</div>
<div className={styles.changesScope}>
<SegmentedControl
ariaLabel={tx("Changes to show")}
options={[
{ value: "task", label: tx("Whole Task") },
{ value: "turn", label: tx("Last Turn") },
]}
value={scope}
onChange={(value) => {
setChangesOptions({ scope: value === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
/>
</div>
<Tabs
variant="compact"
className={styles.changesScope}
aria-label="Changes to show"
activeId={scope}
onSelect={(id) => {
if (id === scope) return;
setChangesOptions({ scope: id === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
items={[
{ id: "task", label: "Whole Task" },
{ id: "turn", label: "Last Turn" },
]}
/>
{(scope === "turn" || grouped || head || task.base) && (
<div className={styles.changesSummary}>
{scope === "turn" ? (
+4 -33
Переглянути файл
@@ -11,6 +11,7 @@ import {
showContextMenu,
Spinner,
useSelectionBoundary,
useSelectionVisibility,
} from "@/ui";
import { useEditorShown } from "@/workbench/contributions";
import clsx from "clsx";
@@ -144,39 +145,9 @@ function useOffscreenRows(
resize.disconnect();
};
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
// WebKit never clears the selection highlight of a row that skips rendering: once the
// selection moves, rows it covered off screen still show it when scrolled back. While the
// stream holds a selection every row renders (`data-selection`), and keeps rendering until
// the frame after it goes, when WebKit applies the change.
useEffect(() => {
const el = ref.current;
if (!el || !enabled || !visible) return;
let frame = 0;
const selected = () => {
const sel = window.getSelection();
return !!sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el);
};
const update = () => {
cancelAnimationFrame(frame);
if (selected()) {
el.setAttribute("data-selection", "");
return;
}
if (!el.hasAttribute("data-selection")) return;
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
if (!selected()) el.removeAttribute("data-selection");
});
});
};
update();
document.addEventListener("selectionchange", update);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("selectionchange", update);
el.removeAttribute("data-selection");
};
}, [ref, visible, enabled]);
// Keep independent of `visible`: when a kept-alive tab hides, `data-selection` must stay until
// the selection leaves and WebKit clears off-screen rows' highlights before skipping again.
useSelectionVisibility(ref, enabled);
}
interface StreamProps {
+3 -3
Переглянути файл
@@ -2529,7 +2529,7 @@ describe("import sessions dialog", () => {
backend.external = sessions;
open();
await listed("Login fix");
expect(screen.getByRole("dialog", { name: "Import Sessions from Other Apps" })).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "Import Sessions" })).toBeInTheDocument();
});
it("imports the selected session and opens it", async () => {
@@ -3046,7 +3046,7 @@ describe("last turn changes", () => {
const pane = await screen.findByRole("complementary", { name: "Changes" });
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Last Turn" }));
fireEvent.click(within(pane).getByRole("tab", { name: "Last Turn" }));
await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull());
expect(within(pane).getByText("b.ts")).toBeInTheDocument();
expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument();
@@ -3059,7 +3059,7 @@ describe("last turn changes", () => {
backend.turnChanges = [];
fireEvent.click(within(pane).getByRole("button", { name: "Refresh" }));
expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Whole Task" }));
fireEvent.click(within(pane).getByRole("tab", { name: "Whole Task" }));
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
});
});
+6 -7
Переглянути файл
@@ -2,24 +2,23 @@ import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
title: "Agent Setup",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
keywords: ["agent", "acp", "registry", "install", "update", "Coding Agents"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
title: "MCP Connections",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
@@ -32,10 +31,10 @@ export function activateSettingsPages(): () => void {
},
{
id: POLICY_PAGE,
title: "Command Permissions",
title: "Command Rules",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "Command Permissions", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
+1 -1
Переглянути файл
@@ -136,7 +136,7 @@ interface AgentsState {
external: ExternalSession[];
/** Why the external sessions could not be listed. */
externalError: string | null;
/** The Import Sessions from Other Apps dialog is open. */
/** The Import Sessions dialog is open. */
importOpen: boolean;
/** External sessions being imported (`provider:sessionId`), so none is imported twice. */
importing: ReadonlySet<string>;
+13 -6
Переглянути файл
@@ -1,6 +1,6 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { t, tx } from "@/platform/i18n";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
@@ -165,7 +165,7 @@ function arrangeMenu(tasks: AgentTask[], ids: string[]): MenuItem[] {
{
kind: "item",
id: "move-to-group",
label: "Move to Group",
label: "Group",
icon: "folder",
submenu: groupSubmenu(
ids,
@@ -194,7 +194,7 @@ function groupSubmenu(ids: string[], groups: OrganizeGroup[], current: Array<str
{
kind: "item",
id: "group:none",
label: "Remove from Group",
label: "No Group",
run: () => moveTasksToGroup(ids, null),
},
] satisfies MenuItem[])
@@ -213,11 +213,11 @@ export function groupMenu(group: OrganizeGroup): MenuItem[] {
export const taskActions: Action[] = [
{
id: "agents.importSessions",
title: "Import Sessions from Other Apps…",
title: "Import Sessions…",
category: "Agents",
icon: "download",
when: "projectOpen",
keywords: ["import", "claude", "codex", "history", "transcript"],
keywords: ["import", "other apps", "claude", "codex", "history", "transcript"],
run: showImportSessions,
},
{
@@ -398,7 +398,14 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
...(!auxiliaryWindow()
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
? ([
{
kind: "action",
action: "agents.moveToNewWindow",
label: t("app.window.askNew"),
arg: task.id,
},
] satisfies MenuItem[])
: []),
...(hasTaskTerminal(task, projectRoot)
? ([
+78
Переглянути файл
@@ -0,0 +1,78 @@
import { useEffect, useRef } from "react";
import { tx, txPart } from "@/platform/i18n";
import { lockDragCursor } from "@/ui/dragCursor";
import styles from "./Coverage.module.css";
export function ColumnDivider({
title,
width,
min,
max,
onResize,
onReset,
}: {
title: string;
width: number;
min: number;
max: number;
onResize: (width: number) => void;
onReset: () => void;
}) {
const drag = useRef<{ x: number; width: number; pointerId: number; unlock: () => void } | null>(null);
const stop = () => {
drag.current?.unlock();
drag.current = null;
};
useEffect(() => stop, []);
const resize = (next: number) => {
const fitted = Math.round(Math.max(min, Math.min(max, next)));
if (fitted !== width) onResize(fitted);
};
return (
<span
className={styles.divider}
role="separator"
aria-orientation="vertical"
aria-label={tx`Resize ${txPart(title)} column`}
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={width}
tabIndex={0}
onPointerDown={(event) => {
if (event.button !== 0 || drag.current) return;
event.currentTarget.setPointerCapture(event.pointerId);
drag.current = { x: event.clientX, width, pointerId: event.pointerId, unlock: lockDragCursor("col-resize") };
}}
onPointerMove={(event) => {
const start = drag.current;
if (start?.pointerId === event.pointerId) resize(start.width + start.x - event.clientX);
}}
onLostPointerCapture={stop}
onDoubleClick={onReset}
onKeyDown={(event) => {
let next: number;
switch (event.key) {
case "ArrowLeft":
next = width + 10;
break;
case "ArrowRight":
next = width - 10;
break;
case "Home":
next = min;
break;
case "End":
next = max;
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
resize(next);
}}
/>
);
}
+39 -12
Переглянути файл
@@ -1,6 +1,6 @@
.view {
--coverage-metrics: 2;
--coverage-metric-width: min(29cqi, 128px);
--coverage-tracks: minmax(0, 1fr) var(--coverage-lines-width) var(--coverage-branches-width);
--coverage-column-gap: var(--space-2);
container-type: inline-size;
height: 100%;
@@ -10,6 +10,7 @@
}
.noBranches {
--coverage-metrics: 1;
--coverage-tracks: minmax(0, 1fr) var(--coverage-lines-width);
}
.tabs {
min-width: 0;
@@ -25,7 +26,7 @@
.header,
.row {
display: grid;
grid-template-columns: minmax(0, 1fr) repeat(var(--coverage-metrics), var(--coverage-metric-width));
grid-template-columns: var(--coverage-tracks);
align-items: center;
column-gap: var(--coverage-column-gap);
font-size: var(--fs-ui);
@@ -44,9 +45,16 @@
.header::-webkit-scrollbar {
width: 10px;
}
.heading {
position: relative;
min-width: 0;
height: 100%;
}
.headerCell {
display: inline-flex;
display: flex;
align-items: center;
width: 100%;
height: 100%;
gap: var(--space-0-5);
min-width: 0;
padding: 0;
@@ -63,13 +71,33 @@
.headerCell svg {
flex: none;
}
.divider {
position: absolute;
inset-block: 0;
inset-inline-start: calc(-1 * var(--coverage-column-gap));
width: var(--coverage-column-gap);
cursor: col-resize;
touch-action: none;
}
.divider::after {
position: absolute;
inset: var(--space-1) 50% var(--space-1) auto;
width: 1px;
background: var(--border);
content: "";
}
.divider:hover::after,
.divider:focus-visible::after,
.divider:active::after {
background: var(--accent);
}
.tree {
flex: 1;
min-height: 0;
/* Keep the chevron and icon in the name column at deeper levels. */
--coverage-max-row-inset: max(
4px,
calc(100% - var(--coverage-metrics) * (var(--coverage-metric-width) + var(--coverage-column-gap)) - 72px)
calc(100% - var(--coverage-stats-width) - var(--coverage-metrics) * var(--coverage-column-gap) - 72px)
);
}
.row {
@@ -99,16 +127,15 @@
@container (width < 360px) {
.header,
.tree {
--coverage-metric-width: min(23cqi, 65px);
--coverage-column-gap: var(--space-1);
}
.count {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}
}
.compactCount {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}
.link {
padding: 0;
+51 -18
Переглянути файл
@@ -1,11 +1,13 @@
/** Coverage tool window: one tab per recent suite, a sortable tree of directories and files. */
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState, type CSSProperties } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { EmptyState, Icon, IconButton, Tabs, Tree, fileIconName, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { ColumnDivider } from "./ColumnDivider";
import { coverageColumns, readCoverageWidths, saveCoverageWidths } from "./columns";
import { coverageTree, formatPercent, sortTree, type CoverageNode, type SortKey } from "./model";
import { activeSuite, closeSuite, selectSuite, setCoverageVisible, useCoverage } from "./store";
import styles from "./Coverage.module.css";
@@ -50,13 +52,13 @@ export function CoverageHeaderActions() {
);
}
function Metric({ covered, total }: { covered: number; total: number }) {
function Metric({ covered, total, compact }: { covered: number; total: number; compact: boolean }) {
const value = formatPercent(covered, total);
const [percentage, count] = value.split(" ", 2);
return (
<span className={styles.value} title={value}>
{percentage}
{count && <span className={styles.count}> {count}</span>}
{count && <span className={compact ? styles.compactCount : undefined}> {count}</span>}
</span>
);
}
@@ -74,6 +76,16 @@ export function CoverageView() {
const root = useProject((s) => s.project?.root ?? "");
const [sort, setSort] = useState<{ key: SortKey; ascending: boolean }>({ key: "name", ascending: true });
const [expanded, setExpanded] = useState<Set<string> | null>(null);
const [pane, setPane] = useState<HTMLDivElement | null>(null);
const [paneWidth, setPaneWidth] = useState(0);
const [preferred, setPreferred] = useState(readCoverageWidths);
useEffect(() => {
if (!pane) return;
const observer = new ResizeObserver(() => setPaneWidth(pane.clientWidth));
observer.observe(pane);
return () => observer.disconnect();
}, [pane]);
useEffect(() => saveCoverageWidths(preferred), [preferred]);
const roots = useMemo(
() => (suite ? sortTree(coverageTree(suite.data, root), sort.key, sort.ascending) : []),
@@ -103,11 +115,21 @@ export function CoverageView() {
}
const branches = suite.data.hasBranches;
const columns = branches ? COLUMNS : COLUMNS.slice(0, 2);
const { min, budget, widths } = coverageColumns(paneWidth, branches, preferred);
const statsWidth = widths.lines + widths.branches;
const columnStyle = {
"--coverage-lines-width": `${widths.lines}px`,
"--coverage-branches-width": `${widths.branches}px`,
"--coverage-stats-width": `${statsWidth}px`,
} as CSSProperties;
const toggleSort = (key: SortKey) =>
setSort((s) => (s.key === key ? { key, ascending: !s.ascending } : { key, ascending: key === "name" }));
const resizeLines = (lines: number) =>
setPreferred((old) => ({ ...old, lines, ...(branches && { branches: widths.branches }) }));
const resizeBranches = (width: number) => setPreferred({ lines: statsWidth - width, branches: width });
return (
<div className={clsx(styles.view, !branches && styles.noBranches)}>
<div ref={setPane} className={clsx(styles.view, !branches && styles.noBranches)} style={columnStyle}>
{!visible && (
<div className={styles.banner}>
<T>Coverage is hidden in editors and the project view.</T>
@@ -115,18 +137,29 @@ export function CoverageView() {
)}
<div className={styles.header} role="row">
{columns.map((c) => (
<button
key={c.key}
type="button"
role="columnheader"
aria-sort={sort.key === c.key ? (sort.ascending ? "ascending" : "descending") : "none"}
className={styles.headerCell}
title={tx(c.label)}
onClick={() => toggleSort(c.key)}
>
<span className={styles.label}>{tx(c.label)}</span>
{sort.key === c.key && <Icon name={sort.ascending ? "chevron-up" : "chevron-down"} size={12} />}
</button>
<div className={styles.heading} key={c.key}>
<button
type="button"
role="columnheader"
aria-sort={sort.key === c.key ? (sort.ascending ? "ascending" : "descending") : "none"}
className={styles.headerCell}
title={tx(c.label)}
onClick={() => toggleSort(c.key)}
>
<span className={styles.label}>{tx(c.label)}</span>
{sort.key === c.key && <Icon name={sort.ascending ? "chevron-up" : "chevron-down"} size={12} />}
</button>
{c.key !== "name" && paneWidth > 0 && (
<ColumnDivider
title={c.label}
width={widths[c.key]}
min={min}
max={c.key === "lines" ? budget - widths.branches : statsWidth - min}
onResize={c.key === "lines" ? resizeLines : resizeBranches}
onReset={() => setPreferred(branches ? {} : { branches: preferred.branches })}
/>
)}
</div>
))}
</div>
<Tree<CoverageNode>
@@ -152,8 +185,8 @@ export function CoverageView() {
{n.name}
</span>
</span>
<Metric covered={n.linesCovered} total={n.linesTotal} />
{branches && <Metric covered={n.branchesCovered} total={n.branchesTotal} />}
<Metric covered={n.linesCovered} total={n.linesTotal} compact={widths.lines < 92} />
{branches && <Metric covered={n.branchesCovered} total={n.branchesTotal} compact={widths.branches < 92} />}
</span>
)}
empty={<EmptyState title="The report covers no files" />}
+37
Переглянути файл
@@ -0,0 +1,37 @@
type PreferredWidths = Partial<Record<"lines" | "branches", number>>;
const KEY = "openidea.coverage.columns";
export function readCoverageWidths(): PreferredWidths {
try {
const widths = JSON.parse(localStorage.getItem(KEY) ?? "null");
const valid = (n: unknown) => (typeof n === "number" && Number.isFinite(n) && n > 0 ? n : undefined);
return { lines: valid(widths?.lines), branches: valid(widths?.branches) };
} catch {
return {};
}
}
export function saveCoverageWidths(widths: PreferredWidths) {
try {
localStorage.setItem(KEY, JSON.stringify(widths));
} catch {
/* Storage may be unavailable. */
}
}
export function coverageColumns(pane: number, hasBranches: boolean, preferred: PreferredWidths) {
const min = Math.min(52, Math.floor(pane / 5));
const count = hasBranches ? 2 : 1;
// Reserve space for the tree label, its icons and indentation, and the table gutters.
const budget = Math.max(count * min, pane - 132);
const auto = Math.round(pane < 360 ? Math.min(pane * 0.23, 65) : Math.min(pane * 0.29, 128));
const lines = Math.min(budget, Math.max(min, preferred.lines ?? auto));
const branches = hasBranches ? Math.min(budget, Math.max(min, preferred.branches ?? auto)) : 0;
if (lines + branches <= budget) return { min, budget, widths: { lines, branches } };
// Fit saved widths proportionally on a smaller dock without changing the saved layout.
const room = budget - min * count;
const fittedLines = min + Math.round(((lines - min) / (lines + branches - min * count)) * room);
return { min, budget, widths: { lines: fittedLines, branches: budget - fittedLines } };
}
+16 -3
Переглянути файл
@@ -14,7 +14,7 @@
align-items: center;
gap: var(--space-1);
height: var(--h-row);
padding: 0 4px 0 12px;
padding: 0 var(--space-1) 0 var(--space-3);
border-bottom: 1px solid var(--border);
}
@@ -26,7 +26,7 @@
white-space: nowrap;
color: var(--fg-strong);
font-size: var(--fs-ui);
font-family: var(--font-mono);
font-family: var(--font-ui);
}
.note,
@@ -72,11 +72,19 @@
font-size: var(--fs-ui);
}
.node {
flex: 1;
}
.name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-strong);
}
.equals {
flex: none;
white-space: pre;
color: var(--fg-subtle);
}
@@ -90,6 +98,11 @@
font-family: var(--font-mono);
}
.equals + .value {
/* Keep a preview readable beside long field names, even on indented rows. */
min-width: min(14ch, 45%);
}
.group {
color: var(--fg-muted);
}
@@ -101,7 +114,7 @@
.rowButton {
flex: none;
margin-left: 8px;
margin-inline-start: var(--space-2);
opacity: 0;
}
/* Outranks `.iconButton:disabled`, which would show it on every row of an outdated list. */
+12 -4
Переглянути файл
@@ -43,7 +43,9 @@ export function InstancesPane({ session }: { session: DebugSession }) {
return (
<section className={styles.pane} aria-label={title}>
<div className={styles.header}>
<span className={styles.title}>{title}</span>
<span className={styles.title} title={title}>
{title}
</span>
<IconButton
icon="edit-source"
action="debug.memory.jumpToSource"
@@ -206,16 +208,21 @@ function NodeRow({
onRetry: (r: Retry) => void;
}) {
switch (node.kind) {
case "value":
case "value": {
const value = labelOf(node);
return (
<span className={styles.node}>
{node.name != null && (
<>
<span className={styles.name}>{node.name}</span>
<span className={styles.name} title={node.name}>
{node.name}
</span>
<span className={styles.equals}> = </span>
</>
)}
<span className={styles.value}>{labelOf(node)}</span>
<span className={styles.value} title={value}>
{value}
</span>
{node.ref && (
<IconButton
icon="hierarchy"
@@ -229,6 +236,7 @@ function NodeRow({
)}
</span>
);
}
case "referrers":
return (
<span className={styles.group}>
+44 -13
Переглянути файл
@@ -31,9 +31,6 @@
.bold {
font-weight: 600;
}
.flex {
flex: 1;
}
.ellipsis {
min-width: 0;
overflow: hidden;
@@ -440,29 +437,49 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
width: var(--submit-width);
min-width: 320px;
height: var(--submit-height);
min-height: 160px;
padding: 12px;
overflow: hidden;
resize: both;
width: 500px;
max-width: calc(100vw - 12px);
height: 200px;
max-height: calc(100vh - 12px);
padding: var(--space-3);
overflow: auto;
}
.submitHeader {
display: flex;
flex: none;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-1);
}
.submitHeading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
align-self: center;
gap: var(--space-0-5) var(--space-2);
min-width: 0;
overflow-wrap: anywhere;
}
.submitCount {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.submitHeaderActions {
display: flex;
flex: none;
align-items: center;
gap: 5px;
gap: var(--space-1);
}
.submitEditor {
flex: 1;
min-height: 40px;
padding: 4px 6px;
padding: var(--space-1) var(--space-2);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--bg-input);
color: var(--fg);
font: inherit;
line-height: var(--lh-code);
resize: none;
outline: none;
}
@@ -470,12 +487,26 @@
border-color: var(--focus-ring);
}
.submitError {
flex: none;
flex: 0 1 auto;
min-height: 0;
max-height: 35%;
overflow: auto;
overflow-wrap: anywhere;
color: var(--danger);
}
.submitButtons {
display: flex;
flex: none;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
}
.submitButtons > button {
max-width: 100%;
height: auto;
min-height: var(--h-button);
padding-block: var(--space-1);
line-height: 1.2;
white-space: normal;
overflow-wrap: anywhere;
}
+40 -28
Переглянути файл
@@ -5,9 +5,11 @@
* Request Changes (not for the author) and Comment. Shown above the button that opened
* it, or centred in the window. 500×200, resizable.
*/
import { useEffect, useState, type CSSProperties } from "react";
import { useEffect, useState } from "react";
import { Button, IconButton, Popup, Spinner, T } from "@/ui";
import { resolveMonoFont } from "@/platform/fonts";
import { useTx, tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { ask } from "@/workbench/messages";
import { errorMessage } from "../api/client";
import type { GHPullRequestReviewEvent } from "../api/types";
@@ -25,26 +27,25 @@ export function showSubmitReview(number: number, anchor?: Element | null): Promi
// The details and the pending review are needed for the buttons and the header.
void loadPullRequestData(number, "details").catch(() => undefined);
void loadPullRequestData(number, "pendingReview").catch(() => undefined);
const at = anchor?.isConnected
? anchor
: { x: Math.round(window.innerWidth / 2) - 250, y: Math.round(window.innerHeight / 3) };
return openDialog<true>((done) => (
<SubmitReview number={number} draftKey={draftKey} anchor={at} onClose={() => done(null)} />
<SubmitReview
number={number}
draftKey={draftKey}
anchor={anchor?.isConnected ? anchor : "center"}
onClose={() => done(null)}
/>
));
}
function SubmitReview(props: {
number: number;
draftKey: string;
anchor: Element | { x: number; y: number };
onClose: () => void;
}) {
const { number, draftKey, onClose } = props;
function SubmitReview(props: { number: number; draftKey: string; anchor: Element | "center"; onClose: () => void }) {
const { number, draftKey, anchor, onClose } = props;
const t = useTx();
const details = usePullRequestData(number, "details").value;
const pending = usePullRequestData(number, "pendingReview").value;
const text = useReviewText((s) => s.text[draftKey] ?? "");
const activeDraftKey = useGhRepository((s) => reviewDraftKey(s.connection, number));
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -94,12 +95,11 @@ function SubmitReview(props: {
setBusy(false);
}
};
const anchored = "getBoundingClientRect" in props.anchor;
return (
<Popup
open
anchor={props.anchor}
placement={anchored ? "top-start" : "bottom-start"}
anchor={anchor}
placement="top-start"
onClose={(reason) => {
// A click outside does not drop a review while it is being sent.
if (reason !== "outside" || !busy) onClose();
@@ -107,26 +107,38 @@ function SubmitReview(props: {
role="dialog"
aria-label={t("Submit Review")}
className={styles.submitPopup}
style={{ "--submit-width": "500px", "--submit-height": "200px" } as CSSProperties}
resizable="both"
minWidth={260}
minHeight={160}
>
<div className={styles.submitHeader}>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span>{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}</span>
)}
<span className={styles.flex} />
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
<div className={styles.submitHeading}>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span className={styles.submitCount}>
{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}
</span>
)}
</div>
<div className={styles.submitHeaderActions}>
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
</div>
<textarea
data-autofocus
className={styles.submitEditor}
placeholder={t("Review comment")}
aria-label={t("Review comment")}
style={{
fontFamily: family,
fontSize: size,
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={text}
onChange={(e) => {
setError(null);
@@ -134,7 +146,7 @@ function SubmitReview(props: {
}}
/>
{error && (
<div className={styles.submitError}>
<div className={styles.submitError} role="alert">
<T>Failed to submit review</T>
<div className={styles.secondary}>{error}</div>
</div>
+15 -5
Переглянути файл
@@ -1,18 +1,28 @@
.highlight,
.search,
.added,
.modified,
.removed {
background-color: var(--plugin-mark-bg);
background: linear-gradient(var(--plugin-mark-bg), var(--plugin-mark-bg)) center / 100% 1lh no-repeat;
-webkit-box-decoration-break: clone;
box-decoration-break: clone;
}
.highlight {
background: var(--accent-soft);
--plugin-mark-bg: var(--accent-soft);
}
.search {
background: var(--bg-search-match);
--plugin-mark-bg: var(--bg-search-match);
color: var(--fg-search-match);
}
.added {
background: color-mix(in srgb, var(--vcs-added) 18%, transparent);
--plugin-mark-bg: color-mix(in srgb, var(--vcs-added) 18%, transparent);
}
.modified {
background: color-mix(in srgb, var(--vcs-modified) 18%, transparent);
--plugin-mark-bg: color-mix(in srgb, var(--vcs-modified) 18%, transparent);
}
.removed {
background: color-mix(in srgb, var(--vcs-deleted) 18%, transparent);
--plugin-mark-bg: color-mix(in srgb, var(--vcs-deleted) 18%, transparent);
}
.warning {
text-decoration: underline wavy var(--warning);
+11
Переглянути файл
@@ -115,6 +115,17 @@ describe("project view context menu", () => {
}
});
it("passes the selected Project view directory to Commit…", () => {
const items = contextMenuItems([node("/p/module", true)]);
const git = items.find((item) => item.kind !== "separator" && item.kind !== "header" && item.label === "Git");
const commit =
git && "submenu" in git
? git.submenu?.find((item) => item.kind !== "separator" && item.kind !== "header" && item.label === "Commit…")
: undefined;
expect(commit).toMatchObject({ kind: "action", action: "vcs.commit", arg: "/p/module" });
});
it("lists contributed links in Copy Path/Reference…", () => {
disposers.push(
registerMenuGroup({
+1 -1
Переглянути файл
@@ -378,7 +378,7 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
"git",
"Git",
[
act("vcs.commit", undefined, dirs || nodes.length > 1 ? "Commit…" : "Commit File…"),
act("vcs.commit", arg, dirs || nodes.length > 1 ? "Commit…" : "Commit File…"),
act("vcs.addToVcs", arg, "Add"),
nonRoot.length === nodes.length &&
nodes.length > 0 &&
+44 -1
Переглянути файл
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc";
import {
FindSession,
@@ -149,6 +149,49 @@ describe("FindSession", () => {
expect(last()).toMatchObject({ status: "done", stale: false, files: [], matchCount: 0 });
});
describe("while results stream in", () => {
afterEach(() => vi.useRealTimers());
it("publishes a burst of files as a few updates, showing the first at once and the last without waiting for done", async () => {
vi.useFakeTimers();
const { session, running, states, last } = setup();
void session.search(q("foo"));
await vi.advanceTimersByTimeAsync(0);
const before = states.length;
// 1000 files, one per millisecond: 1s of streaming.
running[0]!.onFile(file("f0.kt", [1]));
await vi.advanceTimersByTimeAsync(0);
expect(last().files).toHaveLength(1);
for (let i = 1; i < 1000; i++) {
running[0]!.onFile(file(`f${i}.kt`, [1]));
await vi.advanceTimersByTimeAsync(1);
}
await vi.advanceTimersByTimeAsync(100);
expect(last().files).toHaveLength(1000);
expect(last().matchCount).toBe(1000);
expect(last().status).toBe("searching");
// One per 50 ms plus the first: far below the one-per-file of an unbatched stream.
expect(states.length - before).toBeLessThanOrEqual(30);
running[0]!.finish(summary(1000));
await vi.advanceTimersByTimeAsync(0);
expect(last().status).toBe("done");
});
it("does not publish a pending update after dispose", async () => {
vi.useFakeTimers();
const { session, running, states } = setup();
void session.search(q("foo"));
await vi.advanceTimersByTimeAsync(0);
running[0]!.onFile(file("a.kt", [1]));
await vi.advanceTimersByTimeAsync(0);
running[0]!.onFile(file("b.kt", [1]));
session.dispose();
const seen = states.length;
await vi.advanceTimersByTimeAsync(200);
expect(states.length).toBe(seen);
});
});
it("reports invalid patterns without starting a search", async () => {
const { session, deps, last } = setup();
await session.search(q("(", { isRegex: true }));
+188
Переглянути файл
@@ -0,0 +1,188 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc";
import { FindToolWindow } from "../find/FindToolWindow";
import { FindTreeBuilder, buildFindTree } from "../find/findTree";
import type { FindDeps } from "../find/session";
import { disposeFindWindow, openInFindWindow, useFindViewOptions } from "../find/windowStore";
const query: SearchQuery = {
pattern: "needle",
isRegex: false,
caseSensitive: false,
wholeWord: false,
include: [],
exclude: [],
scope: { kind: "project" },
maxMatches: 0,
};
/** A deterministic pseudo-random order, so batches interleave paths and directories. */
const shuffled = <T,>(items: readonly T[], seed = 7): T[] => {
const out = [...items];
let s = seed;
for (let i = out.length - 1; i > 0; i--) {
s = (s * 1103515245 + 12345) & 0x7fffffff;
const j = s % (i + 1);
[out[i], out[j]] = [out[j]!, out[i]!];
}
return out;
};
const file = (i: number): FileMatches => {
const dir = i % 9 === 0 ? "" : `src/pkg${i % 13}/sub${i % 4}`;
const relPath = `${dir ? `${dir}/` : ""}${i % 5 === 0 ? "File" : "file"}${i}.ts`;
return {
path: `/proj/${relPath}`,
relPath,
matches: [
{ line: 1, text: ` needle ${i}`, ranges: [[2, 8]], textOffset: 0 },
{
line: 4 + (i % 3),
text: "needle needle",
ranges: [
[0, 6],
[7, 13],
],
textOffset: 0,
},
],
};
};
afterEach(disposeFindWindow);
describe("FindTreeBuilder", () => {
const files = shuffled(Array.from({ length: 300 }, (_, i) => file(i)));
/** The files in their final order, by the same rule the view documents: sorted by path. */
const sortedRels = (list: readonly FileMatches[]) =>
[...list].map((f) => f.relPath).sort((a, b) => a.localeCompare(b));
for (const group of [false, true]) {
it(`builds the same tree incrementally as from scratch (${group ? "grouped by directory" : "flat"})`, () => {
const builder = new FindTreeBuilder(group);
let roots = builder.sync([]);
// Uneven batch sizes, including a batch that changes nothing.
for (const end of [1, 2, 2, 30, 31, 100, 299, 300]) roots = builder.sync(files.slice(0, end));
expect(roots).toEqual(buildFindTree(files, group));
expect(builder.sync(files)).toBe(roots);
if (group) {
expect(roots.map((n) => (n.kind === "dir" ? n.label : ""))).toEqual(
[...new Set(files.map((f) => f.relPath.split("/").slice(0, -1).join("/") || "/"))].sort((a, b) =>
a.localeCompare(b),
),
);
expect(roots.reduce((n, r) => n + (r.kind === "dir" ? r.count : 0), 0)).toBe(300 * 3);
} else {
expect(roots.map((n) => (n.kind === "file" ? n.path : ""))).toEqual(
sortedRels(files).map((rel) => `/proj/${rel}`),
);
}
});
}
it("keeps the lookup tables in step with the roots", () => {
const builder = new FindTreeBuilder(true);
builder.sync(files.slice(0, 120));
const roots = builder.sync(files);
const fresh = new FindTreeBuilder(true);
fresh.sync(files);
expect([...builder.byKey.keys()].sort()).toEqual([...fresh.byKey.keys()].sort());
expect([...builder.expandable].sort()).toEqual([...fresh.expandable].sort());
expect(builder.filesByPath.size).toBe(300);
for (const root of roots) expect(builder.byKey.get(root.key)).toBe(root);
});
it("replaces only the directories that gained files", () => {
const builder = new FindTreeBuilder(true);
const list = [file(1), file(2), file(3)];
const before = builder.sync(list);
const after = builder.sync([...list, file(53)]); // same dir as file(1)
const byLabel = (roots: typeof before) => new Map(roots.map((n) => [n.kind === "dir" ? n.label : "", n]));
const [a, b] = [byLabel(before), byLabel(after)];
expect(b.get("src/pkg1/sub1")).not.toBe(a.get("src/pkg1/sub1"));
expect(b.get("src/pkg1/sub1")).toMatchObject({ count: 6 });
expect(b.get("src/pkg2/sub2")).toBe(a.get("src/pkg2/sub2"));
expect(b.get("src/pkg3/sub3")).toBe(a.get("src/pkg3/sub3"));
});
it("rebuilds when the list is not an extension of the previous one", () => {
const builder = new FindTreeBuilder(false);
builder.sync(files.slice(0, 50));
const other = files.slice(100, 120);
expect(builder.sync(other)).toEqual(buildFindTree(other, false));
expect(builder.sync([])).toEqual([]);
expect(builder.byKey.size).toBe(0);
const swapped = [...files.slice(0, 5)];
builder.sync(swapped);
swapped[4] = files[40]!;
expect(builder.sync(swapped)).toEqual(buildFindTree(swapped, false));
});
});
describe("streaming results into the Find tool window", () => {
const F = 2000;
const BATCHES = 40;
beforeEach(() => {
vi.useFakeTimers();
useFindViewOptions.setState({ preview: false, groupByDirectory: false });
});
afterEach(() => vi.useRealTimers());
/** Files whose `matches` list counts how often a consumer reads it, i.e. how often a file is processed. */
const counted = (reads: { n: number }) =>
Array.from({ length: F }, (_, i) => {
const { matches, ...rest } = file(i);
return Object.defineProperty({ ...rest } as FileMatches, "matches", {
get() {
reads.n++;
return matches;
},
enumerable: true,
});
});
it("processes each streamed file a bounded number of times, not once per update", async () => {
const reads = { n: 0 };
const all = counted(reads);
let push!: (f: FileMatches) => void;
let finish!: (s: SearchSummary) => void;
const deps: FindDeps = {
validate: async () => {},
start: (_id, _q, onFile) =>
new Promise<SearchSummary | null>((resolve) => {
push = onFile;
finish = resolve;
}),
cancel: () => {},
nextRequestId: () => 1,
};
openInFindWindow(query, "needle", { deps });
render(<FindToolWindow />);
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
let updates = 0;
for (let b = 0; b < BATCHES; b++) {
await act(async () => {
for (const f of all.slice((b * F) / BATCHES, ((b + 1) * F) / BATCHES)) push(f);
await vi.advanceTimersByTimeAsync(60);
});
updates++;
}
await act(async () => {
finish({ files: F, matches: F * 3, limitHit: false, cancelled: false, elapsedMs: 1 });
await vi.advanceTimersByTimeAsync(0);
});
expect(updates).toBe(BATCHES);
expect(screen.getByText(/6.?000 matches in 2.?000 files/)).toBeInTheDocument();
// Counting matches and building nodes read each file's matches once each; rebuilding the tree on
// every one of the 40 updates would read them about 20 times each.
expect(reads.n).toBeLessThanOrEqual(3 * F);
});
});
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
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 { buildFindTree } from "../find/findTree";
import type { FindDeps } from "../find/session";
import {
closeFindTab,
+1 -1
Переглянути файл
@@ -19,7 +19,7 @@ import {
toggleExcluded,
type ReplaceDeps,
} from "../find/replaceFlow";
import { buildFindTree, nodeGroups } from "../find/FindToolWindow";
import { buildFindTree, nodeGroups } from "../find/findTree";
const q: SearchQuery = {
pattern: "foo",
+2 -6
Переглянути файл
@@ -83,18 +83,14 @@
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 8px 8px 0;
gap: var(--space-1);
padding: var(--space-2) var(--space-2) 0;
}
/* The query fields sit on the popup surface, framed only by their border. */
.fields .field {
width: 100%;
background: transparent;
}
.field input {
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.error {
color: var(--danger);
font-size: var(--fs-small);
+2
Переглянути файл
@@ -717,6 +717,7 @@ function FindInFilesDialog() {
invalid={state.status === "invalid"}
className={styles.field}
multiline
maxRows={3}
onHistory={() => setHistoryMenu("find")}
toggles={[
{
@@ -757,6 +758,7 @@ function FindInFilesDialog() {
aria-label="Replace with"
className={styles.field}
multiline
maxRows={3}
onHistory={() => setHistoryMenu("replace")}
toggles={[
{
+14 -108
Переглянути файл
@@ -3,7 +3,6 @@ import { useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "
import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import type { FileMatches } from "@/platform/ipc";
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
import {
Button,
@@ -23,8 +22,8 @@ import {
T,
} from "@/ui";
import { notifications, useOccurrenceNavigator } from "@/workbench/contributions";
import { basename, openLocation, relDir } from "../common/open";
import { countFileMatches } from "./session";
import { openLocation } from "../common/open";
import { FindTreeBuilder, allExpandableKeys, nodeGroups, type Node } from "./findTree";
import { CodePreview, MatchText, type PreviewHighlight } from "./parts";
import { confirmReplacement } from "./ReplaceAllConfirmation";
import {
@@ -41,7 +40,6 @@ import {
type ReplaceMarks,
type ReplaceProgress,
type ReplaceRun,
type UsageGroup,
type Usage,
} from "./replaceFlow";
import {
@@ -56,78 +54,6 @@ import {
import styles from "./FindToolWindow.module.css";
import { t, tx } from "@/platform/i18n";
type Node =
| { kind: "dir"; key: string; label: string; count: number; children: Node[] }
| { kind: "file"; key: string; path: string; name: string; dir: string; count: number; children: Node[] }
| {
kind: "match";
key: string;
path: string;
line: number;
col: number;
endCol: number;
text: string;
/** Column of `text` in the real line. */
textCol: number;
ranges: Array<[number, number]>;
starts: Array<{ line: number; col: number }>;
};
/**
* Streamed file matches as file → line nodes, flat and sorted by path (IDEA's
* default), or under their directory with `groupByDirectory`.
*/
export function buildFindTree(files: readonly FileMatches[], groupByDirectory = false): Node[] {
const dirs = new Map<string, Node & { kind: "dir" }>();
const flat: Node[] = [];
for (const f of files) {
const dir = relDir(f.relPath);
let d = dirs.get(dir);
if (!d && groupByDirectory) {
d = { kind: "dir", key: `d:${dir}`, label: dir || "/", count: 0, children: [] };
dirs.set(dir, d);
}
const children: Node[] = f.matches.map((m) => {
const lead = m.text.length - m.text.trimStart().length;
const text = m.text.slice(lead).trimEnd();
const first = m.ranges[0] ?? [0, 0];
return {
kind: "match",
key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`,
path: f.path,
line: m.line,
col: first[0] + m.textOffset,
endCol: first[1] + m.textOffset,
text,
textCol: lead + m.textOffset,
ranges: m.ranges
.map(([s, e]) => [Math.max(0, s - lead), Math.min(text.length, e - lead)] as [number, number])
.filter(([s, e]) => e > s),
starts: m.ranges.map(([s]) => ({ line: m.line, col: s + m.textOffset })),
};
});
const count = countFileMatches(f);
const file: Node = {
kind: "file",
key: `f:${f.path}`,
path: f.path,
name: basename(f.relPath),
dir,
count,
children,
};
if (d) {
d.children.push(file);
d.count += count;
} else flat.push(file);
}
if (!groupByDirectory) {
const rel = (n: Node) => (n.kind === "file" ? (n.dir ? `${n.dir}/${n.name}` : n.name) : "");
return flat.sort((a, b) => rel(a).localeCompare(rel(b)));
}
return [...dirs.values()].sort((a, b) => a.label.localeCompare(b.label));
}
/** Preview target of a node: a match, or a file's first match. */
function previewOf(node: Node | null): { path: string; line: number } | null {
if (!node || node.kind === "dir") return null;
@@ -136,12 +62,6 @@ function previewOf(node: Node | null): { path: string; line: number } | null {
return first?.kind === "match" ? { path: node.path, line: first.line } : null;
}
/** The usages under a node (itself for a match). */
export function nodeGroups(node: Node): UsageGroup[] {
if (node.kind === "match") return [{ key: node.key, path: node.path, starts: node.starts }];
return node.children.flatMap(nodeGroups);
}
/** Excluded (⌫) / replaced usages per Find tab. */
const useMarks = create<{ byTab: Record<number, ReplaceMarks> }>(() => ({ byTab: {} }));
const setMarks = (tab: number, marks: ReplaceMarks) =>
@@ -151,15 +71,6 @@ const useCollapsed = create<{ byTab: Record<number, ReadonlySet<string>> }>(() =
const setCollapsed = (tab: number, keys: ReadonlySet<string>) =>
useCollapsed.setState((s) => ({ byTab: { ...s.byTab, [tab]: keys } }));
function allExpandableKeys(nodes: readonly Node[], out = new Set<string>()): Set<string> {
for (const n of nodes) {
if (n.kind === "match") continue;
out.add(n.key);
allExpandableKeys(n.children, out);
}
return out;
}
/** Search tabs in the tool window header. */
export function FindTabs() {
const tabs = useFindWindow((s) => s.tabs);
@@ -236,32 +147,23 @@ function FindTabView({ tab }: { tab: FindTab }) {
}, [showPreview]);
const previewLayout = stacked ? "openidea.find.previewSplit.vertical" : "openidea.find.previewSplit";
const minPanelSize = stacked ? "30%" : 160;
const roots = useMemo(() => buildFindTree(tab.state.files, groupByDirectory), [tab.state.files, groupByDirectory]);
const findTree = useMemo(() => new FindTreeBuilder(groupByDirectory), [groupByDirectory]);
const roots = useMemo(() => findTree.sync(tab.state.files), [findTree, tab.state.files]);
const tree = useRef<TreeHandle>(null);
const [leadNode, setLeadNode] = useState<Node | null>(null);
const collapsed = useCollapsed((s) => s.byTab[tab.id]);
const expanded = useMemo(() => {
const all = allExpandableKeys(roots);
const all = new Set(findTree.expandable);
if (collapsed) for (const k of collapsed) all.delete(k);
return all;
}, [roots, collapsed]);
}, [findTree, roots, collapsed]); // eslint-disable-line react-hooks/exhaustive-deps -- roots: the builder changed under it
const st = tab.state;
const marks = useMarks((m) => m.byTab[tab.id]) ?? NO_MARKS;
const [selection, setSelection] = useState<Set<string>>(new Set());
const [running, setRunning] = useState<ReplaceRun | null>(null);
const [progress, setProgress] = useState<ReplaceProgress | null>(null);
const busy = !!running;
const allGroups = useMemo(() => roots.flatMap(nodeGroups), [roots]);
const byKey = useMemo(() => {
const map = new Map<string, Node>();
const walk = (list: readonly Node[]) =>
list.forEach((n) => {
map.set(n.key, n);
if (n.kind !== "match") walk(n.children);
});
walk(roots);
return map;
}, [roots]);
const byKey = findTree.byKey;
const selectedGroups = () => [...selection].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : []));
const exclude = () => {
@@ -284,7 +186,7 @@ function FindTabView({ tab }: { tab: FindTab }) {
const preview = previewOf(leadNode);
const highlights = useMemo<PreviewHighlight[]>(() => {
const f = preview && st.files.find((x) => x.path === preview.path);
const f = preview && findTree.filesByPath.get(preview.path);
return (f?.matches ?? []).map((m) => ({
line: m.line,
ranges: m.ranges.map(([a, b]) => [a + m.textOffset, b + m.textOffset] as [number, number]),
@@ -298,7 +200,7 @@ function FindTabView({ tab }: { tab: FindTab }) {
query: tab.query,
replacement: tab.replacement,
preserveCase: !!tab.preserveCase,
targets: allInScope ? skipTargets(allGroups, marks) : replaceTargets(usages),
targets: allInScope ? skipTargets(roots.flatMap(nodeGroups), marks) : replaceTargets(usages),
allInScope,
},
setProgress,
@@ -363,7 +265,11 @@ function FindTabView({ tab }: { tab: FindTab }) {
};
const replaceMode = tab.replacement !== null;
const allPending = pendingUsages(allGroups, marks);
// Replace All stays disabled while results stream in, so the pass over every usage waits for the end.
const allPending = useMemo(
() => (replaceMode && st.status !== "searching" ? pendingUsages(roots.flatMap(nodeGroups), marks) : []),
[replaceMode, st.status, roots, marks],
);
// Past the search's limit, every match in the scope is replaced, listed or not (as in IDEA).
const allInScope = !!st.summary?.limitHit;
const confirmReplaceAll = async () => {
+198
Переглянути файл
@@ -0,0 +1,198 @@
import type { FileMatches } from "@/platform/ipc";
import { basename, relDir } from "../common/open";
import { countFileMatches } from "./session";
import type { UsageGroup } from "./replaceFlow";
export type Node =
| { kind: "dir"; key: string; label: string; count: number; children: Node[] }
| { kind: "file"; key: string; path: string; name: string; dir: string; count: number; children: Node[] }
| {
kind: "match";
key: string;
path: string;
line: number;
col: number;
endCol: number;
text: string;
/** Column of `text` in the real line. */
textCol: number;
ranges: Array<[number, number]>;
starts: Array<{ line: number; col: number }>;
};
type FileNode = Node & { kind: "file" };
function fileNode(f: FileMatches): FileNode {
const children: Node[] = f.matches.map((m) => {
const lead = m.text.length - m.text.trimStart().length;
const text = m.text.slice(lead).trimEnd();
const first = m.ranges[0] ?? [0, 0];
return {
kind: "match",
key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`,
path: f.path,
line: m.line,
col: first[0] + m.textOffset,
endCol: first[1] + m.textOffset,
text,
textCol: lead + m.textOffset,
ranges: m.ranges
.map(([s, e]) => [Math.max(0, s - lead), Math.min(text.length, e - lead)] as [number, number])
.filter(([s, e]) => e > s),
starts: m.ranges.map(([s]) => ({ line: m.line, col: s + m.textOffset })),
};
});
return {
kind: "file",
key: `f:${f.path}`,
path: f.path,
name: basename(f.relPath),
dir: relDir(f.relPath),
count: countFileMatches(f),
children,
};
}
/** `old` and `add` are sorted by `cmp`; ties keep `old` first, so the result equals a stable sort of both. */
function mergeSorted<T>(old: readonly T[], add: T[], cmp: (a: T, b: T) => number): T[] {
if (!add.length) return old.slice();
add.sort(cmp);
const out: T[] = [];
let from = 0;
let i = 0;
while (i < add.length) {
// First `old` entry greater than add[i].
let lo = from;
let hi = old.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (cmp(old[mid]!, add[i]!) <= 0) lo = mid + 1;
else hi = mid;
}
for (let k = from; k < lo; k++) out.push(old[k]!);
from = lo;
out.push(add[i++]!);
}
for (let k = from; k < old.length; k++) out.push(old[k]!);
return out;
}
interface FlatEntry {
rel: string;
node: FileNode;
}
interface DirEntry {
key: string;
label: string;
count: number;
children: Node[];
node: Node | null;
}
/**
* Streamed file matches as file → line nodes, flat and sorted by path (IDEA's
* default), or under their directory with `groupByDirectory`.
*
* `sync` is incremental: the streamed list only ever grows at its end, so a call
* builds nodes for the new files alone and merges them into the sorted result,
* making the cost of a whole stream linear in the number of files. A list that
* is not an extension of the previous one is rebuilt from scratch.
*/
export class FindTreeBuilder {
/** Every node by key, kept in step with `sync`. */
readonly byKey = new Map<string, Node>();
/** Keys of every node that has children (files, directories). */
readonly expandable = new Set<string>();
readonly filesByPath = new Map<string, FileMatches>();
private roots: Node[] = [];
private built = 0;
private first: FileMatches | null = null;
private last: FileMatches | null = null;
private flat: FlatEntry[] = [];
private dirs = new Map<string, DirEntry>();
private dirList: DirEntry[] = [];
constructor(private readonly groupByDirectory = false) {}
/** Roots for `files`; the same array while nothing was appended. */
sync(files: readonly FileMatches[]): Node[] {
if (this.built && (files.length < this.built || files[0] !== this.first || files[this.built - 1] !== this.last))
this.reset();
if (files.length === this.built) return this.roots;
const fresh: FlatEntry[] = [];
const newDirs: DirEntry[] = [];
const touched = new Set<DirEntry>();
for (let i = this.built; i < files.length; i++) {
const f = files[i]!;
const file = fileNode(f);
this.filesByPath.set(f.path, f);
this.byKey.set(file.key, file);
this.expandable.add(file.key);
for (const m of file.children) this.byKey.set(m.key, m);
if (!this.groupByDirectory) {
fresh.push({ rel: file.dir ? `${file.dir}/${file.name}` : file.name, node: file });
continue;
}
let d = this.dirs.get(file.dir);
if (!d) {
d = { key: `d:${file.dir}`, label: file.dir || "/", count: 0, children: [], node: null };
this.dirs.set(file.dir, d);
newDirs.push(d);
}
d.children.push(file);
d.count += file.count;
touched.add(d);
}
if (files.length) {
this.first = files[0]!;
this.last = files[files.length - 1]!;
}
this.built = files.length;
if (!this.groupByDirectory) {
this.flat = mergeSorted(this.flat, fresh, (a, b) => a.rel.localeCompare(b.rel));
this.roots = this.flat.map((e) => e.node);
return this.roots;
}
// A directory that gained files becomes a new node, so rows showing its count update.
for (const d of touched) {
d.node = { kind: "dir", key: d.key, label: d.label, count: d.count, children: d.children.slice() };
this.byKey.set(d.key, d.node);
this.expandable.add(d.key);
}
this.dirList = mergeSorted(this.dirList, newDirs, (a, b) => a.label.localeCompare(b.label));
this.roots = this.dirList.map((d) => d.node!);
return this.roots;
}
private reset() {
this.byKey.clear();
this.expandable.clear();
this.filesByPath.clear();
this.roots = [];
this.built = 0;
this.first = this.last = null;
this.flat = [];
this.dirs.clear();
this.dirList = [];
}
}
export function buildFindTree(files: readonly FileMatches[], groupByDirectory = false): Node[] {
return new FindTreeBuilder(groupByDirectory).sync(files);
}
/** The usages under a node (itself for a match). */
export function nodeGroups(node: Node): UsageGroup[] {
if (node.kind === "match") return [{ key: node.key, path: node.path, starts: node.starts }];
return node.children.flatMap(nodeGroups);
}
export function allExpandableKeys(nodes: readonly Node[], out = new Set<string>()): Set<string> {
for (const n of nodes) {
if (n.kind === "match") continue;
out.add(n.key);
allExpandableKeys(n.children, out);
}
return out;
}
+28 -10
Переглянути файл
@@ -7,7 +7,8 @@
*
* A new `search()` supersedes whatever is running: the previous backend
* request is cancelled and its late events are dropped. Results stream in
* per file and are published at most once per microtask.
* per file and are published at most once per `PUBLISH_INTERVAL_MS`, so a burst of
* files costs one view update instead of one per file.
*/
import type { FileMatches, RequestId, SearchQuery, SearchSummary } from "@/platform/ipc";
import { preserveCase } from "@/platform/search";
@@ -33,6 +34,9 @@ export interface FindDeps {
nextRequestId(): RequestId;
}
/** Streamed results reach the view at most this often (a few frames), keeping a long stream linear. */
const PUBLISH_INTERVAL_MS = 50;
export const countFileMatches = (file: FileMatches): number =>
file.matches.reduce((count, line) => count + line.ranges.length, 0);
@@ -60,6 +64,8 @@ export class FindSession {
private request: RequestId | null = null;
private state: FindState = IDLE;
private queued = false;
private timer: ReturnType<typeof setTimeout> | undefined;
private lastPublish = 0;
private disposed = false;
constructor(
@@ -102,6 +108,7 @@ export class FindSession {
const request = this.deps.nextRequestId();
this.request = request;
this.lastPublish = 0;
const files: FileMatches[] = [];
let matchCount = 0;
this.update({ ...this.state, status: "searching" }, true);
@@ -151,17 +158,28 @@ export class FindSession {
this.state = next;
if (this.disposed) return;
if (immediate) {
this.queued = false;
this.onChange(next);
this.publish(false);
return;
}
if (this.queued) return;
this.queued = true;
queueMicrotask(() => {
if (!this.queued || this.disposed) return;
this.queued = false;
this.onChange(this.state);
});
if (this.timer !== undefined || this.queued) return;
// A streamed file publishes at once when the last publish is old enough (the first file shows
// without delay); otherwise it waits so the batch behind it is one update, not one per file.
const wait = this.lastPublish + PUBLISH_INTERVAL_MS - Date.now();
if (wait <= 0) {
this.queued = true;
queueMicrotask(() => {
if (this.queued) this.publish(true);
});
} else this.timer = setTimeout(() => this.publish(true), wait);
}
private publish(streamed: boolean) {
this.queued = false;
clearTimeout(this.timer);
this.timer = undefined;
if (this.disposed) return;
if (streamed) this.lastPublish = Date.now();
this.onChange(this.state);
}
}
+139 -4
Переглянути файл
@@ -260,18 +260,20 @@
}
.propRow {
display: grid;
grid-template-columns: 140px 1fr;
grid-template-columns: 140px minmax(0, 1fr);
gap: var(--space-2);
align-items: baseline;
align-items: start;
padding: 5px 12px;
border-bottom: 1px solid var(--border);
}
.propName {
color: var(--fg-secondary);
font-size: var(--fs-small);
line-height: 20px;
}
.propVal {
min-width: 0;
line-height: 20px;
overflow-wrap: anywhere;
color: var(--fg);
}
@@ -285,14 +287,85 @@
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.codeInline {
display: inline-block;
.commandField {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
min-width: 0;
}
.commandHeader {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.commandPreview {
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 1px 6px;
border-radius: var(--radius-small);
background: var(--bg-elev);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 18px;
}
.commandToggle {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
flex: none;
height: 20px;
padding: 0 6px;
border: 1px solid var(--border);
border-radius: var(--radius-small);
background: var(--bg-elev);
color: var(--fg-secondary);
font-family: var(--font-ui);
font-size: var(--fs-tiny);
line-height: 1;
cursor: pointer;
}
.commandToggle:hover {
background: var(--bg-hover);
color: var(--fg);
}
.commandToggle:focus-visible {
outline: 1px solid var(--accent);
outline-offset: -1px;
}
.commandBody {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
max-height: 180px;
overflow: auto;
padding: 6px 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border);
background: var(--bg-elev);
}
.commandSection {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.commandSectionLabel {
font-size: var(--fs-tiny);
font-weight: 600;
line-height: 14px;
color: var(--fg-subtle);
}
.commandPre {
margin: 0;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 18px;
white-space: pre-wrap;
overflow-wrap: anywhere;
color: var(--fg);
}
.mutedMeta {
color: var(--fg-subtle);
@@ -501,3 +574,65 @@ button.entityChip:not(:disabled):hover {
min-width: 96px;
white-space: nowrap;
}
.composeTableWrap {
overflow-x: auto;
}
.composeServicesTable th {
position: static;
background: transparent;
padding: 4px 8px;
}
.composeServicesTable td {
padding: 4px 8px;
vertical-align: middle;
}
.composeServicesTable tbody tr:last-child td {
border-bottom: 0;
}
.composeServicesTable th:first-child,
.composeServicesTable td:first-child {
padding-left: 12px;
}
.composeServicesTable th:last-child,
.composeServicesTable td:last-child {
padding-right: 12px;
}
.composeServiceCell {
white-space: nowrap;
}
.composeServiceCell > .mutedMeta {
margin-left: var(--space-1-5);
}
.nowrapCell {
white-space: nowrap;
}
.composeMetricCell {
min-width: 76px;
white-space: nowrap;
}
.composeMemoryCell {
min-width: 148px;
white-space: nowrap;
}
.composeMetric {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.volumeChip {
max-width: 100%;
min-width: 0;
}
.volumeChipIcon {
flex: none;
}
.volumeChipName {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.volumeChipMeta {
flex: none;
white-space: nowrap;
}
+320
Переглянути файл
@@ -0,0 +1,320 @@
/**
* Jump to Source for Docker Compose services and containers: resolves the
* container's `composeFiles` / `composeWorkingDir` and opens the Compose YAML
* file at the service declaration, or (from the dashboard's Command row) at
* `services.<service>.command`, else `entrypoint`, else the declaration.
*/
import { editorsFor } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, type DockerContainer } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { editorService, notifications } from "@/workbench/contributions";
/** Where to land in a service: its `command` (else `entrypoint`), or its declaration. */
export type ComposeTarget = "command" | "service";
export interface ComposeCommandLocation {
kind: "command" | "entrypoint" | "service" | "services" | "file";
/** 0-based line index. */
line: number;
/** 0-based UTF-16 column index. */
col: number;
}
const DEFAULT_COMPOSE_FILENAMES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"] as const;
const BLOCK_SCALAR_HEADER = /^[|>](?:[+-]?\d*|\d+[+-]?)$/;
const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:\//.test(p);
const normalizeSlashes = (p: string) => p.replace(/\\/g, "/");
function joinDirAndFile(dir: string, file: string): string {
const cleanDir = normalizeSlashes(dir).replace(/\/+$/, "");
const cleanFile = normalizeSlashes(file).replace(/^(?:\.\/)+/, "");
if (!cleanDir) return cleanFile;
return `${cleanDir}/${cleanFile}`;
}
export function hasComposeSource(
container: Pick<DockerContainer, "composeProject" | "composeWorkingDir" | "composeFiles">,
): boolean {
return Boolean(container.composeFiles.length || (container.composeProject && container.composeWorkingDir));
}
/**
* Candidate Compose file paths in evaluation order (base files first, override files last),
* resolved against `composeWorkingDir` or `projectRoot` when relative.
*/
export function resolveComposeFilePaths(
composeFiles: readonly string[],
composeWorkingDir: string | null,
projectRoot: string | null = null,
): string[] {
const baseDir = composeWorkingDir?.trim() || projectRoot?.trim() || "";
const seen = new Set<string>();
const add = (raw: string) => {
const trimmed = raw.trim();
if (!trimmed) return;
const normalized = normalizeSlashes(trimmed);
const full = isAbsolute(normalized) ? normalized : baseDir ? joinDirAndFile(baseDir, normalized) : null;
if (full && !seen.has(full)) seen.add(full);
};
if (composeFiles.length > 0) {
for (const f of composeFiles) add(f);
} else if (composeWorkingDir?.trim()) {
for (const name of DEFAULT_COMPOSE_FILENAMES) add(joinDirAndFile(composeWorkingDir.trim(), name));
}
return [...seen];
}
/** Strip `# ...` comments outside of single/double quotes. */
function stripInlineComment(line: string): string {
let quote: string | null = null;
for (let i = 0; i < line.length; i++) {
const ch = line[i]!;
if (quote) {
if (ch === "\\" && quote === '"') i++;
else if (ch === quote) quote = null;
} else if (ch === '"' || ch === "'") {
quote = ch;
} else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]!))) {
return line.slice(0, i);
}
}
return line;
}
function valuePositionAt(
lines: readonly string[],
propLine: number,
propIndent: number,
codeAfterColon: string,
colonEndCol: number,
): { line: number; col: number } {
const trimmed = codeAfterColon.trim();
if (trimmed && !BLOCK_SCALAR_HEADER.test(trimmed)) {
const leadWs = codeAfterColon.length - codeAfterColon.trimStart().length;
return { line: propLine, col: colonEndCol + leadWs };
}
if (BLOCK_SCALAR_HEADER.test(trimmed)) {
for (let k = propLine + 1; k < lines.length; k++) {
const raw = lines[k]!.replace(/\r$/, "");
if (!raw.trim()) continue;
const rawLead = raw.length - raw.trimStart().length;
if (rawLead <= propIndent) break;
return { line: k, col: rawLead };
}
return { line: propLine, col: propIndent };
}
for (let k = propLine + 1; k < lines.length; k++) {
const raw = lines[k]!.replace(/\r$/, "");
const code = stripInlineComment(raw);
if (!code.trim()) continue;
const lead = code.length - code.trimStart().length;
if (lead < propIndent) break;
const seqMatch = /^(\s*-\s+)(.*)$/.exec(code);
if (seqMatch) {
const itemText = seqMatch[2]!.trim();
if (BLOCK_SCALAR_HEADER.test(itemText)) {
const dashIndent = lead;
for (let m = k + 1; m < lines.length; m++) {
const scriptRaw = lines[m]!.replace(/\r$/, "");
if (!scriptRaw.trim()) continue;
const scriptLead = scriptRaw.length - scriptRaw.trimStart().length;
if (scriptLead <= dashIndent) break;
return { line: m, col: scriptLead };
}
}
return { line: k, col: seqMatch[1]!.length };
}
if (lead === propIndent) break;
return { line: k, col: lead };
}
return { line: propLine, col: propIndent };
}
/**
* Locates `services.<service>.command` (preferred), `services.<service>.entrypoint`,
* or the `services.<service>` declaration in a Compose YAML document.
* When `service` is null, locates the top-level `services:` section.
*/
export function locateComposeServiceCommand(
text: string,
service: string | null,
at: ComposeTarget = "command",
): ComposeCommandLocation | null {
const lines = text.split("\n");
let inServices = false;
let serviceIndent: number | null = null;
for (let i = 0; i < lines.length; i++) {
const code = stripInlineComment(lines[i]!.replace(/\r$/, ""));
if (!code.trim()) continue;
const lead = code.length - code.trimStart().length;
if (lead === 0) {
const top = /^([A-Za-z0-9._-]+)\s*:/.exec(code)?.[1];
if (top === "services") {
if (!service) return { kind: "services", line: i, col: 0 };
inServices = true;
serviceIndent = null;
} else {
inServices = false;
serviceIndent = null;
}
continue;
}
if (!inServices || !service) continue;
serviceIndent ??= lead;
if (lead !== serviceIndent) continue;
const svcMatch = /^(\s*)("([^"]+)"|'([^']+)'|([A-Za-z0-9._-]+))\s*:/.exec(code);
if (!svcMatch) continue;
const svcName = (svcMatch[3] ?? svcMatch[4] ?? svcMatch[5])!;
if (svcName !== service) continue;
const rawToken = svcMatch[2]!;
const svcCol = svcMatch[1]!.length + (rawToken.startsWith('"') || rawToken.startsWith("'") ? 1 : 0);
const serviceLoc: ComposeCommandLocation = { kind: "service", line: i, col: svcCol };
if (at === "service") return serviceLoc;
let propIndent: number | null = null;
let commandLoc: ComposeCommandLocation | null = null;
let entrypointLoc: ComposeCommandLocation | null = null;
for (let j = i + 1; j < lines.length; j++) {
const propCode = stripInlineComment(lines[j]!.replace(/\r$/, ""));
if (!propCode.trim()) continue;
const propLead = propCode.length - propCode.trimStart().length;
if (propLead <= serviceIndent) break;
const keyMatch = /^(\s*)("([^"]+)"|'([^']+)'|([A-Za-z0-9._-]+))\s*:(.*)$/.exec(propCode);
if (!keyMatch) continue;
if (propIndent === null || propLead < propIndent) propIndent = propLead;
if (propLead !== propIndent) continue;
const propName = (keyMatch[3] ?? keyMatch[4] ?? keyMatch[5])!;
if (propName !== "command" && propName !== "entrypoint") continue;
const afterColon = keyMatch[6] ?? "";
const colonEndCol = propCode.length - afterColon.length;
const pos = valuePositionAt(lines, j, propIndent, afterColon, colonEndCol);
if (propName === "command") commandLoc = { kind: "command", ...pos };
else entrypointLoc = { kind: "entrypoint", ...pos };
}
return commandLoc ?? entrypointLoc ?? serviceLoc;
}
return service ? null : { kind: "file", line: 0, col: 0 };
}
/**
* Picks the active Compose file and caret position across ordered Compose files
* (later override files take precedence when they define `command` or `entrypoint`).
*/
export function pickComposeCommandLocation(
files: ReadonlyArray<{ path: string; text: string }>,
service: string | null,
at: ComposeTarget = "command",
): (ComposeCommandLocation & { path: string }) | null {
if (!files.length) return null;
if (!service) {
for (const f of files) {
const loc = locateComposeServiceCommand(f.text, null);
if (loc && loc.kind === "services") return { path: f.path, ...loc };
}
return { path: files[0]!.path, kind: "file", line: 0, col: 0 };
}
for (let i = files.length - 1; at === "command" && i >= 0; i--) {
const f = files[i]!;
const loc = locateComposeServiceCommand(f.text, service);
if (loc && (loc.kind === "command" || loc.kind === "entrypoint")) {
return { path: f.path, ...loc };
}
}
for (const f of files) {
const loc = locateComposeServiceCommand(f.text, service, at);
if (loc) return { path: f.path, ...loc };
}
return { path: files[0]!.path, kind: "file", line: 0, col: 0 };
}
async function readComposeFileText(path: string): Promise<string | null> {
const open = editorsFor(path)[0];
if (open) return open.view.state.doc.toString();
try {
return await call(commands.fsReadText(path));
} catch {
return null;
}
}
async function loadReadableComposeFiles(
composeFiles: readonly string[],
composeWorkingDir: string | null,
): Promise<Array<{ path: string; text: string }>> {
const root = useProject.getState().project?.root ?? null;
const candidates = resolveComposeFilePaths(composeFiles, composeWorkingDir, root);
const loaded = await Promise.all(
candidates.map(async (path) => {
const text = await readComposeFileText(path);
return text !== null ? { path, text } : null;
}),
);
return loaded.filter((x): x is { path: string; text: string } => x !== null);
}
export async function jumpToContainerComposeSource(
container: DockerContainer,
at: ComposeTarget = "service",
): Promise<void> {
const files = await loadReadableComposeFiles(container.composeFiles, container.composeWorkingDir);
const target = pickComposeCommandLocation(files, container.composeService, at);
if (!target) {
notifications().notify({
group: "run",
level: "info",
title: tx`Cannot find the source of ${container.name}`,
});
return;
}
await editorService().openFile(target.path, {
selection: { line: target.line, col: target.col },
focus: true,
});
}
export async function jumpToComposeProjectSource(
project: string,
containers: readonly DockerContainer[],
): Promise<void> {
const first = containers[0];
const files = first ? await loadReadableComposeFiles(first.composeFiles, first.composeWorkingDir) : [];
const target = pickComposeCommandLocation(files, null);
if (!target) {
notifications().notify({
group: "run",
level: "info",
title: tx`Cannot find the source of ${project}`,
});
return;
}
await editorService().openFile(target.path, {
selection: { line: target.line, col: target.col },
focus: true,
});
}
export async function openComposeFile(file: string, composeWorkingDir: string | null): Promise<void> {
const files = await loadReadableComposeFiles([file], composeWorkingDir);
if (!files.length) {
notifications().notify({
group: "run",
level: "info",
title: tx`Cannot find the source of ${file}`,
});
return;
}
await editorService().openFile(files[0]!.path, { focus: true });
}
+459 -60
Переглянути файл
@@ -7,7 +7,7 @@
* proven in `openidea-kubernetes` (`ResourceDetails.tsx`).
*/
import { writeClipboardText } from "@/platform/clipboard";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import type {
DockerContainer,
@@ -23,7 +23,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { Button, EmptyState, Icon, IconButton, Spinner, T } from "@/ui";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { notifications } from "@/workbench/contributions";
import { notifications, useToolWindowShown } from "@/workbench/contributions";
import {
containersInNetwork,
containersUsingImage,
@@ -35,6 +35,7 @@ import {
isRunning,
shortId,
treeKey,
volumesInComposeProject,
type DockerTarget,
} from "./model";
import {
@@ -51,6 +52,7 @@ import {
targetBusy,
} from "./ops";
import { openContainerLogInEditor } from "./logEditor";
import { hasComposeSource, jumpToContainerComposeSource, openComposeFile } from "./composeSource";
import { containerOp, endpointOf, errorMessage, useServices } from "./store";
import { useServicesTree } from "./tree";
import styles from "./Services.module.css";
@@ -536,6 +538,155 @@ export function parseNetworkInspect(raw: string | null): ParsedNetworkInspect |
const copyText = (text: string) => void writeClipboardText(text);
const SAFE_SHELL_TOKEN = /^[A-Za-z0-9_./:@%+=,-]+$/;
function formatShellToken(token: string): string {
const normalized = token.replace(/\r\n?/g, "\n");
if (!normalized) return "''";
if (normalized.includes("\n")) {
const trimmed = normalized.replace(/^\n+|\n+$/g, "");
return `'\n${trimmed.replace(/'/g, "'\\''")}\n'`;
}
if (SAFE_SHELL_TOKEN.test(normalized)) return normalized;
return `'${normalized.replace(/'/g, "'\\''")}'`;
}
function formatPreviewToken(token: string): string {
const normalized = token.replace(/\r\n?/g, "\n");
if (!normalized) return "''";
if (normalized.includes("\n")) {
const lines = normalized
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
return `'${lines.join(" ↵ ")}'`;
}
if (SAFE_SHELL_TOKEN.test(normalized)) return normalized;
return `'${normalized.replace(/'/g, "'\\''")}'`;
}
export interface FormattedDockerCommand {
preview: string;
entrypoint: string;
args: string;
fullText: string;
copyText: string;
lineCount: number;
}
export function formatDockerCommand(
entrypoint: readonly string[],
cmd: readonly string[],
fallback = "",
): FormattedDockerCommand | null {
if (entrypoint.length || cmd.length) {
const entrypointText = entrypoint.map(formatShellToken).join(" ");
const argsText = cmd.map(formatShellToken).join(" ");
const copyText = entrypointText && argsText ? `${entrypointText} ${argsText}` : entrypointText || argsText;
const preview = [...entrypoint, ...cmd].map(formatPreviewToken).join(" ");
return {
preview,
entrypoint: entrypointText,
args: argsText,
fullText: copyText,
copyText,
lineCount: copyText.split("\n").length,
};
}
const trimmed = fallback.replace(/\r\n?/g, "\n").trim();
if (!trimmed) return null;
const lines = trimmed.split("\n");
const preview =
lines.length > 1
? lines
.map((l) => l.trim())
.filter(Boolean)
.join(" ↵ ")
: trimmed;
return {
preview,
entrypoint: "",
args: "",
fullText: trimmed,
copyText: trimmed,
lineCount: lines.length,
};
}
function CommandField({ command, actions }: { command: FormattedDockerCommand; actions?: ReactNode }) {
const tx = useTx();
const [expanded, setExpanded] = useState(false);
const [overflowing, setOverflowing] = useState(false);
const previewRef = useRef<HTMLElement>(null);
const multiLine = command.lineCount > 1;
useEffect(() => {
const el = previewRef.current;
if (!el || expanded || multiLine) return;
const measure = () => setOverflowing(el.scrollWidth > el.clientWidth);
const frame = requestAnimationFrame(measure);
if (typeof ResizeObserver === "undefined") return () => cancelAnimationFrame(frame);
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
};
}, [command.preview, expanded, multiLine]);
const canExpand = multiLine || overflowing;
const count = command.lineCount;
const hasSplitSections = !!command.entrypoint && !!command.args;
return (
<div className={styles.commandField}>
<div className={styles.commandHeader}>
{!expanded && (
<code ref={previewRef} className={styles.commandPreview} data-no-tooltip="">
{command.preview}
</code>
)}
{(canExpand || expanded) && (
<button
type="button"
className={styles.commandToggle}
aria-expanded={expanded}
onClick={() => setExpanded((v) => !v)}
>
<Icon name={expanded ? "chevron-down" : "chevron-right"} size={12} />
<span>{expanded ? <T>Collapse</T> : multiLine ? tx`${count} lines` : <T>Expand</T>}</span>
</button>
)}
{expanded && multiLine && <span className={styles.mutedMeta}>{tx`${count} lines`}</span>}
<IconButton icon="copy" size="small" title="Copy Command" onClick={() => copyText(command.copyText)} />
{actions}
</div>
{expanded && (
<div className={styles.commandBody}>
{hasSplitSections ? (
<>
<div className={styles.commandSection}>
<div className={styles.commandSectionLabel}>
<T>Entrypoint</T>
</div>
<pre className={styles.commandPre}>{command.entrypoint}</pre>
</div>
<div className={styles.commandSection}>
<div className={styles.commandSectionLabel}>
<T>Command arguments</T>
</div>
<pre className={styles.commandPre}>{command.args}</pre>
</div>
</>
) : (
<pre className={styles.commandPre}>{command.fullText}</pre>
)}
</div>
)}
</div>
);
}
async function openExternalUrl(url: string): Promise<void> {
try {
if (isTauri()) {
@@ -638,28 +789,26 @@ function KeyValueTable({ rows, emptyText }: { rows: ReadonlyArray<readonly [stri
);
}
function ContainerLinkChip({ conn, container }: { conn: string; container: DockerContainer }) {
const running = isRunning(container);
function selectContainerInTree(conn: string, container: DockerContainer): void {
const key = treeKey(conn, { kind: "container", key: `container:${container.id}`, container });
const parentKey = container.composeProject
? `docker:${conn}:compose:${container.composeProject}`
: isDevContainer(container)
? `docker:${conn}:group:devContainers`
: `docker:${conn}:group:containers`;
useServicesTree.setState((s) => {
const expanded = new Set(s.expanded);
expanded.add(`docker:${conn}`);
expanded.add(parentKey);
return { selectedKey: key, selectedKeys: new Set([key]), expanded };
});
showDetail("dashboard");
}
function ContainerLinkChip({ conn, container }: { conn: string; container: DockerContainer }) {
const running = isRunning(container);
return (
<button
type="button"
className={styles.entityChip}
onClick={() => {
useServicesTree.setState((s) => {
const expanded = new Set(s.expanded);
expanded.add(`docker:${conn}`);
expanded.add(parentKey);
return { selectedKey: key, selectedKeys: new Set([key]), expanded };
});
showDetail("dashboard");
}}
>
<button type="button" className={styles.entityChip} onClick={() => selectContainerInTree(conn, container)}>
<span className={clsx(styles.statusDot, running ? styles.dotOk : styles.dotMuted)} />
<span className={styles.mono}>{container.name}</span>
<span className={styles.chipMeta}>{container.status}</span>
@@ -667,6 +816,122 @@ function ContainerLinkChip({ conn, container }: { conn: string; container: Docke
);
}
function VolumeLinkChip({ conn, volume }: { conn: string; volume: DockerVolume }) {
const composeVol = volume.labels?.["com.docker.compose.volume"];
const meta = composeVol && composeVol !== volume.name ? `${composeVol} · ${volume.driver}` : volume.driver;
return (
<button
type="button"
className={clsx(styles.entityChip, styles.volumeChip)}
title={volume.mountpoint || volume.name}
onClick={() => {
selectServicesTreeKey(treeKey(conn, { kind: "volume", key: `volume:${volume.name}`, volume }));
showDetail("dashboard");
}}
>
<Icon name="docker-volumes" size={14} className={styles.volumeChipIcon} />
<span className={clsx(styles.mono, styles.volumeChipName)}>{volume.name}</span>
{meta && <span className={clsx(styles.chipMeta, styles.volumeChipMeta)}>{meta}</span>}
</button>
);
}
const STATS_CONCURRENCY = 6;
/** Default `top` refresh delay (3s) between live `docker stats --no-stream` samples. */
export const CONTAINER_STATS_POLL_MS = 3000;
async function fetchContainerStatsMap(
conn: string,
ids: readonly string[],
): Promise<Record<string, DockerContainerStats>> {
const out: Record<string, DockerContainerStats> = {};
const endpoint = endpointOf(conn);
let next = 0;
const worker = async () => {
while (next < ids.length) {
const id = ids[next++]!;
try {
out[id] = await call(commands.dockerContainerStats(endpoint, id));
} catch {
// Container may have stopped before stats were sampled.
}
}
};
await Promise.all(Array.from({ length: Math.min(STATS_CONCURRENCY, ids.length) }, () => worker()));
return out;
}
function useLiveContainerStats(
conn: string,
runningIdsKey: string,
): {
byId: Record<string, DockerContainerStats>;
loading: boolean;
} {
const shown = useToolWindowShown();
const statsScope = `${conn}\0${runningIdsKey}`;
const [statsState, setStatsState] = useState<{
conn: string;
byId: Record<string, DockerContainerStats>;
settledScope: string;
}>({ conn: "", byId: {}, settledScope: "" });
useEffect(() => {
const ids = runningIdsKey ? runningIdsKey.split("\0") : [];
if (!ids.length || !shown || !isTauri()) return;
let alive = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let inFlight = false;
const clearTimer = () => {
if (timer !== undefined) {
clearTimeout(timer);
timer = undefined;
}
};
const isDocumentHidden = () => document.visibilityState === "hidden";
const sample = async () => {
clearTimer();
if (!alive || inFlight || isDocumentHidden()) return;
inFlight = true;
try {
const byId = await fetchContainerStatsMap(conn, ids);
if (alive) {
setStatsState({ conn, byId, settledScope: statsScope });
}
} finally {
inFlight = false;
if (alive && !isDocumentHidden()) {
timer = setTimeout(() => void sample(), CONTAINER_STATS_POLL_MS);
}
}
};
const onVisibility = () => {
if (isDocumentHidden()) clearTimer();
else void sample();
};
document.addEventListener("visibilitychange", onVisibility);
if (!isDocumentHidden()) void sample();
return () => {
alive = false;
clearTimer();
document.removeEventListener("visibilitychange", onVisibility);
};
}, [conn, runningIdsKey, shown, statsScope]);
const active = Boolean(runningIdsKey) && shown && isTauri();
return {
byId: statsState.conn === conn ? statsState.byId : {},
loading: active && statsState.settledScope !== statsScope,
};
}
// ---------------------------------------------------------------------------
// Container Dashboard & Processes View
@@ -711,32 +976,16 @@ export function ContainerDashboard({
const ports = useMemo(() => inspect?.ports ?? parsePortMappings(container.ports), [inspect, container.ports]);
const matchedImage = useMemo(() => findImageForContainer(snapshot, container), [snapshot, container]);
const [stats, setStats] = useState<DockerContainerStats | null>(null);
const [statsLoading, setStatsLoading] = useState(false);
useEffect(() => {
if (!running || !isTauri()) return;
let alive = true;
call(commands.dockerContainerStats(endpointOf(conn), container.id))
.then((s) => alive && setStats(s))
.catch(() => alive && setStats(null));
return () => {
alive = false;
};
}, [conn, container.id, running]);
const reloadStats = useCallback(() => {
if (!running || !isTauri()) return;
setStatsLoading(true);
call(commands.dockerContainerStats(endpointOf(conn), container.id))
.then((s) => setStats(s))
.catch(() => setStats(null))
.finally(() => setStatsLoading(false));
}, [conn, container.id, running]);
const { byId: statsById, loading: statsLoading } = useLiveContainerStats(conn, running ? container.id : "");
const stats = running ? (statsById[container.id] ?? null) : null;
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
const labels = inspect?.labels.length ? inspect.labels : Object.entries(container.labels ?? {});
const command = useMemo(
() => formatDockerCommand(inspect?.entrypoint ?? [], inspect?.cmd ?? [], container.command),
[inspect, container.command],
);
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
@@ -831,12 +1080,22 @@ export function ContainerDashboard({
<PropRow label={<T>Started</T>} hidden={!inspect?.startedAt || inspect.startedAt.startsWith("0001-01-01")}>
{formatCreatedDetailed(inspect?.startedAt)}
</PropRow>
<PropRow label={<T>Command</T>} hidden={!container.command && !inspect?.cmd.length}>
<code className={styles.codeInline}>
{inspect && (inspect.entrypoint.length || inspect.cmd.length)
? [...inspect.entrypoint, ...inspect.cmd].join(" ")
: container.command}
</code>
<PropRow label={<T>Command</T>} hidden={!command}>
{command && (
<CommandField
command={command}
actions={
hasComposeSource(container) && (
<IconButton
icon="autoscroll-to-source"
size="small"
title="Jump to Source"
onClick={() => void jumpToContainerComposeSource(container, "command")}
/>
)
}
/>
)}
</PropRow>
<PropRow label={<T>Working directory</T>} hidden={!inspect?.workingDir}>
<span className={styles.mono}>{inspect?.workingDir}</span>
@@ -874,11 +1133,7 @@ export function ContainerDashboard({
{running && (
<>
<SectionBanner
action={
<IconButton icon="refresh" size="small" title="Refresh" disabled={statsLoading} onClick={reloadStats} />
}
>
<SectionBanner>
<T>Resource Usage</T>
</SectionBanner>
{stats ? (
@@ -1192,6 +1447,7 @@ export function ImageDashboard({
return [...new Set([...fromSnap, ...fromInspect])];
}, [snapshot, image, inspect]);
const usingContainers = useMemo(() => containersUsingImage(snapshot, image), [snapshot, image]);
const command = useMemo(() => formatDockerCommand(inspect?.entrypoint ?? [], inspect?.cmd ?? []), [inspect]);
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
@@ -1236,10 +1492,8 @@ export function ImageDashboard({
<PropRow label={<T>Platform</T>} hidden={!inspect?.os && !inspect?.architecture}>
<span className={styles.mono}>{[inspect?.os, inspect?.architecture].filter(Boolean).join("/")}</span>
</PropRow>
<PropRow label={<T>Command</T>} hidden={!inspect?.entrypoint.length && !inspect?.cmd.length}>
<code className={styles.codeInline}>
{[...(inspect?.entrypoint ?? []), ...(inspect?.cmd ?? [])].join(" ")}
</code>
<PropRow label={<T>Command</T>} hidden={!command}>
{command && <CommandField command={command} />}
</PropRow>
<PropRow label={<T>Working directory</T>} hidden={!inspect?.workingDir}>
<span className={styles.mono}>{inspect?.workingDir}</span>
@@ -1437,7 +1691,26 @@ export function VolumeDashboard({
</span>
</PropRow>
<PropRow label={<T>Compose</T>} hidden={!volume.composeProject}>
<span className={styles.mono}>{volume.composeProject}</span>
{volume.composeProject && snapshot.containers.some((c) => c.composeProject === volume.composeProject) ? (
<button
type="button"
className={styles.link}
onClick={() => {
selectServicesTreeKey(
treeKey(conn, {
kind: "compose",
key: `compose:${volume.composeProject!}`,
project: volume.composeProject!,
containers: [],
}),
);
}}
>
<span className={styles.mono}>{volume.composeProject}</span>
</button>
) : (
<span className={styles.mono}>{volume.composeProject}</span>
)}
</PropRow>
</div>
@@ -1574,10 +1847,12 @@ export function ComposeProjectDashboard({
conn,
project,
containers,
snapshot,
}: {
conn: string;
project: string;
containers: DockerContainer[];
snapshot: DockerSnapshot;
}) {
const txTemplate = useTxTemplate();
const target: DockerTarget = {
@@ -1587,6 +1862,18 @@ export function ComposeProjectDashboard({
const busy = useServices((s) => targetBusy(target, s));
const first = containers[0];
const runningCount = containers.filter(isRunning).length;
const namedVolumes = useMemo(() => volumesInComposeProject(snapshot, project), [snapshot, project]);
const runningIdsKey = useMemo(
() =>
containers
.filter(isRunning)
.map((c) => c.id)
.sort()
.join("\0"),
[containers],
);
const { byId: activeStats, loading: statsLoading } = useLiveContainerStats(conn, runningIdsKey);
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
@@ -1619,18 +1906,130 @@ export function ComposeProjectDashboard({
<span className={styles.mono}>{first?.composeWorkingDir}</span>
</PropRow>
<PropRow label={<T>Compose files</T>} hidden={!first?.composeFiles.length}>
<span className={styles.mono}>{first?.composeFiles.join(", ")}</span>
<span className={styles.inlineRow}>
{first?.composeFiles.map((file) => (
<button
key={file}
type="button"
className={styles.link}
onClick={() => void openComposeFile(file, first.composeWorkingDir)}
>
<span className={styles.mono}>{file}</span>
</button>
))}
</span>
</PropRow>
</div>
<SectionBanner>
<T>Services</T>
</SectionBanner>
<div className={styles.chipGroup}>
{containers.map((c) => (
<ContainerLinkChip key={c.id} conn={conn} container={c} />
))}
<div className={styles.composeTableWrap}>
<table className={clsx(styles.gridTable, styles.composeServicesTable)}>
<thead>
<tr>
<th>
<T>Service</T>
</th>
<th>
<T>Status</T>
</th>
<th>
<T>CPU</T>
</th>
<th>
<T>Memory</T>
</th>
<th>
<T>Network I/O</T>
</th>
<th>
<T>Block I/O</T>
</th>
<th>
<T>PIDs</T>
</th>
</tr>
</thead>
<tbody>
{containers.map((c) => {
const running = isRunning(c);
const stats = running ? activeStats[c.id] : undefined;
const cpuPct = stats ? parsePercent(stats.cpuPerc) : 0;
const memPair = stats ? parseUsagePair(stats.memUsage) : null;
const memPct = memPair ? memPair.percent : stats ? parsePercent(stats.memPerc) : 0;
return (
<tr key={c.id}>
<td className={styles.composeServiceCell}>
<button type="button" className={styles.link} onClick={() => selectContainerInTree(conn, c)}>
<span className={clsx(styles.statusDot, running ? styles.dotOk : styles.dotMuted)} />
<span className={styles.mono}>{c.name}</span>
</button>
{c.composeService && !c.name.includes(c.composeService) && (
<span className={styles.mutedMeta}>{c.composeService}</span>
)}
</td>
<td className={styles.nowrapCell}>
<StatusBadge state={c.state} text={c.status || c.state} />
</td>
<td className={styles.composeMetricCell}>
{stats ? (
<div className={styles.composeMetric}>
<span className={styles.mono}>{stats.cpuPerc}</span>
<LineProgress percent={cpuPct} />
</div>
) : running && statsLoading ? (
<Spinner size={12} />
) : (
<span className={styles.mutedMeta}>—</span>
)}
</td>
<td className={styles.composeMemoryCell}>
{stats ? (
<div className={styles.composeMetric}>
<span className={styles.mono}>
{stats.memUsage} ({stats.memPerc})
</span>
<LineProgress percent={memPct} />
</div>
) : running && statsLoading ? (
<span className={styles.mutedMeta}>
<T>Loading…</T>
</span>
) : (
<span className={styles.mutedMeta}>—</span>
)}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.netIo || <span className={styles.mutedMeta}>—</span>}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.blockIo || <span className={styles.mutedMeta}>—</span>}
</td>
<td className={clsx(styles.mono, styles.nowrapCell)}>
{stats?.pids || <span className={styles.mutedMeta}>—</span>}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<SectionBanner>
<T>Volumes</T>
</SectionBanner>
{namedVolumes.length > 0 ? (
<div className={styles.chipGroup}>
{namedVolumes.map((v) => (
<VolumeLinkChip key={v.name} conn={conn} volume={v} />
))}
</div>
) : (
<div className={styles.emptySection}>
<T>No named volumes</T>
</div>
)}
</div>
);
}
+186
Переглянути файл
@@ -0,0 +1,186 @@
import { act, cleanup, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DockerContainer, DockerContainerStats, DockerSnapshot } from "@/platform/ipc";
import { ToolWindowShownProvider } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({
stats: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
dockerContainerStats: backend.stats,
},
};
});
import { ComposeProjectDashboard, CONTAINER_STATS_POLL_MS, ContainerDashboard } from "./dashboard";
const ok = (data: DockerContainerStats) => ({ status: "ok" as const, data });
function makeStats(cpuPerc: string): DockerContainerStats {
return {
cpuPerc,
memUsage: "128MiB / 2GiB",
memPerc: "6.25%",
netIo: "2.4MB / 980kB",
blockIo: "12MB / 4.1MB",
pids: "17",
};
}
const runningContainer: DockerContainer = {
id: "db-1",
name: "shop-db-1",
image: "postgres:16",
command: "postgres",
state: "running",
status: "Up 15 minutes",
ports: "",
createdAt: "2026-04-20T05:00:00Z",
composeProject: "shop",
composeService: "db",
composeWorkingDir: "/work/shop",
composeFiles: ["/work/shop/docker-compose.yml"],
mounts: [],
networks: [],
};
const stoppedContainer: DockerContainer = {
...runningContainer,
id: "api-1",
name: "shop-api-1",
state: "exited",
status: "Exited (0) 2 minutes ago",
composeService: "api",
};
const snapshot: DockerSnapshot = {
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: null },
executable: "/usr/bin/docker",
containers: [runningContainer, stoppedContainer],
images: [],
volumes: [],
networks: [],
errors: [],
};
beforeEach(() => {
vi.useFakeTimers();
backend.stats.mockReset();
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.useRealTimers();
});
describe("live container stats polling", () => {
it("auto-refreshes Compose running services every 3s while visible and pauses when hidden", async () => {
let sample = 0;
backend.stats.mockImplementation(async (_ep, id: string) => {
sample += 1;
return ok(makeStats(`${sample * 5}.00%:${id}`));
});
const { rerender } = render(
<ToolWindowShownProvider value={true}>
<ComposeProjectDashboard
conn="default"
project="shop"
containers={[runningContainer, stoppedContainer]}
snapshot={snapshot}
/>
</ToolWindowShownProvider>,
);
await act(async () => {
await Promise.resolve();
});
expect(backend.stats).toHaveBeenCalledTimes(1);
expect(backend.stats).toHaveBeenLastCalledWith({ kind: "default" }, "db-1");
expect(screen.getByText("5.00%:db-1")).toBeInTheDocument();
// Advances 3s (`top` default interval) and refreshes automatically without clicking Refresh.
await act(async () => {
await vi.advanceTimersByTimeAsync(CONTAINER_STATS_POLL_MS);
});
expect(backend.stats).toHaveBeenCalledTimes(2);
expect(screen.getByText("10.00%:db-1")).toBeInTheDocument();
// Pauses while the document is hidden and resumes immediately when visible again.
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
act(() => {
document.dispatchEvent(new Event("visibilitychange"));
});
await act(async () => {
await vi.advanceTimersByTimeAsync(CONTAINER_STATS_POLL_MS * 3);
});
expect(backend.stats).toHaveBeenCalledTimes(2);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
await act(async () => {
document.dispatchEvent(new Event("visibilitychange"));
await Promise.resolve();
});
expect(backend.stats).toHaveBeenCalledTimes(3);
expect(screen.getByText("15.00%:db-1")).toBeInTheDocument();
// Stops polling when the Services tool window is hidden.
rerender(
<ToolWindowShownProvider value={false}>
<ComposeProjectDashboard
conn="default"
project="shop"
containers={[runningContainer, stoppedContainer]}
snapshot={snapshot}
/>
</ToolWindowShownProvider>,
);
await act(async () => {
await vi.advanceTimersByTimeAsync(CONTAINER_STATS_POLL_MS * 3);
});
expect(backend.stats).toHaveBeenCalledTimes(3);
});
it("auto-refreshes ContainerDashboard without overlapping slow stats calls", async () => {
let resolvePending: ((v: ReturnType<typeof ok>) => void) | undefined;
backend.stats
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolvePending = resolve;
}),
)
.mockImplementationOnce(async () => ok(makeStats("22.50%")));
render(<ContainerDashboard conn="default" container={runningContainer} snapshot={snapshot} inspectText={null} />);
expect(backend.stats).toHaveBeenCalledTimes(1);
// Slow first sample (4.5s > 3s): no overlapping second call starts while in flight.
await act(async () => {
await vi.advanceTimersByTimeAsync(4500);
});
expect(backend.stats).toHaveBeenCalledTimes(1);
await act(async () => {
resolvePending!(ok(makeStats("9.00%")));
await Promise.resolve();
});
expect(screen.getByText("9.00%")).toBeInTheDocument();
// Next sample runs 3s after the previous sample completed.
await act(async () => {
await vi.advanceTimersByTimeAsync(CONTAINER_STATS_POLL_MS);
});
expect(backend.stats).toHaveBeenCalledTimes(2);
expect(screen.getByText("22.50%")).toBeInTheDocument();
});
});
+19 -1
Переглянути файл
@@ -59,6 +59,7 @@ import {
VolumeDashboard,
} from "./dashboard";
import { openContainerLogInEditor } from "./logEditor";
import { hasComposeSource, jumpToComposeProjectSource, jumpToContainerComposeSource } from "./composeSource";
import {
canRemove,
canRestart,
@@ -467,7 +468,12 @@ function DockerDetail({ item }: { item: ServiceTreeItem }) {
if (node.kind === "compose") {
return (
<div className={styles.detailPane}>
<ComposeProjectDashboard conn={parsed.conn} project={node.project} containers={node.containers} />
<ComposeProjectDashboard
conn={parsed.conn}
project={node.project}
containers={node.containers}
snapshot={snapshot}
/>
</div>
);
}
@@ -583,6 +589,18 @@ export const dockerProvider: ServiceProviderContribution = {
const r = registryOf(item.key);
if (r) openRegistryDialog(r);
},
jumpToSource: (item) => {
const t = resolveTarget(item.key);
if (t?.node.kind === "container" && hasComposeSource(t.node.container)) {
void jumpToContainerComposeSource(t.node.container);
return;
}
if (t?.node.kind === "compose" && t.node.containers[0] && hasComposeSource(t.node.containers[0])) {
void jumpToComposeProjectSource(t.node.project, t.node.containers);
return;
}
dockerProvider.activate?.(item);
},
detail: DockerDetail,
banner: DockerTaskBanner,
addMenu: () => [
+17
Переглянути файл
@@ -37,6 +37,7 @@ import { gutterActions, registerDockerRunTypes } from "./runTypes";
import { ServicesDialogHost } from "./dialogs";
import { dockerProvider, selectedTarget } from "./docker";
import { DOCKER_LOG_EDITOR_KIND, DockerLogEditor, dockerLogEditorTitle, openContainerLogInEditor } from "./logEditor";
import { hasComposeSource, jumpToComposeProjectSource, jumpToContainerComposeSource } from "./composeSource";
import {
canRemove,
canStart,
@@ -235,6 +236,22 @@ export function activate(): () => void {
if (t?.node.kind === "container") openContainerLogInEditor(t.conn, t.node.container);
},
},
{
id: "docker.jumpToSource",
title: "Jump to Source",
category: "Docker",
icon: "autoscroll-to-source",
when: PROJECT,
run: () => {
const t = selectedTarget();
if (t?.node.kind === "container" && hasComposeSource(t.node.container)) {
return jumpToContainerComposeSource(t.node.container);
}
if (t?.node.kind === "compose" && t.node.containers[0] && hasComposeSource(t.node.containers[0])) {
return jumpToComposeProjectSource(t.node.project, t.node.containers);
}
},
},
{
id: "docker.showProcesses",
title: "Show Container Processes",
+14
Переглянути файл
@@ -206,6 +206,20 @@ export function containersUsingVolume(snap: DockerSnapshot, volume: DockerVolume
return snap.containers.filter((c) => c.mounts?.includes(volume.name));
}
/** Whether `volume` is an anonymous Docker volume rather than a named one. */
export function isAnonymousVolume(volume: DockerVolume): boolean {
if (volume.labels && "com.docker.volume.anonymous" in volume.labels) return true;
if (volume.labels?.["com.docker.compose.volume"]) return false;
return /^[0-9a-f]{64}$/i.test(volume.name);
}
/** Named volumes in `snap` created by Compose `project`. */
export function volumesInComposeProject(snap: DockerSnapshot, project: string): DockerVolume[] {
return snap.volumes
.filter((v) => v.composeProject === project && !isAnonymousVolume(v))
.sort((a, b) => a.name.localeCompare(b.name));
}
/** Containers in `snap` attached to `network`. */
export function containersInNetwork(snap: DockerSnapshot, network: DockerNetwork): DockerContainer[] {
return snap.containers.filter((c) => c.networks?.includes(network.name));
+22
Переглянути файл
@@ -7,6 +7,7 @@ import type { MenuItem } from "@/ui";
import { confirm, confirmChecked } from "@/workbench/messages";
import { promptText } from "./dialogs";
import { openContainerLogInEditor } from "./logEditor";
import { hasComposeSource, jumpToComposeProjectSource, jumpToContainerComposeSource } from "./composeSource";
import { isRunning, nodeContainers, nodeLabel, shortId, type DockerTarget, type ServiceNode } from "./model";
import {
busyOp,
@@ -235,6 +236,17 @@ export function nodeMenu(t: DockerTarget): MenuItem[] {
{ label: "Restart", icon: "rerun", run: () => void restart(t) },
);
}
if (n.kind === "compose" && n.containers[0] && hasComposeSource(n.containers[0])) {
items.push(
{ kind: "separator" },
{
label: "Jump to Source",
icon: "autoscroll-to-source",
shortcut: "F4",
run: () => void jumpToComposeProjectSource(n.project, n.containers),
},
);
}
if (n.kind === "container") {
const running = isRunning(n.container);
items.push(
@@ -248,6 +260,16 @@ export function nodeMenu(t: DockerTarget): MenuItem[] {
},
{ kind: "separator" },
{ label: "Dashboard", icon: "layout", run: () => showDetail("dashboard") },
...(hasComposeSource(n.container)
? [
{
label: "Jump to Source",
icon: "autoscroll-to-source",
shortcut: "F4",
run: () => void jumpToContainerComposeSource(n.container),
},
]
: []),
{ label: "Show Log", icon: "file-log", run: () => showDetail("log") },
{
label: "Open Log in Editor",
+265
Переглянути файл
@@ -34,6 +34,7 @@ import {
findImageForContainer,
findNode,
imageTagsForId,
isAnonymousVolume,
isUntaggedImage,
nodeDetail,
nodeIcon,
@@ -41,11 +42,13 @@ import {
parseTreeKey,
rootNodes,
treeKey,
volumesInComposeProject,
type ServiceNode,
} from "./model";
import {
bytesToUnits,
formatCreatedDetailed,
formatDockerCommand,
parseContainerInspect,
parseImageInspect,
parseNetworkInspect,
@@ -56,6 +59,12 @@ import {
unitsToBytes,
} from "./dashboard";
import { endpointFrom, sshConfigForUrl, sshConfigUrl } from "./dialogs";
import {
hasComposeSource,
locateComposeServiceCommand,
pickComposeCommandLocation,
resolveComposeFilePaths,
} from "./composeSource";
import { dockerItems } from "./docker";
import { setDockerFilters, useServices } from "./store";
import { addServiceMenu, expandableKeys, indexTree, setProviderRoots, useServicesTree } from "./tree";
@@ -447,6 +456,55 @@ describe("phase 1: filters, cross-references and dashboard parsers", () => {
"shop-db-1",
"shop-api-1",
]);
const anonHex = "37cc33a7d603260a82a378d7d3eeb835b748b5712614e2e5b4a3d6572f5e1e71";
const snapWithComposeVolumes: DockerSnapshot = {
...richSnapshot,
volumes: [
{
name: "shop_redis",
driver: "local",
mountpoint: "/var/lib/docker/volumes/shop_redis/_data",
composeProject: "shop",
labels: { "com.docker.compose.project": "shop", "com.docker.compose.volume": "redis" },
},
...richSnapshot.volumes,
{
name: anonHex,
driver: "local",
mountpoint: `/var/lib/docker/volumes/${anonHex}/_data`,
composeProject: "shop",
labels: { "com.docker.volume.anonymous": "" },
},
{
name: anonHex.replace(/^37/, "aa"),
driver: "local",
mountpoint: "/var/lib/docker/volumes/legacy/_data",
composeProject: "shop",
},
{
name: "other_data",
driver: "local",
mountpoint: "/var/lib/docker/volumes/other_data/_data",
composeProject: "other",
labels: { "com.docker.compose.project": "other", "com.docker.compose.volume": "data" },
},
{
name: "standalone_vol",
driver: "local",
mountpoint: "/var/lib/docker/volumes/standalone_vol/_data",
composeProject: null,
},
],
};
expect(isAnonymousVolume(snapWithComposeVolumes.volumes[0]!)).toBe(false);
expect(isAnonymousVolume(snapWithComposeVolumes.volumes[2]!)).toBe(true);
expect(isAnonymousVolume(snapWithComposeVolumes.volumes[3]!)).toBe(true);
expect(volumesInComposeProject(snapWithComposeVolumes, "shop").map((v) => v.name)).toEqual([
"shop_pgdata",
"shop_redis",
]);
expect(volumesInComposeProject(snapWithComposeVolumes, "missing")).toEqual([]);
});
it("parses units, usage pairs, timestamps, ports, layers and inspect payloads", () => {
@@ -724,3 +782,210 @@ describe("docker compose detection and targets", () => {
expect(svcDecl?.line).toBe(8);
});
});
describe("formatDockerCommand", () => {
it("returns null when entrypoint, cmd, and fallback are empty", () => {
expect(formatDockerCommand([], [])).toBeNull();
expect(formatDockerCommand([], [], " \n ")).toBeNull();
});
it("keeps simple single-line entrypoint and cmd compact on one line", () => {
const formatted = formatDockerCommand(["docker-entrypoint.sh"], ["postgres", "-c", "max_connections=200"]);
expect(formatted).toEqual({
preview: "docker-entrypoint.sh postgres -c max_connections=200",
entrypoint: "docker-entrypoint.sh",
args: "postgres -c max_connections=200",
fullText: "docker-entrypoint.sh postgres -c max_connections=200",
copyText: "docker-entrypoint.sh postgres -c max_connections=200",
lineCount: 1,
});
});
it("separates multi-line shell entrypoints from command arguments and builds a single-line preview", () => {
const script = [
"mkdir -p /persist/slots",
"while true; do",
" if flock -n 99; then break; fi",
"done",
'exec /entrypoint.sh "$@"',
"",
].join("\n");
const formatted = formatDockerCommand(
["/bin/bash", "-ec", script, "--"],
["./bin/Runner.Listener", "run", "--startuptype", "service"],
)!;
expect(formatted.preview).toBe(
"/bin/bash -ec 'mkdir -p /persist/slots ↵ while true; do ↵ if flock -n 99; then break; fi ↵ done ↵ exec /entrypoint.sh \"$@\"' -- ./bin/Runner.Listener run --startuptype service",
);
expect(formatted.entrypoint).toBe(
[
"/bin/bash -ec '",
"mkdir -p /persist/slots",
"while true; do",
" if flock -n 99; then break; fi",
"done",
'exec /entrypoint.sh "$@"',
"' --",
].join("\n"),
);
expect(formatted.args).toBe("./bin/Runner.Listener run --startuptype service");
expect(formatted.lineCount).toBe(7);
expect(formatted.copyText).toBe(`${formatted.entrypoint} ${formatted.args}`);
});
it("quotes empty tokens and embedded single quotes and handles multi-line fallback strings", () => {
const quoted = formatDockerCommand(["sh", "-c", "echo 'hi'", ""], [])!;
expect(quoted.entrypoint).toBe("sh -c 'echo '\\''hi'\\''' ''");
expect(quoted.args).toBe("");
expect(quoted.lineCount).toBe(1);
const fallback = formatDockerCommand([], [], "set -e\r\n npm start\r\n")!;
expect(fallback.preview).toBe("set -e ↵ npm start");
expect(fallback.fullText).toBe("set -e\n npm start");
expect(fallback.lineCount).toBe(2);
});
});
describe("composeSource", () => {
it("resolves absolute, relative, Windows, and default Compose file paths", () => {
expect(hasComposeSource({ composeProject: "shop", composeWorkingDir: "/work/shop", composeFiles: [] })).toBe(true);
expect(hasComposeSource({ composeProject: null, composeWorkingDir: null, composeFiles: [] })).toBe(false);
expect(
resolveComposeFilePaths(["./compose.yaml", "/work/shop/compose.override.yaml", "compose.yaml"], "/work/shop/"),
).toEqual(["/work/shop/compose.yaml", "/work/shop/compose.override.yaml"]);
expect(resolveComposeFilePaths(["docker\\compose.yml"], null, "C:\\repo")).toEqual(["C:/repo/docker/compose.yml"]);
expect(resolveComposeFilePaths([], "/work/shop")).toEqual([
"/work/shop/compose.yaml",
"/work/shop/compose.yml",
"/work/shop/docker-compose.yaml",
"/work/shop/docker-compose.yml",
]);
});
it("locates inline commands, block scalars, block sequences, entrypoints, and service fallbacks", () => {
const compose = [
"services:",
" postgres:",
" image: postgres:16",
" github-runner:",
" image: myoung34/github-runner:latest",
" entrypoint:",
" - /bin/bash",
" - -ec",
" - |",
" mkdir -p /persist/slots",
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
" worker:",
" image: python:3.12",
" entrypoint: |",
" # Initialize worker environment",
" python -m app.worker",
" compact-seq:",
" command:",
" - |",
" npm run start",
"",
].join("\n");
// Service without command or entrypoint falls back to the service declaration
expect(locateComposeServiceCommand(compose, "postgres")).toEqual({
kind: "service",
line: 1,
col: 2,
});
// Service with both entrypoint and command lands on command's value
expect(locateComposeServiceCommand(compose, "github-runner")).toEqual({
kind: "command",
line: 10,
col: 13,
});
// Service with only a literal block-scalar entrypoint lands on the first script line (preserving `#` comments)
expect(locateComposeServiceCommand(compose, "worker")).toEqual({
kind: "entrypoint",
line: 14,
col: 6,
});
// Compact sequence item using `- |` lands on the first script line inside the item
expect(locateComposeServiceCommand(compose, "compact-seq")).toEqual({
kind: "command",
line: 19,
col: 6,
});
// The service target always lands on the declaration
expect(locateComposeServiceCommand(compose, "github-runner", "service")).toEqual({
kind: "service",
line: 3,
col: 2,
});
expect(locateComposeServiceCommand(compose, "missing")).toBeNull();
expect(locateComposeServiceCommand(compose, null)).toEqual({ kind: "services", line: 0, col: 0 });
});
it("gives later override files precedence when resolving multi-file Compose commands", () => {
const base = [
"services:",
" api:",
" image: node:22",
" command: npm run start",
" worker:",
" image: node:22",
" command: node worker.js",
" db:",
" image: postgres:16",
].join("\n");
const override = [
"services:",
" api:",
" ports:",
' - "3000:3000"',
" worker:",
" command: npm run worker:dev",
].join("\n");
const files = [
{ path: "/work/compose.yaml", text: base },
{ path: "/work/compose.override.yaml", text: override },
];
// Override does not redefine `api.command`, so base file's `command` wins
expect(pickComposeCommandLocation(files, "api")).toEqual({
path: "/work/compose.yaml",
kind: "command",
line: 3,
col: 13,
});
// Override redefines `worker.command`, so override file's `command` wins
expect(pickComposeCommandLocation(files, "worker")).toEqual({
path: "/work/compose.override.yaml",
kind: "command",
line: 5,
col: 13,
});
// Neither file defines command/entrypoint for `db`, so base file's service declaration wins
// The service target prefers the first file that declares the service
expect(pickComposeCommandLocation(files, "worker", "service")).toEqual({
path: "/work/compose.yaml",
kind: "service",
line: 4,
col: 2,
});
expect(pickComposeCommandLocation(files, "db")).toEqual({
path: "/work/compose.yaml",
kind: "service",
line: 7,
col: 2,
});
});
});
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more