From 09d1f4a673e727c8a7dc5423f1cf596333de83b9 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 10:36:38 +0800 Subject: [PATCH 01/86] fix(linux): follow the caret with Fcitx on GNOME Wayland (#5747) With GTK_IM_MODULE=fcitx, Fcitx's GTK module only gets coordinates inside the window on Wayland, so with several monitors its candidate window opens on the wrong one. GNOME Wayland sessions now drop GTK_IM_MODULE when it names fcitx/fcitx5 and take input through the compositor (Mutter's text-input, served by Fcitx's IBus frontend), which places the candidates at the caret. KDE, other compositors, X11 sessions and an explicit GDK_BACKEND=x11 keep the module. Fixes #5176 --- src-tauri/src/linux_webkit.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src-tauri/src/linux_webkit.rs b/src-tauri/src/linux_webkit.rs index faa57d48b4..7217c1ada2 100644 --- a/src-tauri/src/linux_webkit.rs +++ b/src-tauri/src/linux_webkit.rs @@ -9,6 +9,10 @@ //! With IBus behind it, a dead key waiting for its second key makes WebKit collapse every //! new selection in the window to its caret (Select All, mouse drags, text fields) until a //! composition completes. GTK's own IBus module does not, so IBus sessions use that. +//! Fcitx's GTK module is the other way round on GNOME: Wayland gives it only coordinates +//! inside the window, so with several monitors its candidate window opens on the wrong +//! one. Through the compositor (Mutter hands text-input to Fcitx's IBus frontend) it +//! follows the caret, so GNOME Wayland sessions drop `GTK_IM_MODULE=fcitx`. const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER"; const DISABLE_EXPLICIT_SYNC: &str = "__NV_DISABLE_EXPLICIT_SYNC"; @@ -26,6 +30,17 @@ pub fn configure() { tracing::info!("Wayland with IBus: {IM_MODULE}=ibus"); unsafe { std::env::set_var(IM_MODULE, "ibus") }; } + if drop_fcitx_module(|k| std::env::var(k).ok()) { + tracing::info!("GNOME Wayland with Fcitx: input method through the compositor"); + unsafe { std::env::remove_var(IM_MODULE) }; + } +} + +/// GNOME on Wayland with Fcitx's GTK module selected (the session default `im-config` and +/// Fcitx's setup write). +fn drop_fcitx_module(var: impl Fn(&str) -> Option) -> bool { + let gnome = var("XDG_CURRENT_DESKTOP").is_some_and(|d| d.split(':').any(|d| d.eq_ignore_ascii_case("gnome"))); + gnome && var(IM_MODULE).is_some_and(|m| matches!(m.trim(), "fcitx" | "fcitx5")) && gdk_wayland(&var) } /// GTK 3's IBus input method module (`ibus-gtk3`), wherever the distribution keeps it. @@ -132,6 +147,22 @@ mod tests { assert!(!decide_im(&[gnome[0], gnome[1], ("GDK_BACKEND", "x11")], true)); } + fn env(vars: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + let vars = vars.to_vec(); + move |k| vars.iter().find(|(name, _)| *name == k).map(|(_, v)| v.to_string()) + } + + #[test] + fn gnome_wayland_drops_the_fcitx_module() { + let gnome = [("XDG_CURRENT_DESKTOP", "ubuntu:GNOME"), ("WAYLAND_DISPLAY", "wayland-0"), (IM_MODULE, "fcitx")]; + assert!(drop_fcitx_module(env(&gnome))); + assert!(drop_fcitx_module(env(&[gnome[0], gnome[1], (IM_MODULE, "fcitx5")]))); + assert!(!drop_fcitx_module(env(&[("XDG_CURRENT_DESKTOP", "KDE"), gnome[1], gnome[2]]))); + assert!(!drop_fcitx_module(env(&[gnome[0], gnome[2], ("DISPLAY", ":0")])), "X11 session"); + assert!(!drop_fcitx_module(env(&[gnome[0], gnome[1], gnome[2], ("GDK_BACKEND", "x11")]))); + assert!(!drop_fcitx_module(env(&[gnome[0], gnome[1], (IM_MODULE, "ibus")]))); + } + #[test] fn keeps_the_users_input_method_module() { let vars = [("WAYLAND_DISPLAY", "wayland-0"), ("XMODIFIERS", "@im=ibus"), (IM_MODULE, "wayland")]; From c6bb0b84ce27c9637ea3502d855b1c342da69d5e Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 10:51:29 +0800 Subject: [PATCH 02/86] test(agents): give the hidden session tab tests room for their own waits (#5759) hiddenWindow.test.tsx renders a long conversation twice per test and waits up to 10 s for it, but ran under the default 5 s test timeout, so on a loaded CI runner the test failed before its own wait gave up (Frontend failed on #5723 and #5736 this way). The suite now has a 30 s timeout. --- src/features/agents/hiddenWindow.test.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/features/agents/hiddenWindow.test.tsx b/src/features/agents/hiddenWindow.test.tsx index 3c07cb16e1..be92d0738a 100644 --- a/src/features/agents/hiddenWindow.test.tsx +++ b/src/features/agents/hiddenWindow.test.tsx @@ -113,7 +113,9 @@ afterEach(() => { vi.useRealTimers(); }); -describe("a kept-alive session tab that stays hidden", () => { +// Each test renders a long conversation twice and waits up to 10 s for it (`settle`, Find); on a +// loaded CI runner that can pass the default 5 s test timeout before the wait itself gives up. +describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () => { it("keeps an unsent edit to an earlier message even after returning to the end", async () => { const view = render(session(true)); await settle("Reply 59"); From 26f83240a75cf0d069c59bea1166f4e641b4263c Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 25 Nov 2026 11:57:14 +0900 Subject: [PATCH 03/86] fix(debug): find Java sources when jdtls has not imported the project (#5741) When jdtls has not imported a Maven project (e.g. a parent POM that does not resolve), Java debugging still stopped and stepped, but no frame had a file, so the editor never opened the stopped line. java-debug looks a frame's source up through jdtls and then in sourcePaths, which was never set; java-analyzer's debugger likewise falls back to sourcePaths for sibling modules. Java debug sessions (java-debug and java-analyzer, launch and attach) now pass the project's detected source and test roots as sourcePaths unless the configuration sets its own; jdtls still wins when it finds the source. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/debug.rs | 74 ++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 103e53657d..34ca50a496 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -114,6 +114,12 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide extra["__adapterJavaHome"] = serde_json::json!(runtime.home); config.extra_json = Some(extra.to_string()); } + if finds_java_sources(&config) + && let Ok(project) = host.project(window) + { + let roots = host.blocking(move || Ok(java_source_roots(&project))).await?; + config = add_java_source_paths(config, &roots); + } let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default(); let mut ruby_tools = Vec::new(); if config.adapter == "rdbg" && config.request == "launch" { @@ -308,6 +314,46 @@ fn start_java_attach_listener(mut config: LaunchConfig, windows: bool) -> Launch config } +/// The project's source and test roots, as the IDE detects them (no Maven / Gradle import needed). +fn java_source_roots(project: &crate::project::Project) -> Vec { + use ide_workspace::roots::RootKind; + project + .roots() + .roots + .iter() + .filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test)) + .map(|r| project.root.join(&r.path)) + .filter(|p| p.is_dir()) + .collect() +} + +/// Debuggers that look a frame's source up in `sourcePaths` when their own model has no file: +/// java-debug after jdtls (which has not imported a project whose Maven sync failed), and +/// java-analyzer after the module it debugs (whose sibling modules it does not load). +fn finds_java_sources(config: &LaunchConfig) -> bool { + matches!(config.adapter.as_str(), "java-debug" | ide_dap::adapter::JAVA_ANALYZER) +} + +/// Without a file for the stopped frame the editor cannot follow the execution point, so Java +/// sessions get every source root of the project. The user's own list wins. +fn add_java_source_paths(mut config: LaunchConfig, roots: &[PathBuf]) -> LaunchConfig { + if !finds_java_sources(&config) || roots.is_empty() { + return config; + } + let mut extra = match config.extra_json.as_deref().map(serde_json::from_str) { + None => serde_json::Map::new(), + Some(Ok(serde_json::Value::Object(extra))) => extra, + Some(_) => return config, + }; + if extra.get("sourcePaths").is_some_and(|v| !v.is_null()) { + return config; + } + let paths: Vec = roots.iter().map(|r| r.to_string_lossy().into_owned()).collect(); + extra.insert("sourcePaths".into(), paths.into()); + config.extra_json = Some(serde_json::Value::Object(extra).to_string()); + config +} + /// A JVM launched by java-debug writes what java-debug decodes its output as /// (see [`ide_core::output_encoding::java_debug_vm_args`]). fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig { @@ -737,6 +783,34 @@ mod tests { serde_json::from_str::(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone() } + #[test] + fn java_debug_sessions_look_up_sources_in_project_roots() { + let roots = [PathBuf::from("/p/src/main/java"), PathBuf::from("/p/src/test/java")]; + let source_paths = |config: &LaunchConfig| { + serde_json::from_str::(config.extra_json.as_deref().unwrap()).unwrap()["sourcePaths"] + .clone() + }; + for adapter in ["java-debug", ide_dap::adapter::JAVA_ANALYZER] { + for request in ["launch", "attach"] { + let config = add_java_source_paths(launch(adapter, request, serde_json::json!({"port": 5005})), &roots); + assert_eq!(source_paths(&config), serde_json::json!(["/p/src/main/java", "/p/src/test/java"])); + } + } + let mut bare = launch("java-debug", "attach", serde_json::json!({})); + bare.extra_json = None; + assert_eq!( + source_paths(&add_java_source_paths(bare, &roots)), + serde_json::json!(["/p/src/main/java", "/p/src/test/java"]) + ); + + let own = launch("java-debug", "launch", serde_json::json!({"sourcePaths": ["/elsewhere"]})); + assert_eq!(source_paths(&add_java_source_paths(own, &roots)), serde_json::json!(["/elsewhere"])); + let other = launch("debugpy", "launch", serde_json::json!({})); + assert_eq!(add_java_source_paths(other.clone(), &roots).extra_json, other.extra_json); + let none = launch("java-debug", "launch", serde_json::json!({})); + assert_eq!(add_java_source_paths(none.clone(), &[]).extra_json, none.extra_json); + } + #[test] fn java_debug_launches_on_windows_write_utf8() { let extra = From b9a0c66ca6d1aee689f9cfd1575d3ca1ca53c83c Mon Sep 17 00:00:00 2001 From: Mansur Akhmadi Date: Wed, 25 Nov 2026 09:58:31 +0700 Subject: [PATCH 04/86] feat(workbench): Hide Side Tool Windows action (#5744) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Window › Active Tool Window › Hide Side Tool Windows: hides every tool window on the active (else last active) window's side, un-maximizing that side and moving focus to the editor if it was in one of them. Available from Find Action and the native menu, with no default shortcut. IDEA keymap import and IdeaVim :action also map HideSideWindows and the existing Active Tool Window actions (HideActiveWindow, MaximizeToolWindow, JumpToLastWindow, ResizeToolWindow*). Closes #5743 Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com> --- src-tauri/src/menu.rs | 2 + src/platform/ideaActions.ts | 8 +++ src/platform/ideaKeymap.test.ts | 17 ++++++ src/platform/keymap.ts | 1 + src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + src/platform/keymaps/vscode-macos.ts | 1 + src/platform/locales/en.json | 1 + src/platform/locales/es.json | 1 + src/platform/locales/fr.json | 1 + src/platform/locales/ko.json | 1 + src/platform/locales/pl.json | 1 + src/platform/locales/pt.json | 1 + src/platform/locales/ru.json | 1 + src/platform/locales/text/es.json | 1 + src/platform/locales/text/fr.json | 1 + src/platform/locales/text/ko.json | 1 + src/platform/locales/text/pl.json | 1 + src/platform/locales/text/pt.json | 1 + src/platform/locales/text/ru.json | 1 + src/platform/locales/text/tr.json | 1 + src/platform/locales/text/zh-TW.json | 1 + src/platform/locales/text/zh.json | 1 + src/platform/locales/tr.json | 1 + src/platform/locales/zh-TW.json | 1 + src/platform/locales/zh.json | 1 + src/workbench/toolwindows/actions.ts | 10 ++++ src/workbench/toolwindows/store.test.ts | 71 +++++++++++++++++++++++- src/workbench/toolwindows/store.ts | 19 +++++++ 29 files changed, 149 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 1e7bf2845e..d9801ddb8f 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -825,6 +825,7 @@ pub fn spec(os: Os) -> Vec { "Active Tool Window", vec![ act("toolwindow.hideActive", "Hide Active Tool Window"), + act("toolwindow.hideSide", "Hide Side Tool Windows"), act("toolwindow.maximize", "Maximize Tool Window"), act("toolwindow.closeContent", "Close Active Tab"), sub( @@ -2392,6 +2393,7 @@ mod tests { && *id != "toolwindow.hideAll" && ![ "toolwindow.hideActive", + "toolwindow.hideSide", "toolwindow.maximize", "toolwindow.closeContent", "toolwindow.jumpToLast", diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index 5abff8ef8a..3488a1cfbe 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -114,6 +114,14 @@ export const IDEA_ACTIONS: Readonly> = { EditorGutterToggleGlobalStickyLines: "editor.toggleStickyLines", ActivateProjectToolWindow: "toolwindow.project", HideAllWindows: "toolwindow.hideAll", + HideActiveWindow: "toolwindow.hideActive", + HideSideWindows: "toolwindow.hideSide", + MaximizeToolWindow: "toolwindow.maximize", + JumpToLastWindow: "toolwindow.jumpToLast", + ResizeToolWindowLeft: "toolwindow.resizeLeft", + ResizeToolWindowRight: "toolwindow.resizeRight", + ResizeToolWindowUp: "toolwindow.resizeUp", + ResizeToolWindowDown: "toolwindow.resizeDown", "Vcs.QuickListPopupAction": "vcs.operations", CheckinProject: "vcs.commit", "Vcs.Push": "vcs.push", diff --git a/src/platform/ideaKeymap.test.ts b/src/platform/ideaKeymap.test.ts index 6caed15267..681dcd0386 100644 --- a/src/platform/ideaKeymap.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -110,6 +110,23 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.unknownActions).toEqual([]); }); + it("maps the Active Tool Window actions", () => { + const k = parseIdeaKeymap( + ``, + ); + expect(k.overrides).toMatchObject({ + "toolwindow.hideSide": [normalizeBinding("Ctrl+Alt+Shift+F12")], + "toolwindow.hideActive": [normalizeBinding("Alt+Escape")], + "toolwindow.maximize": [normalizeBinding("Ctrl+Alt+M")], + "toolwindow.jumpToLast": [normalizeBinding("Alt+F12")], + "toolwindow.resizeLeft": [normalizeBinding("Ctrl+Alt+Left")], + "toolwindow.resizeRight": [normalizeBinding("Ctrl+Alt+Right")], + "toolwindow.resizeUp": [normalizeBinding("Ctrl+Alt+Up")], + "toolwindow.resizeDown": [normalizeBinding("Ctrl+Alt+Down")], + }); + expect(k.unknownActions).toEqual([]); + }); + it("rejects other XML", () => { expect(() => parseIdeaKeymap("")).toThrow(/keymap/); }); diff --git a/src/platform/keymap.ts b/src/platform/keymap.ts index f5aab4e224..b58b86541b 100644 --- a/src/platform/keymap.ts +++ b/src/platform/keymap.ts @@ -666,6 +666,7 @@ export const FORWARDABLE_ACTIONS: ReadonlySet = new Set([ "toolwindow.debug", "toolwindow.hideActive", "toolwindow.hideAll", + "toolwindow.hideSide", "toolwindow.jumpToLast", "toolwindow.focusEditor", "toolwindow.maximize", diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index d773f8184f..8654accf83 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -268,6 +268,7 @@ export const intellijMacos: Record = { "layout.restoreDefault": [], "toolwindow.jumpToLast": ["F12"], "toolwindow.hideActive": ["Shift+Escape"], + "toolwindow.hideSide": [], "toolwindow.focusEditor": ["Escape"], // View › Appearance › Enter / Exit Distraction Free Mode: unbound, as in IDEA // (ToggleDistractionFreeMode has no default). ⌃⌘D is macOS's system-wide diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 5d727476ef..f4e62622d9 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -265,6 +265,7 @@ export const intellijWindows: Record = { "layout.restoreDefault": [], "toolwindow.jumpToLast": ["F12"], "toolwindow.hideActive": ["Shift+Escape"], + "toolwindow.hideSide": [], "toolwindow.focusEditor": ["Escape"], "editor.toggleZen": [], "editor.toggleLineNumbers": [], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index ebc0894f01..2afa8023be 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -292,6 +292,7 @@ export const vscodeMacos: Record = { "toolwindow.maximize": [], "toolwindow.jumpToLast": [], "toolwindow.hideActive": ["Meta+J"], + "toolwindow.hideSide": [], "toolwindow.focusEditor": ["Escape"], // Build (Terminal › Run Build Task) diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json index 2a75a34951..dfb57f1d79 100644 --- a/src/platform/locales/en.json +++ b/src/platform/locales/en.json @@ -481,6 +481,7 @@ "menu.layout.delete": "Delete Layout…", "menu.activeToolWindow": "Active Tool Window", "menu.toolwindow.hideActive": "Hide Active Tool Window", + "menu.toolwindow.hideSide": "Hide Side Tool Windows", "menu.toolwindow.maximize": "Maximize Tool Window", "menu.toolwindow.closeContent": "Close Active Tab", "menu.toolwindow.jumpToLast": "Jump to Last Tool Window", diff --git a/src/platform/locales/es.json b/src/platform/locales/es.json index 8f2b4ad219..e09865472c 100644 --- a/src/platform/locales/es.json +++ b/src/platform/locales/es.json @@ -400,6 +400,7 @@ "menu.layout.delete": "Eliminar diseño…", "menu.activeToolWindow": "Ventana de herramientas activa", "menu.toolwindow.hideActive": "Ocultar ventana de herramientas activa", + "menu.toolwindow.hideSide": "Ocultar ventanas de herramientas laterales", "menu.toolwindow.maximize": "Maximizar ventana de herramientas", "menu.toolwindow.closeContent": "Cerrar pestaña activa", "menu.toolwindow.jumpToLast": "Ir a la última ventana de herramientas", diff --git a/src/platform/locales/fr.json b/src/platform/locales/fr.json index 9b1ef17020..29829667bb 100644 --- a/src/platform/locales/fr.json +++ b/src/platform/locales/fr.json @@ -398,6 +398,7 @@ "menu.layout.delete": "Supprimer la disposition…", "menu.activeToolWindow": "Fenêtre d'outil active", "menu.toolwindow.hideActive": "Masquer la fenêtre d'outil active", + "menu.toolwindow.hideSide": "Masquer les fenêtres d'outils latérales", "menu.toolwindow.maximize": "Agrandir la fenêtre d'outil", "menu.toolwindow.closeContent": "Fermer l'onglet actif", "menu.toolwindow.jumpToLast": "Aller à la dernière fenêtre d'outil", diff --git a/src/platform/locales/ko.json b/src/platform/locales/ko.json index 33c977f515..8bda431d39 100644 --- a/src/platform/locales/ko.json +++ b/src/platform/locales/ko.json @@ -406,6 +406,7 @@ "menu.layout.delete": "레이아웃 삭제…", "menu.activeToolWindow": "활성 도구 창", "menu.toolwindow.hideActive": "활성 도구 창 숨기기", + "menu.toolwindow.hideSide": "측면 도구 창 숨기기", "menu.toolwindow.maximize": "도구 창 최대화", "menu.toolwindow.closeContent": "활성 탭 닫기", "menu.toolwindow.jumpToLast": "마지막 도구 창으로 이동", diff --git a/src/platform/locales/pl.json b/src/platform/locales/pl.json index 8564dd1732..0f4962f89a 100644 --- a/src/platform/locales/pl.json +++ b/src/platform/locales/pl.json @@ -400,6 +400,7 @@ "menu.layout.delete": "Usuń układ…", "menu.activeToolWindow": "Aktywne okno narzędziowe", "menu.toolwindow.hideActive": "Ukryj aktywne okno narzędziowe", + "menu.toolwindow.hideSide": "Ukryj boczne okna narzędziowe", "menu.toolwindow.maximize": "Maksymalizuj okno narzędziowe", "menu.toolwindow.closeContent": "Zamknij aktywną kartę", "menu.toolwindow.jumpToLast": "Przejdź do ostatniego okna narzędziowego", diff --git a/src/platform/locales/pt.json b/src/platform/locales/pt.json index 78e092c5a4..7ee11db657 100644 --- a/src/platform/locales/pt.json +++ b/src/platform/locales/pt.json @@ -397,6 +397,7 @@ "menu.layout.delete": "Excluir layout…", "menu.activeToolWindow": "Janela de ferramentas ativa", "menu.toolwindow.hideActive": "Ocultar janela de ferramentas ativa", + "menu.toolwindow.hideSide": "Ocultar janelas de ferramentas laterais", "menu.toolwindow.maximize": "Maximizar janela de ferramentas", "menu.toolwindow.closeContent": "Fechar aba ativa", "menu.toolwindow.jumpToLast": "Ir para a última janela de ferramentas", diff --git a/src/platform/locales/ru.json b/src/platform/locales/ru.json index 0846729ac9..fa7bc1a42e 100644 --- a/src/platform/locales/ru.json +++ b/src/platform/locales/ru.json @@ -480,6 +480,7 @@ "menu.layout.delete": "Удалить макет…", "menu.activeToolWindow": "Активное окно инструментов", "menu.toolwindow.hideActive": "Скрыть активное окно инструментов", + "menu.toolwindow.hideSide": "Скрыть боковые окна инструментов", "menu.toolwindow.maximize": "Развернуть окно инструментов", "menu.toolwindow.closeContent": "Закрыть активную вкладку", "menu.toolwindow.jumpToLast": "Перейти к последнему окну инструментов", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 756cdd75c9..258967eee7 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -979,6 +979,7 @@ "Hide": "Ocultar", "Hide Active Tool Window": "Ocultar ventana de herramientas activa", "Hide All Tool Windows": "Ocultar todas las ventanas de herramientas", + "Hide Side Tool Windows": "Ocultar ventanas de herramientas laterales", "Hide changes": "Ocultar cambios", "Hide Coverage": "Ocultar cobertura", "Hide Library Frames": "Ocultar marcos de bibliotecas", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index f98cd6fdbd..9a820f2d57 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -916,6 +916,7 @@ "Hide": "Masquer", "Hide Active Tool Window": "Masquer la fenêtre d'outil active", "Hide All Tool Windows": "Masquer toutes les fenêtres d'outils", + "Hide Side Tool Windows": "Masquer les fenêtres d'outils latérales", "Hide changes": "Masquer les modifications", "Hide Coverage": "Masquer la couverture", "Hide Library Frames": "Masquer les cadres de bibliothèque", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 5657f0c686..d5cf2a5d8d 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -1015,6 +1015,7 @@ "Hide": "숨기기", "Hide Active Tool Window": "활성 도구 창 숨기기", "Hide All Tool Windows": "모든 도구 창 숨기기", + "Hide Side Tool Windows": "측면 도구 창 숨기기", "Hide changes": "변경 사항 숨기기", "Hide Coverage": "커버리지 숨기기", "Hide Library Frames": "라이브러리 프레임 숨기기", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 24dae7ea01..85d967ca40 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -971,6 +971,7 @@ "Hide": "Ukryj", "Hide Active Tool Window": "Ukryj aktywne okno narzędziowe", "Hide All Tool Windows": "Ukryj wszystkie okna narzędziowe", + "Hide Side Tool Windows": "Ukryj boczne okna narzędziowe", "Hide changes": "Ukryj zmiany", "Hide Coverage": "Ukryj pokrycie kodu", "Hide Library Frames": "Ukryj ramki biblioteczne", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 41d2a03749..6b07faaa1a 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -971,6 +971,7 @@ "Hide": "Ocultar", "Hide Active Tool Window": "Ocultar janela de ferramentas ativa", "Hide All Tool Windows": "Ocultar todas as janelas de ferramentas", + "Hide Side Tool Windows": "Ocultar janelas de ferramentas laterais", "Hide changes": "Ocultar alterações", "Hide Coverage": "Ocultar cobertura", "Hide Library Frames": "Ocultar frames de biblioteca", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index be282c9860..14b6e9f57d 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -2038,6 +2038,7 @@ "Hide": "Скрыть", "Hide Active Tool Window": "Скрыть активное окно инструментов", "Hide All Tool Windows": "Скрыть все окна инструментов", + "Hide Side Tool Windows": "Скрыть боковые окна инструментов", "Hide changes": "Скрыть изменения", "Resize changes": "Изменить размер изменений", "Hide Coverage": "Скрыть покрытие", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 5c26b81e00..1d1c596bed 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -3768,6 +3768,7 @@ "Hide": "Gizle", "Hide Active Tool Window": "Etkin Araç Penceresini Gizle", "Hide All Tool Windows": "Tüm Araç Pencerelerini Gizle", + "Hide Side Tool Windows": "Yan Araç Pencerelerini Gizle", "Hide changes": "Değişiklikleri gizle", "Hide Coverage": "Kapsamayı Gizle", "Hide Library Frames": "Kütüphane Çerçevelerini Gizle", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index f2493fce25..69b7753d5b 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -1650,6 +1650,7 @@ "Hide": "隱藏", "Hide Active Tool Window": "隱藏活動工具視窗", "Hide All Tool Windows": "隱藏所有工具視窗", + "Hide Side Tool Windows": "隱藏側邊工具視窗", "Hide changes": "隱藏更改", "Resize changes": "調整更改面板寬度", "Hide Coverage": "隱藏覆蓋率", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index fa9b5f0ab4..4fa27c17ea 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2061,6 +2061,7 @@ "Hide": "隐藏", "Hide Active Tool Window": "隐藏活动工具窗口", "Hide All Tool Windows": "隐藏所有工具窗口", + "Hide Side Tool Windows": "隐藏侧边工具窗口", "Hide changes": "隐藏更改", "Resize changes": "调整更改面板宽度", "Hide Coverage": "隐藏覆盖率", diff --git a/src/platform/locales/tr.json b/src/platform/locales/tr.json index e6cbeeafc7..439d138176 100644 --- a/src/platform/locales/tr.json +++ b/src/platform/locales/tr.json @@ -475,6 +475,7 @@ "menu.layout.delete": "Düzeni Sil…", "menu.activeToolWindow": "Etkin Araç Penceresi", "menu.toolwindow.hideActive": "Etkin Araç Penceresini Gizle", + "menu.toolwindow.hideSide": "Yan Araç Pencerelerini Gizle", "menu.toolwindow.maximize": "Araç Penceresini Ekranı Kaplayacak Şekilde Büyüt", "menu.toolwindow.closeContent": "Etkin Sekmeyi Kapat", "menu.toolwindow.jumpToLast": "Son Araç Penceresine Git", diff --git a/src/platform/locales/zh-TW.json b/src/platform/locales/zh-TW.json index 5f60b63b98..7a387ef171 100644 --- a/src/platform/locales/zh-TW.json +++ b/src/platform/locales/zh-TW.json @@ -475,6 +475,7 @@ "menu.layout.delete": "刪除佈局…", "menu.activeToolWindow": "活動工具視窗", "menu.toolwindow.hideActive": "隱藏活動工具視窗", + "menu.toolwindow.hideSide": "隱藏側邊工具視窗", "menu.toolwindow.maximize": "最大化工具視窗", "menu.toolwindow.closeContent": "關閉活動分頁", "menu.toolwindow.jumpToLast": "跳轉到上一個工具視窗", diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json index 35b63a1206..7c446aca51 100644 --- a/src/platform/locales/zh.json +++ b/src/platform/locales/zh.json @@ -481,6 +481,7 @@ "menu.layout.delete": "删除布局…", "menu.activeToolWindow": "活动工具窗口", "menu.toolwindow.hideActive": "隐藏活动工具窗口", + "menu.toolwindow.hideSide": "隐藏侧边工具窗口", "menu.toolwindow.maximize": "最大化工具窗口", "menu.toolwindow.closeContent": "关闭活动标签页", "menu.toolwindow.jumpToLast": "跳转到上一个工具窗口", diff --git a/src/workbench/toolwindows/actions.ts b/src/workbench/toolwindows/actions.ts index 17b2d2bf41..051b651dd7 100644 --- a/src/workbench/toolwindows/actions.ts +++ b/src/workbench/toolwindows/actions.ts @@ -23,6 +23,7 @@ import { activateToolWindow, hideActiveToolWindow, hideAllToolWindows, + hideSideToolWindows, hideToolWindow, jumpToLastToolWindow, lastUsedToolWindow, @@ -247,6 +248,15 @@ export function installToolWindowActions(): () => void { when: "projectOpen && !popupOpen", run: hideActiveToolWindow, }, + { + // IDEA's HideSideWindows: every window on the active window's side. + id: "toolwindow.hideSide", + title: "Hide Side Tool Windows", + category: "Window", + keywords: ["tool window"], + when: "projectOpen && !popupOpen", + run: hideSideToolWindows, + }, { // Close Content, as IDEA (⌘W / Ctrl+F4 in a tool window): the selected closable tab, else the window. id: "toolwindow.closeContent", diff --git a/src/workbench/toolwindows/store.test.ts b/src/workbench/toolwindows/store.test.ts index 606dc614e0..07655e7909 100644 --- a/src/workbench/toolwindows/store.test.ts +++ b/src/workbench/toolwindows/store.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { getContext } from "@/platform/context"; +import { getContext, setContext } from "@/platform/context"; import { useProject } from "@/platform/project"; import { actionToggled, executeAction, getAction } from "@/platform/actions"; import { registerToolWindow } from "../contributions"; @@ -14,6 +14,7 @@ import { restoreSidesAfterNarrowWindow, hideActiveToolWindow, hideAllToolWindows, + hideSideToolWindows, hideToolWindow, hasStripeButton, removeFromStripe, @@ -108,6 +109,58 @@ describe("tool window semantics", () => { expect(isToolWindowVisible("project")).toBe(true); }); + it("hide side hides every window docked on the active window's side", () => { + moveToolWindow("structure", "left-split"); + showToolWindow("structure"); + showToolWindow("terminal"); + setFocusedToolWindow("structure"); + hideSideToolWindows(); + expect(useToolWindowLayout.getState().visible).toMatchObject({ + left: null, + "left-split": null, + bottom: "terminal", + }); + expect(useToolWindowLayout.getState().lastActive).toBeNull(); + // Again with the side empty and nothing active: nothing else is hidden. + hideSideToolWindows(); + expect(isToolWindowVisible("terminal")).toBe(true); + }); + + it("hide side falls back to the last active window, and does nothing when it is hidden", () => { + showToolWindow("terminal"); + showToolWindow("project"); + setFocusedToolWindow(null); + expect(useToolWindowLayout.getState().lastActive).toBe("project"); + hideSideToolWindows(); + expect(isToolWindowVisible("project")).toBe(false); + expect(isToolWindowVisible("terminal")).toBe(true); + showToolWindow("structure"); + hideToolWindow("structure"); + useToolWindowLayout.setState({ lastActive: "structure" }); + hideSideToolWindows(); + expect(isToolWindowVisible("terminal")).toBe(true); + }); + + it("hide side restores a maximized side and leaves another maximized side alone", () => { + showToolWindow("terminal"); + toggleMaximizeToolWindow("terminal"); + setFocusedToolWindow("terminal"); + hideSideToolWindows(); + expect(useToolWindowLayout.getState()).toMatchObject({ + maximized: null, + visible: { bottom: null, left: "project" }, + }); + showToolWindow("terminal"); + toggleMaximizeToolWindow("terminal"); + // The left side is covered by the maximized bottom: its window is not the one shown. + useToolWindowLayout.setState({ focused: null, lastActive: "project" }); + hideSideToolWindows(); + expect(useToolWindowLayout.getState()).toMatchObject({ + maximized: "bottom", + visible: { bottom: "terminal", left: "project" }, + }); + }); + it("restores the maximized side through the shared Hide All toggle", () => { showToolWindow("terminal"); toggleMaximizeToolWindow("terminal"); @@ -244,6 +297,22 @@ describe("tool window persistence", () => { }); describe("tool window actions", () => { + it("runs Hide Side Tool Windows on the active window", async () => { + const dispose = installToolWindowActions(); + try { + setContext("projectOpen", true); + showToolWindow("terminal"); + setFocusedToolWindow("project"); + expect(getAction("toolwindow.hideSide")?.title).toBe("Hide Side Tool Windows"); + await executeAction("toolwindow.hideSide"); + expect(isToolWindowVisible("project")).toBe(false); + expect(isToolWindowVisible("terminal")).toBe(true); + } finally { + setContext("projectOpen", false); + dispose(); + } + }); + it("titles Hide All Tool Windows 'Restore Tool Windows' while it would restore them", async () => { const dispose = installToolWindowActions(); try { diff --git a/src/workbench/toolwindows/store.ts b/src/workbench/toolwindows/store.ts index 71a3c1dae9..04a6f35c34 100644 --- a/src/workbench/toolwindows/store.ts +++ b/src/workbench/toolwindows/store.ts @@ -709,6 +709,25 @@ export function hideActiveToolWindow() { if (id) hideToolWindow(id); } +/** + * Hide Side Tool Windows (IDEA's HideSideWindows): hides both areas of the side the active + * (else last active) window is docked on. Nothing when that window isn't shown. + */ +export function hideSideToolWindows() { + const s = useToolWindowLayout.getState(); + const id = s.focused ?? s.lastActive; + const anchor = id && isToolWindowVisible(id) ? anchorOf(id) : undefined; + if (!anchor) return; + const side = windowsOn(anchor, s.visible); + const hadFocus = side.some((w) => s.focused === w || isFocusWithinToolWindow(w)); + update({ + visible: { ...s.visible, [anchor]: null, [`${anchor}-split`]: null }, + maximized: s.maximized === anchor ? null : s.maximized, + lastActive: s.lastActive && side.includes(s.lastActive) ? null : s.lastActive, + }); + if (hadFocus) focusEditor(); +} + export function setToolWindowSize(anchor: ToolWindowAnchor, px: number) { const s = useToolWindowLayout.getState(); const v = Math.round(px); From 707b6fe169e40a989a086325bdbb7ab7601ea31d Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Tue, 24 Nov 2026 19:01:14 -0800 Subject: [PATCH 05/86] feat(terminal): drag terminal tabs into editor groups and splits (#5734) Terminal tabs can be dragged from the Terminal tool window into any editor tab strip position, onto an editor pane or the empty editor area, or onto a pane edge to open a split, keeping the running session (PTY, processes, scrollback, focus). Splitting a terminal editor tab opens a fresh shell in the same working directory instead of showing one session in two panes (editor kinds can declare singleton + splitInput). Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- docs/en/guide/terminal.mdx | 4 +- docs/zh/guide/terminal.mdx | 4 +- e2e/terminal-ui.spec.ts | 110 ++++++++++++++- src/editor/core/controller.test.ts | 44 ++++++ src/editor/core/controller.ts | 151 ++++++++++++++++----- src/editor/core/model/tabs.ts | 2 +- src/editor/core/view/EditorArea.tsx | 19 ++- src/features/terminal/TerminalView.tsx | 7 +- src/features/terminal/cli.test.ts | 44 +++++- src/features/terminal/cli.ts | 40 +++++- src/features/terminal/cliKinds.test.tsx | 9 +- src/features/terminal/closeLastTab.test.ts | 9 +- src/features/terminal/index.ts | 10 +- src/features/terminal/runtime.ts | 1 + src/features/terminal/store.ts | 1 + src/ui/Tabs.test.tsx | 31 +++++ src/ui/Tabs.tsx | 12 +- src/ui/pointerDrag.ts | 12 +- src/workbench/contributions.ts | 54 ++++++-- 19 files changed, 482 insertions(+), 82 deletions(-) diff --git a/docs/en/guide/terminal.mdx b/docs/en/guide/terminal.mdx index e66bf314b9..b4bd4277dd 100644 --- a/docs/en/guide/terminal.mdx +++ b/docs/en/guide/terminal.mdx @@ -18,8 +18,8 @@ Showing an empty Terminal window opens a tab in the start directory (the project - **+** (**New Tab**) opens a tab with the default shell. - The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**. -- Right-click a tab for **Rename Session…**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it. -- Drag tabs to reorder them, or drop a tab on the edge of another group to split. +- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it. +- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends. diff --git a/docs/zh/guide/terminal.mdx b/docs/zh/guide/terminal.mdx index d2c7721364..918f5ea158 100644 --- a/docs/zh/guide/terminal.mdx +++ b/docs/zh/guide/terminal.mdx @@ -18,8 +18,8 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找 - **+**(**新建标签页**)用默认 Shell 打开一个标签页。 - **▾** 按钮(**更多终端选项**)包含 **新建终端标签页**、**新建预定义会话**(每个已安装的 Shell 一项,另有 **SSH 会话…**)、**向右拆分**、**向下拆分** 和 **设置**。 -- 右键标签页可以 **重命名会话…**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。 -- 拖动标签页可以调整顺序,拖到另一组的边缘则会拆分。 +- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。 +- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。 标签页名称优先用你设置的名字,其次是 Shell 报告的正在运行的程序名,否则就是 `本地`、`本地 (2)` 等默认名称。命令运行时标签上会显示转圈图标,会话结束后显示 **已退出** 或 **失败**。 diff --git a/e2e/terminal-ui.spec.ts b/e2e/terminal-ui.spec.ts index 63077309aa..cda2d13b73 100644 --- a/e2e/terminal-ui.spec.ts +++ b/e2e/terminal-ui.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from "./fixtures"; +import { expect, stubDesktop, test } from "./fixtures"; test("terminal output menu groups session, clipboard and split actions and opens Find", async ({ workbench: page }) => { await page.evaluate(async () => { @@ -360,3 +360,111 @@ test("terminal composition follows a drawn caret inside the session", async ({ w }) .toBe(true); }); + +test("dragging terminal tabs into editor strips and split edges preserves live sessions and scrollback", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(async () => { + const handlers = window.__ipc.handlers; + let id = 0; + const killed: number[] = []; + (window as unknown as { __killedPtys: number[] }).__killedPtys = killed; + handlers.term_default_shell = () => "/bin/zsh"; + handlers.term_available_shells = () => ["/bin/zsh"]; + handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id }); + handlers.term_resize = () => null; + handlers.term_write = () => null; + handlers.term_is_busy = () => false; + handlers.term_kill = (args: unknown) => { + killed.push((args as { id: number }).id); + return null; + }; + + const contributions = "/src/workbench/contributions.ts"; + const editor = (await import(contributions)).editorService(); + await editor.openFile("/dev/acme-api/App.tsx", { focus: false }); + await editor.openFile("/dev/acme-api/README.md", { focus: false }); + const store = "/src/workbench/toolwindows/store.ts"; + const layout = await import(store); + layout.setToolWindowSize("bottom", 240); + layout.showToolWindow("terminal", true); + }); + + const terminal = page.getByRole("region", { name: "Terminal", exact: true }); + await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused(); + + // Open a second terminal tab and write distinct output into both sessions. + await terminal.getByRole("button", { name: "New Tab", exact: true }).click(); + const termStrip = terminal.getByRole("tablist", { name: "Terminal sessions" }); + await expect(termStrip.getByRole("tab")).toHaveCount(2); + + await page.evaluate(async () => { + const store = "/src/features/terminal/store.ts"; + const rt = await import(store); + const [first, second] = rt.useTerminals.getState().tabs; + const s1 = rt.getSession(first!.session)!; + const s2 = rt.getSession(second!.session)!; + await new Promise((done) => s1.term.write("ALPHA-SESSION-OUTPUT\r\n", done)); + await new Promise((done) => s2.term.write("BETA-TEST-RUNNER\r\n", done)); + }); + + // 1) Drag "Local" into the editor tab strip between App.tsx and README.md. + const localTab = termStrip.getByRole("tab", { name: "Local", exact: true }); + const readmeTab = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "README.md" }); + const from1 = (await localTab.boundingBox())!; + const to1 = (await readmeTab.boundingBox())!; + await page.mouse.move(from1.x + from1.width / 2, from1.y + from1.height / 2); + await page.mouse.down(); + await page.mouse.move(to1.x + 6, to1.y + to1.height / 2, { steps: 8 }); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await page.screenshot({ + path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-strip-hover.png`, + animations: "disabled", + }); + await page.mouse.up(); + + const editorLists = page.getByRole("tablist", { name: "Editor tabs" }); + await expect(editorLists.first().getByRole("tab")).toHaveText(["App.tsx", "Local", "README.md"]); + await expect(termStrip.getByRole("tab")).toHaveCount(1); + + const editorArea = page.locator("[data-pane-id]"); + await expect(editorArea.locator(".xterm-rows")).toContainText("ALPHA-SESSION-OUTPUT"); + await expect(editorArea.locator(".xterm-helper-textarea")).toBeFocused(); + + // 2) Drag the remaining "Local (2)" onto the right edge of the editor pane to split it, hiding the empty tool window. + const local2Tab = termStrip.getByRole("tab", { name: "Local (2)", exact: true }); + const paneBox = (await editorArea.first().locator('[role="tabpanel"]').boundingBox())!; + const from2 = (await local2Tab.boundingBox())!; + await page.mouse.move(from2.x + from2.width / 2, from2.y + from2.height / 2); + await page.mouse.down(); + await page.mouse.move(paneBox.x + paneBox.width - 20, paneBox.y + paneBox.height / 2, { steps: 8 }); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await page.screenshot({ + path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-split-hover.png`, + animations: "disabled", + }); + await page.mouse.up(); + + await expect(terminal).toBeHidden(); + await expect(editorArea).toHaveCount(2); + await expect(editorArea.nth(1).locator(".xterm-rows")).toContainText("BETA-TEST-RUNNER"); + await expect(editorArea.nth(1).locator(".xterm-helper-textarea")).toBeFocused(); + + // 3) Resize the editor split divider and confirm both panes and the live PTY survive. + const widthBefore = (await editorArea.nth(1).boundingBox())!.width; + const divider = page.locator("[data-editor-area]").getByRole("separator"); + const divBox = (await divider.boundingBox())!; + await page.mouse.move(divBox.x + divBox.width / 2, divBox.y + divBox.height / 2); + await page.mouse.down(); + await page.mouse.move(divBox.x - 100, divBox.y + divBox.height / 2, { steps: 6 }); + await page.mouse.up(); + await expect.poll(async () => (await editorArea.nth(1).boundingBox())!.width).toBeGreaterThan(widthBefore + 50); + await expect(editorArea.nth(1).locator(".xterm-rows")).toContainText("BETA-TEST-RUNNER"); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await page.screenshot({ + path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-final.png`, + animations: "disabled", + }); + expect(await page.evaluate(() => (window as unknown as { __killedPtys: number[] }).__killedPtys)).toEqual([]); +}); diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index 533cb137f6..eb42d9d75f 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -804,6 +804,50 @@ describe("EditorController", () => { offWrapper(); } }); + + it("opens inputs at explicit strip indices or split edges and never clones singleton kinds", async () => { + let seq = 1; + const dispose = registerEditorKind({ + kind: "singleton-term", + component: () => null, + title: (i) => i.key, + singleton: true, + splitInput: () => ({ kind: "singleton-term", key: `singleton-term:${++seq}` }), + }); + try { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + await ctrl.openFile("/p/b.ts", { focus: false }); + const p1 = useTabs.getState().activePane; + + // Explicit strip index inserts between a.ts and b.ts. + const term1 = { kind: "singleton-term", key: "singleton-term:1" }; + await ctrl.openInput(term1, { pane: p1, index: 1, focus: false }); + expect(useTabs.getState().panes[p1]!.tabs.map((t) => t.input.key)).toEqual([ + "file:/p/a.ts", + "singleton-term:1", + "file:/p/b.ts", + ]); + + // Splitting a singleton tab opens `splitInput` in the new pane instead of duplicating the key. + ctrl.activate(p1, useTabs.getState().panes[p1]!.tabs[1]!.id, false); + ctrl.split(p1, "row"); + await vi.waitFor(() => expect(Object.keys(useTabs.getState().panes)).toHaveLength(2)); + const p2 = Object.keys(useTabs.getState().panes).find((id) => id !== p1)!; + expect(useTabs.getState().panes[p1]!.tabs.map((t) => t.input.key)).toContain("singleton-term:1"); + expect(useTabs.getState().panes[p2]!.tabs.map((t) => t.input.key)).toEqual(["singleton-term:2"]); + + // Re-opening an already open singleton at an edge moves it into the new split instead of duplicating it. + await ctrl.openInput(term1, { pane: p2, edge: "bottom", focus: false }); + const allTerm1 = Object.values(useTabs.getState().panes).flatMap((p) => + p.tabs.filter((t) => t.input.key === "singleton-term:1"), + ); + expect(allTerm1).toHaveLength(1); + } finally { + dispose(); + } + }); }); describe("editor action when clauses", () => { diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 00dd7f823b..57689185d4 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -1402,45 +1402,94 @@ export class EditorController implements SlotHost { const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle })); const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview; if (!activate && preview) return; + const kind = kinds.get(input.kind); let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null; if (!paneId) return; - if (o.side) { - const right = neighbourPane(s, paneId); - if (right) paneId = right; - else { - const split = splitPane(s, paneId, "row"); + const existingSingleton = kind?.singleton ? findTab(s, input.key, paneId) : null; + let tabId: string; + if (existingSingleton) { + tabId = existingSingleton.tab.id; + if (o.edge) { + const moved = moveTabToNewSplit(s, existingSingleton.paneId, tabId, paneId, o.edge); + if (moved) { + s = moved.state; + paneId = moved.paneId; + } else { + paneId = existingSingleton.paneId; + if (activate) s = activateTab(setActivePane(s, paneId), paneId, tabId); + } + } else if ((o.pane || o.side) && existingSingleton.paneId !== paneId) { + const target = o.side ? (neighbourPane(s, paneId) ?? paneId) : paneId; + if (target !== existingSingleton.paneId) { + s = moveTab( + s, + existingSingleton.paneId, + tabId, + target, + o.index ?? s.panes[target]?.tabs.length ?? 0, + o.pinned, + ); + paneId = target; + } else if (o.side) { + const moved = moveTabToNewSplit(s, existingSingleton.paneId, tabId, paneId, "right"); + if (moved) { + s = moved.state; + paneId = moved.paneId; + } + } + } else { + paneId = existingSingleton.paneId; + if (activate) s = activateTab(setActivePane(s, paneId), paneId, tabId); + } + if (!o.preview || !canPreview) s = promoteTab(s, paneId, tabId); + } else { + if (o.edge) { + const split = splitAtEdge(s, paneId, o.edge); s = split.state; paneId = split.paneId; - // The new pane starts with only the requested input. - const pane = s.panes[paneId]!; - s = { ...s, panes: { ...s.panes, [paneId]: { ...pane, tabs: [], active: null, mru: [] } } }; if (!activate) s = { ...s, activePane: useTabs.getState().activePane }; + } else if (o.side) { + const right = neighbourPane(s, paneId); + if (right) paneId = right; + else { + const split = splitPane(s, paneId, "row"); + s = split.state; + paneId = split.paneId; + // The new pane starts with only the requested input. + const pane = s.panes[paneId]!; + s = { ...s, panes: { ...s.panes, [paneId]: { ...pane, tabs: [], active: null, mru: [] } } }; + if (!activate) s = { ...s, activePane: useTabs.getState().activePane }; + } } - } - const found = findTab(s, input.key, paneId); - let tabId: string; - if (found && (!(o.side || o.pane) || found.paneId === paneId)) { - paneId = found.paneId; - if (activate) s = activateTab(setActivePane(s, paneId), paneId, found.tab.id); - if (!o.preview || !canPreview) s = promoteTab(s, paneId, found.tab.id); - tabId = found.tab.id; - if (activate && found.tab.input.data !== input.data && input.data !== undefined) - s = openTab(s, paneId, input, { - preview: o.preview && canPreview, + const found = findTab(s, input.key, paneId); + if (found && (!(o.side || o.pane || o.edge) || found.paneId === paneId)) { + paneId = found.paneId; + if (activate) s = activateTab(setActivePane(s, paneId), paneId, found.tab.id); + if (!o.preview || !canPreview) s = promoteTab(s, paneId, found.tab.id); + tabId = found.tab.id; + if (activate && found.tab.input.data !== input.data && input.data !== undefined) + s = openTab(s, paneId, input, { + preview: o.preview && canPreview, + activate, + }).state; + } else { + const tabs = editorPrefs().tabs; + const r = openTab(s, paneId, input, { + preview, + pinned: o.pinned, activate, - }).state; - } else { - const tabs = editorPrefs().tabs; - const r = openTab(s, paneId, input, { - preview, - activate, - preservePreview: !activate, - keepPreview: (t) => !isTextInput(t.input), - ...(tabs.openAtEnd ? { index: s.panes[paneId]?.tabs.length ?? 0 } : {}), - }); - s = r.state; - tabId = r.tabId; - if (tabs.sortAlphabetically) s = sortTabs(s, paneId, (t) => tabSortKey(t.input)); + preservePreview: !activate, + keepPreview: (t) => !isTextInput(t.input), + ...(o.index !== undefined + ? { index: o.index } + : tabs.openAtEnd + ? { index: s.panes[paneId]?.tabs.length ?? 0 } + : {}), + }); + s = r.state; + tabId = r.tabId; + if (tabs.sortAlphabetically && o.index === undefined) s = sortTabs(s, paneId, (t) => tabSortKey(t.input)); + } } if (o.selection) this.selectionRequests.set(tabId, Math.max(generation.sequence, this.selectionRequests.get(tabId) ?? 0)); @@ -1891,18 +1940,26 @@ export class EditorController implements SlotHost { keepTab(paneId: string, tabId: string) { this.apply((s) => (s.panes[paneId] ? promoteTab(s, paneId, tabId) : s)); } + private focusMovedTab(tabId: string) { + const slot = this.slots.get(tabId); + if (slot?.view) slot.focus(); + else if (slot) slot.wantsFocus = true; + else + requestAnimationFrame(() => { + if (this.activeTabOf()?.id === tabId) this.focus(); + }); + } /** Drag & drop; the tab keeps its id (and slot) when moved within a pane. */ moveTab(fromPane: string, tabId: string, toPane: string, index: number, pin?: boolean) { this.apply((s) => moveTab(s, fromPane, tabId, toPane, index, pin)); + this.focusMovedTab(tabId); } /** Drag & drop onto an editor edge: the tab moves into a new split on that side. */ moveTabToSplit(fromPane: string, tabId: string, targetPane: string, edge: SplitEdge) { const r = moveTabToNewSplit(useTabs.getState(), fromPane, tabId, targetPane, edge); if (!r) return; useTabs.setState(r.state, true); - const slot = this.slots.get(tabId); - if (slot?.view) slot.focus(); - else if (slot) slot.wantsFocus = true; + this.focusMovedTab(tabId); } /** Files dropped on an editor: opened in that pane, or in a new split at `edge`. */ async openFilesIn(paths: readonly string[], paneId: string, edge: SplitEdge | "center") { @@ -1944,6 +2001,19 @@ export class EditorController implements SlotHost { split(paneId: string, dir: "row" | "column") { const s = useTabs.getState(); const srcPane = s.panes[paneId]; + const active = srcPane?.tabs.find((t) => t.id === srcPane.active); + const kind = active ? useContributions.getState().editorKinds.get(active.input.kind) : undefined; + if (active && kind?.singleton) { + if (kind.splitInput) { + void Promise.resolve(kind.splitInput(active.input)).then((fresh) => { + if (!fresh || !useTabs.getState().panes[paneId]) return; + void this.openInput(fresh, { pane: paneId, edge: dir === "row" ? "right" : "bottom", focus: true }); + }); + } else if (srcPane && srcPane.tabs.length > 1) { + this.moveTabToSplit(paneId, active.id, paneId, dir === "row" ? "right" : "bottom"); + } + return; + } const srcSlot = srcPane?.active ? this.slots.get(srcPane.active) : undefined; const r = splitPane(s, paneId, dir); useTabs.setState(r.state, true); @@ -2058,6 +2128,17 @@ export class EditorController implements SlotHost { this.activate(paneId, tabId, false); return this.split(paneId, "row"); } + const kind = useContributions.getState().editorKinds.get(tab.input.kind); + if (kind?.singleton) { + if (kind.splitInput) { + void Promise.resolve(kind.splitInput(tab.input)).then((fresh) => { + if (fresh && useTabs.getState().panes[target]) void this.openInput(fresh, { pane: target, focus: true }); + }); + } else { + this.moveToOpposite(paneId, tabId); + } + return; + } const r = openTab(s, target, tab.input); useTabs.setState(r.state, true); void this.ensureSlot(r.tabId, { from: this.slots.get(tabId) }).then((slot) => { diff --git a/src/editor/core/model/tabs.ts b/src/editor/core/model/tabs.ts index a4ae711177..11071bf9f5 100644 --- a/src/editor/core/model/tabs.ts +++ b/src/editor/core/model/tabs.ts @@ -197,7 +197,7 @@ export function openTab( } else { const pins = pinnedCount(pane); let index: number; - if (tab.pinned) index = pins; + if (tab.pinned) index = opts.index !== undefined ? Math.max(0, Math.min(opts.index, pins)) : pins; else if (opts.index !== undefined) index = Math.max(pins, Math.min(opts.index, tabs.length)); else { const activeIdx = tabs.findIndex((t) => t.id === pane.active); diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 38c8e0b0b6..68c0fe6bab 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -27,6 +27,7 @@ import { EDITOR_TAB_MIME, acceptsEditorDrop, dropOnEditor, + editorDropAllowsSplit, getFileDecoration, prepareMenuGroups, textEditorWrapperFor, @@ -107,7 +108,7 @@ function EmptyEditorArea() { const el = ref.current; if (!el) return; return registerDropTarget(el, { - accepts: (type) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type), + accepts: (type, data) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type, data), over: (data) => setOver(data.type !== FILES_DRAG || droppedFiles(data.payload).length > 0), leave: () => setOver(false), drop: (data) => { @@ -119,7 +120,7 @@ function EmptyEditorArea() { return; } if (data.type !== EDITOR_TAB_MIME) { - dropOnEditor(data); + dropOnEditor(data, { paneId, zone: "center", index: 0 }); return; } const p = parseTabPayload(data.payload); @@ -301,10 +302,14 @@ function PaneView({ paneId }: { paneId: string }) { const strip = (offset: number, pin?: boolean): TabsDnd => ({ type: EDITOR_TAB_MIME, payload: (tabId) => JSON.stringify({ paneId, tabId }), + accepts: (data) => acceptsEditorDrop(data.type, data), onDrop: (raw, index) => { const p = parseTabPayload(raw); if (p) ctrl.moveTab(p.paneId, p.tabId, paneId, index + offset, pin); }, + onExternalDrop: (data, index) => { + dropOnEditor(data, { paneId, zone: "center", index: index + offset, pinned: pin }); + }, onDropOutside: dropOutside, }); return { all: strip(0), pinned: strip(0, true), rest: strip(pinnedCount, false) }; @@ -318,10 +323,13 @@ function PaneView({ paneId }: { paneId: string }) { if (!el) return; const zoneAt = (x: number, y: number) => dropZoneAt(x, y, el.getBoundingClientRect()); return registerDropTarget(el, { - accepts: (type) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type), + accepts: (type, data) => type === EDITOR_TAB_MIME || type === FILES_DRAG || acceptsEditorDrop(type, data), over: (data, x, y) => { if (data.type === FILES_DRAG) setDropZone(droppedFiles(data.payload).length ? zoneAt(x, y) : null); - else setDropZone(data.type === EDITOR_TAB_MIME ? zoneAt(x, y) : "center"); + else + setDropZone( + data.type === EDITOR_TAB_MIME || editorDropAllowsSplit(data.type, data) ? zoneAt(x, y) : "center", + ); }, leave: () => setDropZone(null), drop: (data, x, y) => { @@ -332,7 +340,8 @@ function PaneView({ paneId }: { paneId: string }) { return; } if (data.type !== EDITOR_TAB_MIME) { - dropOnEditor(data); + const target = useTabs.getState().panes[paneId]; + dropOnEditor(data, { paneId, zone, ...(zone === "center" ? { index: target?.tabs.length ?? 0 } : {}) }); return; } const p = parseTabPayload(data.payload); diff --git a/src/features/terminal/TerminalView.tsx b/src/features/terminal/TerminalView.tsx index f8bc7e6b5a..010012414f 100644 --- a/src/features/terminal/TerminalView.tsx +++ b/src/features/terminal/TerminalView.tsx @@ -50,15 +50,12 @@ import { type GroupLayout, type TerminalTab, } from "./store"; +import { TERMINAL_TAB_MIME } from "./cli"; import { openTerminalFind, TerminalFindBar } from "./FindBar"; import styles from "./Terminal.module.css"; const TAB_PREFIX = "openidea-terminal"; -/** - * Drag type of terminal tabs: dragging one reorders its group's strip or moves - * it to another group's, like IDEA's terminal tabs. - */ -const TAB_MIME = "application/x-openidea-terminal-tab"; +const TAB_MIME = TERMINAL_TAB_MIME; /** Session title and working directory, even when available space trims the label. */ function tabTooltip(tab: TerminalTab, sessions: Parameters[1]): string | undefined { diff --git a/src/features/terminal/cli.test.ts b/src/features/terminal/cli.test.ts index 59c518c5be..541a2e4a4c 100644 --- a/src/features/terminal/cli.test.ts +++ b/src/features/terminal/cli.test.ts @@ -3,11 +3,11 @@ * Start flow of a restored tab through the terminal runtime. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { cliData, cliInput, moveTerminalToEditor, startTab } from "./cli"; +import { CLI_KIND, cliData, cliInput, moveTerminalToEditor, splitCliTab, startTab } from "./cli"; const tabs = vi.hoisted(() => ({ state: { - tabs: [] as { id: string; session: string }[], + tabs: [] as { id: string; name?: string; session: string }[], activeTab: null as string | null, sessions: {} as Record, }, @@ -16,12 +16,16 @@ const runtime = vi.hoisted(() => ({ loaded: false, startCli: vi.fn(), adoptCli: vi.fn(), + cliSession: vi.fn(), detachTab: vi.fn(), + nextTabName: vi.fn((existing: readonly string[], base = "Local") => (existing.includes(base) ? `${base} (2)` : base)), + startDirectory: vi.fn((root: string) => root), tabTitle: vi.fn((_tab: unknown, _sessions: unknown) => "Local (2)"), useTerminals: { getState: () => tabs.state }, })); const editor = vi.hoisted(() => ({ openInput: vi.fn(async (_input?: unknown, _options?: unknown) => undefined), + openTabs: vi.fn(() => [] as { input: { kind: string; key: string; data?: unknown }; title: string }[]), })); const toolWindows = vi.hoisted(() => ({ hide: vi.fn() })); @@ -106,6 +110,42 @@ describe("Move to Editor", () => { expect(runtime.detachTab).not.toHaveBeenCalled(); expect(editor.openInput).not.toHaveBeenCalled(); }); + + it("forwards pane, split edge, insertion index and pin state for editor drops", async () => { + tabs.state.tabs = [{ id: "t1", session: "s1" }]; + runtime.detachTab.mockImplementationOnce(() => session); + await moveTerminalToEditor("t1", { paneId: "pane-2", zone: "bottom" }); + expect(editor.openInput).toHaveBeenLastCalledWith(expect.objectContaining({ kind: CLI_KIND }), { + focus: true, + pane: "pane-2", + edge: "bottom", + }); + + runtime.detachTab.mockImplementationOnce(() => session); + await moveTerminalToEditor("t1", { paneId: "pane-1", zone: "center", index: 1, pinned: true }); + expect(editor.openInput).toHaveBeenLastCalledWith(expect.objectContaining({ kind: CLI_KIND }), { + focus: true, + pane: "pane-1", + index: 1, + pinned: true, + }); + }); + + it("splits an editor terminal tab into a fresh session in its working directory", async () => { + tabs.state.tabs = [{ id: "t1", name: "Local", session: "s1" }]; + const existing = cliInput("Local (2)", "", "/repo"); + editor.openTabs.mockReturnValueOnce([{ input: existing, title: "Local (2)" }]); + runtime.cliSession.mockReturnValueOnce({ state: { cwd: "/repo/sub" } }); + runtime.nextTabName.mockReturnValueOnce("Local (3)"); + + const fresh = await splitCliTab(existing); + expect(fresh).toMatchObject({ + kind: CLI_KIND, + data: { name: "Local (3)", command: "", cwd: "/repo/sub" }, + }); + expect(fresh?.key).not.toBe(existing.key); + expect(runtime.startCli).toHaveBeenCalledExactlyOnceWith(fresh!.key, "/repo/sub", "", "/repo"); + }); }); describe("restored tabs", () => { diff --git a/src/features/terminal/cli.ts b/src/features/terminal/cli.ts index f67a798526..b24efb8985 100644 --- a/src/features/terminal/cli.ts +++ b/src/features/terminal/cli.ts @@ -7,10 +7,11 @@ */ import { createElement } from "react"; import { create } from "zustand"; -import { editorService, toolWindowService, type EditorInput } from "@/workbench/contributions"; +import { editorService, toolWindowService, type EditorDropTarget, type EditorInput } from "@/workbench/contributions"; import { useTx } from "@/platform/i18n"; import { useProject } from "@/platform/project"; import { isRemoteWindow } from "@/platform/remote"; +import { workflowSettings } from "@/platform/workflowSettings"; import { Badge } from "@/ui"; import { loadTerminalRuntime } from "./loader"; import type { SessionSnapshot } from "./session"; @@ -18,6 +19,9 @@ import type { SessionSnapshot } from "./session"; /** Editor kind of a terminal session tab. */ export const CLI_KIND = "cli"; +/** Drag type of terminal tabs: reorders within the tool window, or drops onto the editor area. */ +export const TERMINAL_TAB_MIME = "application/x-openidea-terminal-tab"; + /** `data` of a terminal editor tab: its title and where it started. */ export interface CliData { name: string; @@ -91,7 +95,7 @@ function trackCliTerminalId(input: EditorInput) { * Move to Editor: tab `id` of the Terminal tool window (the active one when omitted) * leaves the tool window and opens as an editor tab, its session still running. */ -export async function moveTerminalToEditor(id?: string) { +export async function moveTerminalToEditor(id?: string, target?: EditorDropTarget) { const rt = await loadTerminalRuntime(); const state = rt.useTerminals.getState(); const tab = state.tabs.find((t) => t.id === (id ?? state.activeTab)); @@ -104,7 +108,37 @@ export async function moveTerminalToEditor(id?: string) { rt.adoptCli(input.key, session); trackCliTerminalId(input); if (rt.useTerminals.getState().tabs.length === 0) toolWindowService().hide("terminal"); - await editorService().openInput(input, { focus: true }); + await editorService().openInput(input, { + focus: true, + ...(target + ? { + pane: target.paneId, + ...(target.zone !== "center" ? { edge: target.zone } : {}), + ...(target.index !== undefined ? { index: target.index } : {}), + ...(target.pinned !== undefined ? { pinned: target.pinned } : {}), + } + : {}), + }); +} + +/** Splits a terminal editor tab into a new shell session in the same directory. */ +export async function splitCliTab(input: EditorInput): Promise { + const root = useProject.getState().project?.root; + if (!root) return null; + const rt = await loadTerminalRuntime(); + const cwd = rt.cliSession(input.key)?.state.cwd || cliData(input)?.cwd || rt.startDirectory(root); + const openNames = + editorService() + .openTabs?.() + .flatMap((t) => (t.input.kind === CLI_KIND ? [cliData(t.input)?.name ?? t.title] : [])) ?? []; + const name = rt.nextTabName( + [...rt.useTerminals.getState().tabs.map((t) => t.name), ...openNames], + workflowSettings().terminal.tabName, + ); + const fresh = cliInput(name, "", cwd); + rt.startCli(fresh.key, cwd, "", root); + trackCliTerminalId(fresh); + return fresh; } /** Starts the session of a restored tab: its Start button. */ diff --git a/src/features/terminal/cliKinds.test.tsx b/src/features/terminal/cliKinds.test.tsx index 1a420fe576..0770959e0a 100644 --- a/src/features/terminal/cliKinds.test.tsx +++ b/src/features/terminal/cliKinds.test.tsx @@ -8,10 +8,10 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react" import { executeAction } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { useProject } from "@/platform/project"; -import { useContributions, type EditorInput } from "@/workbench/contributions"; +import { dropOnEditor, editorDropAllowsSplit, useContributions, type EditorInput } from "@/workbench/contributions"; import { initialTabsState, openTab, paneIds, type TabsState } from "@/editor/core/model/tabs"; import { parseSession, restoreTabsState, serializeSession } from "@/editor/core/model/session"; -import { CLI_KIND, cliInput, useClis } from "./cli"; +import { CLI_KIND, TERMINAL_TAB_MIME, cliInput, useClis } from "./cli"; import { CliEditor } from "./CliEditor"; import { activate } from "./index"; @@ -71,7 +71,9 @@ describe("terminal editor kind", () => { const deactivate = activate(); try { const kind = useContributions.getState().editorKinds.get("cli"); - expect(kind).toMatchObject({ restorable: true, keepAlive: true }); + expect(kind).toMatchObject({ restorable: true, keepAlive: true, singleton: true }); + expect(editorDropAllowsSplit(TERMINAL_TAB_MIME)).toBe(true); + expect(dropOnEditor({ type: TERMINAL_TAB_MIME, payload: "t9" }, { paneId: "p1", zone: "right" })).toBe(true); expect(kind?.isBusy?.(cliInputOf())).toBe(false); expect(kind?.title?.(cliInputOf())).toBe("Claude Code"); expect(kind?.title?.({ kind: "cli", key: "cli:r9", data: {} })).toBe("Terminal"); @@ -79,6 +81,7 @@ describe("terminal editor kind", () => { deactivate(); } expect(useContributions.getState().editorKinds.has("cli")).toBe(false); + expect(editorDropAllowsSplit(TERMINAL_TAB_MIME)).toBe(false); }); it("asks the runtime about busy tabs and ends their sessions on close", () => { diff --git a/src/features/terminal/closeLastTab.test.ts b/src/features/terminal/closeLastTab.test.ts index 2d6ba0a6d4..bedb643e7a 100644 --- a/src/features/terminal/closeLastTab.test.ts +++ b/src/features/terminal/closeLastTab.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions"; import { getContext, setContext } from "@/platform/context"; -import { closeAll, closeTab, getSession, newTab, useTerminals } from "./store"; +import { closeAll, closeTab, detachTab, getSession, newTab, useTerminals } from "./store"; const { focused } = vi.hoisted(() => ({ focused: [] as string[] })); @@ -121,6 +121,13 @@ describe("terminalFocus after the focused pane goes away", () => { expect(getContext().terminalFocus).toBe(false); }); + it("is cleared when the focused tab is detached to the editor", () => { + const tab = newTab("/repo"); + typeInto(tab.session); + expect(detachTab(tab.id)?.key).toBe(tab.session); + expect(getContext().terminalFocus).toBe(false); + }); + it("is left alone when a background session ends", () => { const a = newTab("/repo"); const b = newTab("/repo"); diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts index b0c7ed449b..3958b1c92c 100644 --- a/src/features/terminal/index.ts +++ b/src/features/terminal/index.ts @@ -13,12 +13,13 @@ import { onWorkflowSettingsChange } from "@/platform/workflowSettings"; import { provideEmbeddedTerminal, registerAgentContextSource, + registerEditorDropHandler, registerEditorKind, registerToolWindow, toolWindowService, } from "@/workbench/contributions"; import { lazyComponent } from "@/ui"; -import { CLI_KIND, CliDoneMark, cliData, moveTerminalToEditor } from "./cli"; +import { CLI_KIND, CliDoneMark, TERMINAL_TAB_MIME, cliData, moveTerminalToEditor, splitCliTab } from "./cli"; import { installTerminalKeys } from "./keys"; import { loadTerminalRuntime, terminalRuntime } from "./loader"; import { SAMPLE_TUI_END, SAMPLE_TUI_START, sampleTuiFrame } from "./sampleTui"; @@ -144,9 +145,16 @@ export function activate(): () => void { // A reopened tab shows Start: nothing runs on its own. restorable: true, keepAlive: true, + singleton: true, + splitInput: splitCliTab, onClose: (input) => terminalRuntime()?.disposeCli(input.key), isBusy: (input) => terminalRuntime()?.cliBusy(input.key) ?? false, }), + registerEditorDropHandler({ + accepts: (type) => type === TERMINAL_TAB_MIME, + allowSplit: true, + drop: ({ payload }, target) => void moveTerminalToEditor(payload, target), + }), registerActions([ { id: "terminal.moveToEditor", diff --git a/src/features/terminal/runtime.ts b/src/features/terminal/runtime.ts index bb8b162d92..0d410e9e12 100644 --- a/src/features/terminal/runtime.ts +++ b/src/features/terminal/runtime.ts @@ -7,6 +7,7 @@ export { detachTab, newTab, newTabRunning, + nextTabName, pluginSession, rememberTerminals, syncTerminalProject, diff --git a/src/features/terminal/store.ts b/src/features/terminal/store.ts index a4d7bb44bd..516e19d906 100644 --- a/src/features/terminal/store.ts +++ b/src/features/terminal/store.ts @@ -315,6 +315,7 @@ export function detachTab(id: string): TerminalSession | undefined { const tab = useTerminals.getState().tabs.find((t) => t.id === id); const session = tab && sessions.get(tab.session); if (!tab || !session) return undefined; + if (document.activeElement && session.host?.contains(document.activeElement)) publishFocus(false); sessions.delete(tab.session); useTerminals.setState((s) => { const next = { ...s.sessions }; diff --git a/src/ui/Tabs.test.tsx b/src/ui/Tabs.test.tsx index 1e0f1498b7..6553e99b61 100644 --- a/src/ui/Tabs.test.tsx +++ b/src/ui/Tabs.test.tsx @@ -460,4 +460,35 @@ describe("Tabs drag & drop", () => { pointer(window, "pointerup", 180); expect(onDrop).toHaveBeenCalledWith("a", 2); }); + + it("accepts external drag types with an insertion marker and routes them to onExternalDrop", () => { + const onExternalDrop = vi.fn(); + render( + <> + + {}} + dnd={{ + type: "application/x-other", + payload: (id) => id, + onDrop: () => {}, + accepts: (data) => data.type === TYPE && data.payload === "term-1", + onExternalDrop, + }} + /> + , + ); + pointer(within(tab("Source", "term-1")).getByRole("tab"), "pointerdown", 50); + hit = strip("Editor"); + pointer(window, "pointermove", 120); + expect(tab("Editor", "d")).toHaveClass(styles.dropBefore!); + pointer(window, "pointerup", 120); + expect(onExternalDrop).toHaveBeenCalledWith({ type: TYPE, payload: "term-1" }, 1); + }); }); diff --git a/src/ui/Tabs.tsx b/src/ui/Tabs.tsx index e7fef37d24..ee331ca2b7 100644 --- a/src/ui/Tabs.tsx +++ b/src/ui/Tabs.tsx @@ -22,7 +22,7 @@ import { IconButton } from "./Button"; import { Menu, type MenuItem } from "./Menu"; import { HiddenTabsPopup } from "./HiddenTabsPopup"; import { tooltipAttrs } from "./Tooltip"; -import { isOutsideWindow, registerDropTarget, startPointerDrag } from "./pointerDrag"; +import { isOutsideWindow, registerDropTarget, startPointerDrag, type DragData } from "./pointerDrag"; import { Given } from "./T"; import styles from "./Tabs.module.css"; import { tx, useGivenTx } from "@/platform/i18n"; @@ -69,6 +69,9 @@ export interface TabsDnd { type: string; payload: (id: string) => string; onDrop: (payload: string, index: number) => void; + /** Extra drag payloads accepted onto this strip (shown with the cross-strip insertion line). */ + accepts?: (data: DragData) => boolean; + onExternalDrop?: (data: DragData, index: number) => void; /** * A dragged tab released with no accepting target (the pointer left the * window): the editor uses it to detach the tab into a new window. Gets the @@ -242,12 +245,15 @@ export function Tabs({ return next ? items.indexOf(next) : items.length; }; return registerDropTarget(el, { - accepts: (type) => type === dropState.current.dnd?.type, + accepts: (type, data) => type === dropState.current.dnd?.type || !!dropState.current.dnd?.accepts?.(data), over: (_, x, y) => setDrop(indexAt(x, y)), leave: () => setDrop(null), drop: (data, x, y) => { setDrop(null); - dropState.current.dnd?.onDrop(data.payload, indexAt(x, y)); + const current = dropState.current.dnd; + const at = indexAt(x, y); + if (data.type === current?.type) current.onDrop(data.payload, at); + else current?.onExternalDrop?.(data, at); }, }); }, [dndType]); diff --git a/src/ui/pointerDrag.ts b/src/ui/pointerDrag.ts index e90534f891..3d3ba7b791 100644 --- a/src/ui/pointerDrag.ts +++ b/src/ui/pointerDrag.ts @@ -19,7 +19,7 @@ export const FILES_DRAG = "application/x-openidea-files"; export const REMOTE_FILES_DRAG = "application/x-openidea-remote-files"; export interface DropTarget { - accepts(type: string): boolean; + accepts(type: string, data: DragData): boolean; /** The pointer moved over the target. */ over(data: DragData, x: number, y: number): void; /** The pointer left the target, or the drag ended elsewhere / was cancelled. */ @@ -36,11 +36,11 @@ export function registerDropTarget(el: Element, target: DropTarget): () => void }; } -/** The innermost registered target under (x, y) accepting `type`. */ -function targetAt(type: string, x: number, y: number): DropTarget | null { +/** The innermost registered target under (x, y) accepting `data`. */ +function targetAt(data: DragData, x: number, y: number): DropTarget | null { for (let el = document.elementFromPoint(x, y); el; el = el.parentElement) { const t = targets.get(el); - if (t?.accepts(type)) return t; + if (t?.accepts(data.type, data)) return t; } return null; } @@ -98,12 +98,12 @@ export function dragSession(data: DragData): DragSession { }; return { move(x, y) { - enter(targetAt(data.type, x, y)); + enter(targetAt(data, x, y)); current?.over(data, x, y); return !!current; }, drop(x, y) { - const t = targetAt(data.type, x, y); + const t = targetAt(data, x, y); enter(null); t?.drop(data, x, y); return !!t; diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index f108aac8d0..fac591f975 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -153,6 +153,14 @@ export interface EditorKindContribution { * tab keeps running; `useEditorShown` tells it whether it is the one shown. */ keepAlive?: boolean; + /** + * Its input owns one live view (e.g. a terminal session's DOM + PTY) and cannot appear in + * two panes at once: splitting or "Open in Opposite Group" opens a fresh input from + * `splitInput`, or moves the tab instead. + */ + singleton?: boolean; + /** Fresh input opened when splitting a `singleton` tab (e.g. a new shell in the same cwd). */ + splitInput?(input: EditorInput): EditorInput | Promise | null; /** Last tab showing this input closed (including split tabs and tab-limit eviction). */ onClose?(input: EditorInput): void; /** The input that shows this tab where it is now when Back returns to it, e.g. a diff at its caret. */ @@ -716,6 +724,15 @@ export const OWNS_FILE_DROP = { "data-owns-file-drop": "" } as const; // Services implemented by one feature and consumed by others. The provider // calls `provide*` during activation; consumers call through the accessor. +export type EditorDropEdge = "left" | "right" | "top" | "bottom"; + +export interface EditorDropTarget { + paneId: string; + zone: EditorDropEdge | "center"; + index?: number; + pinned?: boolean; +} + export interface OpenOptions { /** Select / reveal this range (0-based line, UTF-16 col). */ selection?: { line: number; col: number; endLine?: number; endCol?: number }; @@ -723,8 +740,14 @@ export interface OpenOptions { preview?: boolean; /** Open to the side (split right). */ side?: boolean; + /** Split `pane` (or the active pane) at this edge and open in the new group. */ + edge?: EditorDropEdge; /** Open in this editor pane, in a tab of its own even when another pane shows the file. */ pane?: string; + /** 0-based insertion index in the target pane's tab strip. */ + index?: number; + /** Open as a pinned tab (e.g. dropped onto the pinned tabs row). */ + pinned?: boolean; focus?: boolean; /** Open in the text editor even when a file editor provider claims the file (SVG as text). */ asText?: boolean; @@ -1050,13 +1073,15 @@ export function registerCommitCheckProvider(p: CommitCheckProvider): () => void } /** - * Handles a pointer drag dropped on the editor content: features register handlers for - * their own drag types (e.g. an agent task dragged from the tool window) without the - * editor depending on them. The editor shows its center drop-zone for accepted types. + * Handles a pointer drag dropped on the editor area (a tab strip, a pane, or an edge split): + * features register handlers for their own drag types (e.g. an agent task or a terminal tab + * dragged from a tool window) without the editor depending on them. */ export interface EditorDropHandler { - accepts(type: string): boolean; - drop(data: DragData): void; + accepts(type: string, data?: DragData): boolean; + /** Whether dropping near an editor pane's edge splits off a new group on that side. */ + allowSplit?: boolean; + drop(data: DragData, target?: EditorDropTarget): void; } const editorDropHandlers: EditorDropHandler[] = []; @@ -1070,16 +1095,21 @@ export function registerEditorDropHandler(handler: EditorDropHandler): () => voi }; } -/** Whether any registered handler takes this drag type. */ -export function acceptsEditorDrop(type: string): boolean { - return editorDropHandlers.some((h) => h.accepts(type)); +/** Whether any registered handler takes this drag. */ +export function acceptsEditorDrop(type: string, data?: DragData): boolean { + return editorDropHandlers.some((h) => h.accepts(type, data)); } -/** Hands a drag dropped on editor content to its registered handler, if any. */ -export function dropOnEditor(data: DragData): boolean { - const handler = editorDropHandlers.find((h) => h.accepts(data.type)); +/** Whether the handler taking this drag supports edge-split drop zones. */ +export function editorDropAllowsSplit(type: string, data?: DragData): boolean { + return !!editorDropHandlers.find((h) => h.accepts(type, data))?.allowSplit; +} + +/** Hands a drag dropped on the editor to its registered handler, if any. */ +export function dropOnEditor(data: DragData, target?: EditorDropTarget): boolean { + const handler = editorDropHandlers.find((h) => h.accepts(data.type, data)); if (!handler) return false; - handler.drop(data); + handler.drop(data, target); return true; } From a7b67347c200539920220f9652c9250799697c53 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:22:22 +0800 Subject: [PATCH 06/86] fix(vcs): let the Repository column of the Git Log be resized (#5718) In a project with several Git roots the Git Log's Repository column was fixed at 100 px, so longer repository names were cut off. While Repository is shown, the first column's left divider (in the header and in the row strips) now resizes it through the same pair-resize path as the other columns; the width is stored in columnWidths.repository (default 100) and Reset Width is in the header's context menu. The column still keeps its place. Closes #5291 Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- src/features/vcs/GitLog.module.css | 2 +- .../vcs/__tests__/logUiFeatures.test.tsx | 38 +++++++++++++++++++ src/features/vcs/log/ColumnHeaders.tsx | 24 +++++++++--- src/features/vcs/log/CommitRow.tsx | 21 +++++++--- src/features/vcs/log/useColumnResize.ts | 11 +++++- 5 files changed, 84 insertions(+), 12 deletions(-) diff --git a/src/features/vcs/GitLog.module.css b/src/features/vcs/GitLog.module.css index eb5c56a858..ee878bcdda 100644 --- a/src/features/vcs/GitLog.module.css +++ b/src/features/vcs/GitLog.module.css @@ -888,7 +888,7 @@ } .colRepository { - flex: 0 1 100px; + flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; diff --git a/src/features/vcs/__tests__/logUiFeatures.test.tsx b/src/features/vcs/__tests__/logUiFeatures.test.tsx index b25cb409a4..7c3f325f15 100644 --- a/src/features/vcs/__tests__/logUiFeatures.test.tsx +++ b/src/features/vcs/__tests__/logUiFeatures.test.tsx @@ -233,6 +233,22 @@ describe("log controls", () => { expect(useLogOptions.getState().columnWidths.hash).toBe(42); // 72 - 30 }); + it("dragging the first column's divider resizes the Repository column", async () => { + useVcs.setState({ roots: ["/repo", "/other"] }); + useLogOptions.setState({ showColumnHeaders: true, showRepository: true }); + render(); + // Commit is first by default; with Repository on its left its divider is live. + const handle = await screen.findByRole("separator", { name: "Resize Commit column" }); + handle.setPointerCapture = vi.fn(); + handle.hasPointerCapture = () => true; + handle.releasePointerCapture = vi.fn(); + fireEvent.pointerDown(handle, { button: 0, pointerId: 7, clientX: 100 }); + fireEvent.pointerMove(handle, { pointerId: 7, clientX: 140 }); + fireEvent.pointerUp(handle, { pointerId: 7, clientX: 140 }); + expect(useLogOptions.getState().columnWidths.repository).toBe(140); // 100 + 40 + expect(screen.getByText("Repository").style.width).toBe("140px"); + }); + it("hides column dividers by default and shows them via the option", async () => { useLogOptions.setState({ showColumnHeaders: true, showColumnDividers: false }); const { rerender } = render(); @@ -262,6 +278,28 @@ describe("log controls", () => { expect(useLogOptions.getState().showAuthor).toBe(false); }); + it.each([ + ["first column", ["author", "subject", "date"]], + ["first shown column, after a hidden one", ["hash", "author", "subject", "date"]], + ])("without headers, a row strip of the %s resizes the Repository column", async (_, columnOrder) => { + useVcs.setState({ roots: ["/repo", "/other"] }); + const tip = { ...c("tip"), repo: "/repo" }; + api.commits = [tip]; + useLogOptions.setState({ showRepository: true, showHash: false, columnOrder }); + render(); + const rows = await within(screen.getByRole("listbox", { name: "Commits" })).findAllByRole("option"); + const strip = rows[0]!.querySelector('[class*="columnResize"]')!; + strip.setPointerCapture = vi.fn(); + strip.hasPointerCapture = () => true; + strip.releasePointerCapture = vi.fn(); + // Author is first and Repository is on its left: the pair trades width. + fireEvent.pointerDown(strip, { button: 0, pointerId: 9, clientX: 100 }); + fireEvent.pointerMove(strip, { pointerId: 9, clientX: 130 }); + fireEvent.pointerUp(strip, { pointerId: 9, clientX: 130 }); + expect(useLogOptions.getState().columnWidths.repository).toBe(130); + expect(rows[0]!.querySelector('[class*="colRepository"]')!.style.width).toBe("130px"); + }); + it("exposes a full-height column divider on data rows", async () => { useLogOptions.setState({ showColumnHeaders: true }); render(); diff --git a/src/features/vcs/log/ColumnHeaders.tsx b/src/features/vcs/log/ColumnHeaders.tsx index a2ae7c5e20..08875da58f 100644 --- a/src/features/vcs/log/ColumnHeaders.tsx +++ b/src/features/vcs/log/ColumnHeaders.tsx @@ -8,7 +8,7 @@ import { updateLogOptions } from "../logStore"; import { useVcs } from "../store"; import { ColumnResizeHandle } from "./ColumnResizeHandle"; import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared"; -import { columnPrev, resetColumnWidth, type ResizeTarget } from "./useColumnResize"; +import { REPOSITORY_WIDTH, columnPrev, resetColumnWidth, type ResizeTarget } from "./useColumnResize"; interface ColumnDrag { id: string; @@ -38,10 +38,20 @@ export function ColumnHeaders({ columns, options }: { columns: LogColumn[]; opti updateLogOptions({ columnOrder: reordered }); }; const visibleIds = ids.filter((id) => id === SUBJECT_COLUMN.id || columns.some((column) => column.id === id)); + const repository = options.showRepository && useVcs.getState().roots.length > 1; return (
- {options.showRepository && useVcs.getState().roots.length > 1 && ( - {tx("Repository")} + {repository && ( + { + e.preventDefault(); + showContextMenu(e, [{ label: "Reset Width", run: () => resetColumnWidth("repository") }]); + }} + > + {tx("Repository")} + )} {ids.map((cid) => { const column = cid === SUBJECT_COLUMN.id ? SUBJECT_COLUMN : columns.find((c) => c.id === cid); @@ -52,6 +62,7 @@ export function ColumnHeaders({ columns, options }: { columns: LogColumn[]; opti column={column} subject={cid === SUBJECT_COLUMN.id} ids={visibleIds} + repository={repository} options={options} columns={columns} drag={drag} @@ -73,6 +84,7 @@ function LogColumnHeader({ column, subject, ids, + repository, options, columns, drag, @@ -83,6 +95,7 @@ function LogColumnHeader({ column: LogColumn; subject?: boolean; ids: string[]; + repository: boolean; options: LogOptions; columns: LogColumn[]; drag: ColumnDrag | null; @@ -123,12 +136,13 @@ function LogColumnHeader({ const resizeTarget: ResizeTarget = { id: column.id, width, - ...columnPrev(ids, column.id, options, columns), + ...columnPrev(ids, column.id, options, columns, repository), // Commit is flex:1 — dragging its left divider only resizes the left neighbour. leftOnly: subject || undefined, }; const index = ids.indexOf(column.id); - const isFirst = index === 0; + // The first column's left divider is the Repository column's right edge when it is shown. + const isFirst = index === 0 && !repository; const hitColumn = (x: number, y: number) => { const el = document.elementFromPoint(x, y)?.closest?.("[data-log-column]"); if (!el || el.parentElement !== press.current?.element.parentElement) return null; diff --git a/src/features/vcs/log/CommitRow.tsx b/src/features/vcs/log/CommitRow.tsx index d347ca29b4..f734adfc34 100644 --- a/src/features/vcs/log/CommitRow.tsx +++ b/src/features/vcs/log/CommitRow.tsx @@ -14,7 +14,7 @@ import { GraphCell } from "./GraphCell"; import { RowResizeHandle } from "./RowResizeHandle"; import { commitMenu } from "./commitMenu"; import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared"; -import { columnPrev } from "./useColumnResize"; +import { REPOSITORY_WIDTH, columnPrev } from "./useColumnResize"; function CommitRowView({ id, @@ -161,6 +161,11 @@ function CommitRowView({ ); + const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1; + // The header's neighbours: an id without a shown column (a hidden one) is skipped. + const visibleIds = columnSequence(opts.columnOrder, columns).filter( + (cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid), + ); return (
- {opts.showRepository && commitRepo(c) && useVcs.getState().roots.length > 1 && ( - + {repository && ( + {repoName(commitRepo(c)!)} )} - {columnSequence(opts.columnOrder, columns).map((cid, _index, ids) => { + {visibleIds.map((cid, _index, ids) => { if (cid === SUBJECT_COLUMN.id) return subjectCell; const column = columns.find((col) => col.id === cid); if (!column) return null; @@ -205,7 +214,9 @@ function CommitRowView({ title={column.id === "author" ? `${c.author} <${c.email}>` : undefined} > {column.render(c)} - + ); })} diff --git a/src/features/vcs/log/useColumnResize.ts b/src/features/vcs/log/useColumnResize.ts index 56a2cc5720..064a74c803 100644 --- a/src/features/vcs/log/useColumnResize.ts +++ b/src/features/vcs/log/useColumnResize.ts @@ -24,14 +24,23 @@ export type ResizeTarget = { leftOnly?: boolean; }; -/** Resolve the column immediately left of `id` in the visible order. */ +/** Default width of the Repository column, which stays left of the reorderable columns. */ +export const REPOSITORY_WIDTH = 100; + +/** + * Resolve the column immediately left of `id` in the visible order. With `repository`, the + * Repository column is shown before `ids`, so the first column's left divider resizes it. + */ export function columnPrev( ids: string[], id: string, options: LogOptions, columns: LogColumn[], + repository = false, ): { prevId: string | null; prevWidth: number } { const index = ids.indexOf(id); + if (index === 0 && repository) + return { prevId: "repository", prevWidth: options.columnWidths.repository ?? REPOSITORY_WIDTH }; const prevId = index > 0 ? ids[index - 1] : null; // The Commit column is flex:1 and absorbs space on its own — never store a width for it. // (When *we are* the Commit column the caller handles the left neighbour via leftOnly, From ae7a8e74c836b89473162bd486eec0f13c52d962 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 11:26:49 +0800 Subject: [PATCH 07/86] fix(agents): quiet tool rows and use the IDE's controls and type scale (#5725) The agents tool window looked like a separate chat app. A running tool call now shows one spinner (no entrance or pulse animation; shimmer only on summary text without a spinner); tool icons are muted, exit codes show only on failure, and terminal blocks lose their coloured edge. Home starts at the top with a 13px heading, the composer uses the text-field radius, conversation text uses line height 1.4 with tighter turn spacing, and message times are always shown. Badges, tags and the subagent chip are flat text; font sizes and heights use the shared tokens (so compact mode applies), list rows and chips use the tree and toolbar hover colours, Markdown headings stay on the UI type scale, and Compact session is a standard Button. --- src/features/agents/AgentList.module.css | 2 +- src/features/agents/Agents.module.css | 17 ++- src/features/agents/Composer.module.css | 23 ++-- src/features/agents/ConfigPickers.tsx | 8 +- src/features/agents/Home.module.css | 29 ++-- src/features/agents/HomeEditor.tsx | 2 +- src/features/agents/McpServers.module.css | 9 +- src/features/agents/ReferenceChip.module.css | 4 +- src/features/agents/Session.module.css | 137 +++++-------------- src/features/agents/SessionPicker.module.css | 14 +- src/features/agents/SettingsPage.module.css | 23 ++-- src/features/agents/session/ContextMeter.tsx | 8 +- src/features/agents/session/ProcessRows.tsx | 4 +- src/features/agents/session/toolEntries.tsx | 8 +- 14 files changed, 104 insertions(+), 184 deletions(-) diff --git a/src/features/agents/AgentList.module.css b/src/features/agents/AgentList.module.css index 31c2d4a57e..22b3ab52bc 100644 --- a/src/features/agents/AgentList.module.css +++ b/src/features/agents/AgentList.module.css @@ -258,7 +258,7 @@ display: flex; align-items: center; min-width: 0; - min-height: 28px; + min-height: var(--h-field); } .rowHint { grid-column: 2; diff --git a/src/features/agents/Agents.module.css b/src/features/agents/Agents.module.css index 86d93983c6..d42d8cfcdd 100644 --- a/src/features/agents/Agents.module.css +++ b/src/features/agents/Agents.module.css @@ -97,7 +97,7 @@ flex: none; margin-left: auto; margin-right: var(--space-2); - gap: var(--space-2); + gap: var(--space-0-5); } .row:hover .rowActions, .rowActions:focus-within { @@ -111,22 +111,29 @@ display: flex; align-items: center; justify-content: center; - width: 16px; - height: 16px; + width: var(--h-control-small); + height: var(--h-control-small); padding: 0; border: none; + border-radius: var(--radius-small); background: none; color: var(--fg-subtle); --icon-color: currentColor; cursor: pointer; + transition: + background var(--dur-fast) var(--ease), + color var(--dur-fast) var(--ease); } .rowAction:hover { + background: var(--bg-toolbar-hover); color: var(--fg-strong); } +.rowAction:active { + background: var(--bg-toolbar-pressed); +} .rowAction:focus-visible { outline: 2px solid var(--focus-ring); - outline-offset: 1px; - border-radius: var(--radius-small); + outline-offset: -2px; } .ready { color: var(--success); diff --git a/src/features/agents/Composer.module.css b/src/features/agents/Composer.module.css index 234774c3a6..00ad4f365a 100644 --- a/src/features/agents/Composer.module.css +++ b/src/features/agents/Composer.module.css @@ -5,7 +5,7 @@ position: relative; display: flex; flex-direction: column; - border-radius: var(--radius-popup); + border-radius: var(--radius-control); background: var(--bg-field, var(--bg-button)); box-shadow: inset 0 0 0 1px var(--border-button); cursor: text; @@ -48,7 +48,7 @@ A host sets --composer-min-height rather than overriding the rule, so stylesheet order can't undo it. */ .field :global(.cm-content) { min-height: var(--composer-min-height, 44px); - padding: 10px 12px 2px; + padding: var(--space-2) var(--space-2) var(--space-0-5); caret-color: var(--fg-strong); white-space: pre-wrap; overflow-wrap: anywhere; @@ -273,21 +273,14 @@ background: var(--bg-hover); color: var(--fg-strong); } +/* The model's relative cost: plain text; only an expensive model is coloured. */ .costBadge { flex: none; - padding: 1px 7px; - border-radius: var(--radius-popup); - background: var(--bg-floating-toolbar); - color: var(--fg-secondary); + color: var(--fg-subtle); font-size: var(--fs-tiny); white-space: nowrap; } -.costBadgeLow { - background: color-mix(in srgb, var(--success) 18%, var(--bg-elev)); - color: var(--success); -} .costBadgeHigh { - background: color-mix(in srgb, var(--warning) 20%, var(--bg-elev)); color: var(--warning); } @@ -299,14 +292,14 @@ align-items: stretch; gap: var(--space-0-5); padding: 2px; - border-radius: var(--radius-popup); + border-radius: var(--radius-toolbar-button); background: var(--bg-input); box-shadow: inset 0 0 0 1px var(--border-strong); } .segment { flex: 1 1 0; min-width: 0; - height: 26px; + height: calc(var(--h-button) - 2px); padding: 0 6px; border: 0; border-radius: var(--radius-control); @@ -345,7 +338,7 @@ display: flex; align-items: center; gap: var(--space-1-5); - height: 24px; + height: var(--h-row); margin: 0 6px; padding: 0 8px; border-radius: var(--radius-row); @@ -493,7 +486,7 @@ align-items: center; gap: 5px; max-width: 240px; - height: 24px; + height: var(--h-control); padding: 0 4px 0 7px; border-radius: var(--radius-control); box-shadow: inset 0 0 0 1px var(--border); diff --git a/src/features/agents/ConfigPickers.tsx b/src/features/agents/ConfigPickers.tsx index 53c0e4a05c..04fb7dcd4d 100644 --- a/src/features/agents/ConfigPickers.tsx +++ b/src/features/agents/ConfigPickers.tsx @@ -507,13 +507,7 @@ function CostBadge({ category }: { category: string | null | undefined }) { ) : null; if (!label) return null; return ( - + {label} ); diff --git a/src/features/agents/Home.module.css b/src/features/agents/Home.module.css index 3696c174a1..300ee6efaa 100644 --- a/src/features/agents/Home.module.css +++ b/src/features/agents/Home.module.css @@ -8,13 +8,13 @@ display: flex; flex-direction: column; align-items: center; - justify-content: center; - padding: 24px 24px 12vh; + justify-content: flex-start; + padding: var(--space-4); background: var(--bg-editor); color: var(--fg); } .inner { - /* A compact block in the middle of the page: narrower than a session's conversation. */ + /* A compact block at the top of the editor: narrower than a session's conversation. */ width: min(680px, 100%); display: flex; flex-direction: column; @@ -24,13 +24,12 @@ width: 100%; } .heading { - margin: 0 0 14px; - font-size: calc(22px + var(--agent-font-zoom, 0px)); - font-weight: 500; - letter-spacing: -0.01em; - text-align: center; + margin: 0; + padding: 0 4px; + font-size: var(--agent-fs-ui); + font-weight: 600; + line-height: 1.4; color: var(--fg-strong); - text-wrap: balance; } /* A box to write in, not a search bar: room for a few lines before it grows. */ @@ -93,21 +92,19 @@ .docked { justify-content: flex-end; - padding: 16px 12px 12px; + padding: var(--space-3); } +/* The tool window keeps its box at the bottom, as a session does; the question is a hint line above it. */ .dockedIntro { flex: 1; display: flex; - align-items: center; - justify-content: center; + align-items: flex-end; width: 100%; min-height: 0; - padding-bottom: 8vh; + padding-bottom: var(--space-2); } .docked .heading { - margin: 0; - font-size: calc(15px + var(--agent-font-zoom, 0px)); - font-weight: 500; + font-weight: 400; color: var(--fg-muted); } diff --git a/src/features/agents/HomeEditor.tsx b/src/features/agents/HomeEditor.tsx index bb80fa60e8..9a695f3cce 100644 --- a/src/features/agents/HomeEditor.tsx +++ b/src/features/agents/HomeEditor.tsx @@ -184,7 +184,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input? className={clsx(styles.home, docked && styles.docked, fitWindowWidth && styles.fitWidth)} style={zoomStyle} > - {/* In the tool window the box sits at the bottom, under the question centred in the space above. */} + {/* In the tool window the box sits at the bottom, with the question as a hint line just above it. */} {docked && (

diff --git a/src/features/agents/McpServers.module.css b/src/features/agents/McpServers.module.css index 8b25f65e63..f8fb38dbd2 100644 --- a/src/features/agents/McpServers.module.css +++ b/src/features/agents/McpServers.module.css @@ -5,7 +5,8 @@ gap: var(--space-2); padding: 6px 10px; border-radius: var(--radius-control); - background: color-mix(in srgb, var(--accent) 14%, var(--bg-elev)); + background: var(--bg-feedback-info); + box-shadow: inset 0 0 0 1px var(--border-feedback-info); color: var(--fg); font-size: var(--fs-small); } @@ -59,7 +60,6 @@ } .tagSuccess { - background: color-mix(in srgb, var(--success) 18%, var(--bg-elev)); color: var(--success); } @@ -116,7 +116,7 @@ flex-direction: column; gap: var(--space-0-5); padding: 5px 8px; - border-radius: var(--radius-small, 3px); + border-radius: var(--radius-small); background: var(--bg-elev); box-shadow: inset 0 0 0 1px var(--border); } @@ -246,12 +246,11 @@ .segmentBtn { padding: 3px 10px; border: 0; - border-radius: var(--radius-small, 3px); + border-radius: var(--radius-small); background: transparent; color: var(--fg-muted); font: inherit; font-size: var(--fs-small); - font-weight: 500; cursor: pointer; } diff --git a/src/features/agents/ReferenceChip.module.css b/src/features/agents/ReferenceChip.module.css index b478e46631..7be2618e58 100644 --- a/src/features/agents/ReferenceChip.module.css +++ b/src/features/agents/ReferenceChip.module.css @@ -22,7 +22,7 @@ box-shadow var(--dur-fast) var(--ease); } .chip:hover { - background: color-mix(in srgb, var(--accent) 16%, transparent); + background: var(--accent-soft); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent); } .chip:focus-visible { @@ -84,7 +84,7 @@ -webkit-box-decoration-break: clone; box-decoration-break: clone; color: var(--accent); - background: color-mix(in srgb, var(--accent) 16%, transparent); + background: var(--accent-soft); } /* `@something` that names no referenced file: as typed, just marked. */ .pending { diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index f91514bbc5..7535b0f121 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -54,7 +54,7 @@ align-items: center; gap: var(--space-2); min-width: 0; - height: 24px; + height: var(--h-row); padding: 0 6px; overflow: hidden; color: var(--fg-subtle); @@ -243,7 +243,7 @@ universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every DOM insertion anywhere in the window, which costs every editor scroll frame. */ .stream > :where(:not(:first-child)) { - margin-top: var(--space-4); + margin-top: var(--space-3); } .stream > [data-process] + [data-process] { margin-top: var(--space-2); @@ -410,18 +410,9 @@ -webkit-user-select: none; user-select: none; } -.messageFooter > .messageTime, -.messageHead > .messageTime { - opacity: 0; -} /* A turn's final reply keeps its time and actions in view; your messages show theirs on hover. */ -.conversationRow:nth-last-child(1 of [data-message]) .agentMessage .messageTime, .conversationRow:nth-last-child(1 of [data-message]) .agentMessage .messageActions, .conversationRow:nth-last-child(1 of [data-message]) .reply .messageActions, -.message:hover .messageTime, -.agentMessage:hover .messageFooter > .messageTime, -.message:focus-within .messageTime, -.agentMessage:focus-within .messageFooter > .messageTime, .message:hover .messageActions, .reply:hover .messageActions, .agentMessage:hover .messageActions, @@ -445,7 +436,7 @@ left: 0; box-sizing: border-box; display: flex; - min-height: 24px; + min-height: var(--h-control); padding-top: 2px; -webkit-user-select: none; user-select: none; @@ -496,7 +487,7 @@ border-radius: var(--radius-tab); background: var(--bg-hover); color: var(--fg); - line-height: 1.5; + line-height: 1.4; white-space: pre-wrap; overflow-wrap: anywhere; } @@ -529,7 +520,7 @@ } .markdown { - line-height: 1.5; + line-height: 1.4; overflow-wrap: anywhere; } .markdown :global(p) { @@ -552,7 +543,7 @@ .markdown :global(code) { font-family: var(--font-mono); font-size: var(--agent-fs-small, var(--fs-small)); - border-radius: 3px; + border-radius: var(--radius-small); background: var(--md-code-bg); /* Side insets as shadows, not padding: a selection leaves inline padding unpainted. */ box-shadow: @@ -611,7 +602,7 @@ right: 56px; } .codeCopy:hover { - background: var(--bg-hover); + background: var(--bg-toolbar-hover); } /* Mermaid diagrams: the source stays until the diagram is drawn (and next to an error), and the Copy button lives on the block — the drawn diagram hides the @@ -739,13 +730,12 @@ margin: 12px 0 6px; color: var(--fg-strong); font-size: 1em; + font-weight: 600; line-height: 1.3; } +/* On the UI scale: one step up for a title, every other level at body size and weight 600. */ .markdown :global(h1) { - font-size: 1.15em; -} -.markdown :global(h2) { - font-size: 1.08em; + font-size: calc(var(--fs-input-large) + var(--agent-font-zoom, 0px)); } .markdown :global(blockquote) { margin: 0 0 8px; @@ -775,7 +765,7 @@ cursor: pointer; } .loadImage:hover { - background: var(--bg-hover); + background: var(--bg-toolbar-hover); } .markdown :global(li:has(> input[type="checkbox"])) { margin-left: calc(-1 * var(--md-list-indent)); @@ -817,7 +807,7 @@ user-select: none; } .thought summary:hover { - background: var(--bg-hover); + background: var(--bg-tree-hover); color: var(--fg); } .thoughtChevron { @@ -840,8 +830,6 @@ } .thoughtText { margin-top: 4px; - padding-left: 10px; - border-left: 2px solid var(--border-strong); color: var(--fg-secondary); white-space: pre-wrap; } @@ -860,7 +848,7 @@ max-width: 100%; } .toolDetails > summary.tool:hover { - background: var(--bg-hover); + background: var(--bg-tree-hover); color: var(--fg); } .tool > svg { @@ -894,7 +882,7 @@ white-space: nowrap; } .toolDiff:hover { - background: var(--bg-hover); + background: var(--bg-toolbar-hover); } /* Reasoning and tool calls between messages, folded as one block per turn. */ @@ -921,12 +909,12 @@ user-select: none; } .processSummary:hover { - background: var(--bg-hover); + background: var(--bg-tree-hover); color: var(--fg); } .processChevron { flex: none; - transition: transform 120ms ease; + transition: transform var(--dur-fast) var(--ease); } .processRun[open] .processChevron { transform: rotate(90deg); @@ -1025,7 +1013,7 @@ } .permissionTitle { color: var(--fg-strong); - font-weight: 400; + font-weight: 600; } .permissionCommand { min-width: 0; @@ -1137,7 +1125,7 @@ display: flex; align-items: center; gap: var(--space-1-5); - min-height: 24px; + min-height: var(--h-row); padding: 0 4px 0 8px; border-radius: var(--radius-row); background: var(--bg-elev); @@ -1162,7 +1150,7 @@ display: flex; align-items: center; gap: var(--space-1-5); - min-height: 28px; + min-height: var(--h-field); padding: 0 4px 0 8px; border-radius: var(--radius-row); background: var(--bg-elev); @@ -1590,23 +1578,24 @@ flex-wrap: wrap; gap: var(--space-1); } +/* Flat like the toolbar chips: no frame at rest, the toolbar hover when the pointer is on it. */ .subagentChip { display: inline-flex; align-items: center; gap: var(--space-1-5); max-width: 240px; height: 22px; - padding: 0 8px; - border: 1px solid var(--border); - border-radius: 11px; - background: var(--bg-elev); + padding: 0 6px; + border: 0; + border-radius: var(--radius-toolbar-button); + background: transparent; color: var(--fg-secondary); font: inherit; font-size: var(--fs-small); cursor: pointer; } .subagentChip:hover { - background: var(--bg-hover); + background: var(--bg-toolbar-hover); color: var(--fg); } .subagentChipTitle { @@ -1905,7 +1894,7 @@ } .trayChip:hover, .trayChip[aria-expanded="true"] { - background: var(--bg-hover); + background: var(--bg-toolbar-hover); color: var(--fg); } .trayPlan { @@ -1936,7 +1925,7 @@ background-position: 0 0; } } -@media (prefers-reduced-motion: reduce) { +@media (prefers-reduced-motion: reduce), (forced-colors: active) { .shimmer { animation: none; background: none; @@ -1944,32 +1933,11 @@ } } -/* Tool calls: an accent by what the call does, a pulse while it runs, its end and time on the right. */ -.toolEntry { - --tool-accent: var(--fg-subtle); - animation: entryIn 180ms ease-out; -} -.kind-read, -.kind-search { - --tool-accent: var(--info); -} -.kind-edit, -.kind-delete, -.kind-move { - --tool-accent: var(--warning); -} -.kind-execute { - --tool-accent: var(--success); -} -.kind-fetch { - --tool-accent: var(--accent); -} +/* Tool calls: a muted icon by what the call does, its end and time on the right. Colour is kept for + failures; a running call shows one spinner and nothing else moves. */ .toolKindIcon { flex: none; - color: var(--tool-accent); -} -.toolLive .toolKindIcon { - animation: toolPulse 1.2s ease-in-out infinite; + color: var(--fg-muted); } .toolPath { flex: none; @@ -2001,25 +1969,18 @@ color: var(--success); } .toolSpinner { - color: var(--tool-accent); + color: var(--fg-muted); } +/* Only a failed command shows its exit code. */ .exitCode { flex: none; - padding: 0 5px; - border-radius: var(--radius-small); - background: color-mix(in srgb, var(--success) 18%, transparent); - color: var(--success); + color: var(--danger); font-family: var(--font-mono); font-size: var(--agent-fs-small, var(--fs-small)); } -.exitFailed { - background: color-mix(in srgb, var(--danger) 18%, transparent); - color: var(--danger); -} .terminalBlock { margin: 4px 0 4px 22px; border: 1px solid var(--border); - border-left: 2px solid var(--tool-accent); border-radius: var(--radius-small); background: var(--bg-elev); overflow: hidden; @@ -2040,36 +2001,14 @@ color: var(--fg-muted); } .prompt { - color: var(--tool-accent); + color: var(--fg-subtle); user-select: none; } -.thoughtEntry { - animation: entryIn 180ms ease-out; -} .thoughtTook { flex: none; margin-left: 6px; color: var(--fg-subtle); } -@keyframes entryIn { - from { - opacity: 0; - transform: translateY(4px); - } -} -@keyframes toolPulse { - 50% { - opacity: 0.35; - } -} -@media (prefers-reduced-motion: reduce) { - .toolEntry, - .thoughtEntry, - .toolLive .toolKindIcon { - animation: none; - } -} - .meterButton { composes: meter; cursor: pointer; @@ -2085,7 +2024,7 @@ .contextPopover[data-positioned], .contextClosing[data-positioned] { animation: none; - transition: opacity 100ms ease; + transition: opacity var(--dur-fast) var(--ease); } .contextClosing { composes: contextPopover; @@ -2156,10 +2095,4 @@ } .contextCompact { justify-self: end; - cursor: pointer; - color: var(--fg); - background: var(--bg-button); - border: 1px solid var(--border); - border-radius: 4px; - padding: var(--space-1) var(--space-2); } diff --git a/src/features/agents/SessionPicker.module.css b/src/features/agents/SessionPicker.module.css index 8acab29b2c..c383a849ed 100644 --- a/src/features/agents/SessionPicker.module.css +++ b/src/features/agents/SessionPicker.module.css @@ -68,7 +68,7 @@ .resetBtn { padding: 2px 6px; border: 0; - border-radius: var(--radius-small, 3px); + border-radius: var(--radius-small); background: transparent; color: var(--link); font: inherit; @@ -130,7 +130,7 @@ } .name { - font-weight: 500; + font-weight: 600; color: var(--fg-strong); overflow: hidden; text-overflow: ellipsis; @@ -150,16 +150,14 @@ align-items: center; height: 16px; padding: 0 5px; - border-radius: var(--radius-small, 3px); + border-radius: var(--radius-small); background: var(--bg-floating-toolbar); color: var(--fg-secondary); - font-size: 10px; - font-weight: 500; + font-size: var(--fs-tiny); } .pillSession { - background: color-mix(in srgb, var(--accent) 20%, var(--bg-elev)); - color: var(--link); + color: var(--fg-strong); } .rowControls { @@ -191,7 +189,7 @@ .inlineLink { padding: 2px 6px; border: 0; - border-radius: var(--radius-small, 3px); + border-radius: var(--radius-small); background: var(--bg-elev); box-shadow: inset 0 0 0 1px var(--border-button); color: var(--fg-secondary); diff --git a/src/features/agents/SettingsPage.module.css b/src/features/agents/SettingsPage.module.css index 6cb58e33c0..e35ddfbcef 100644 --- a/src/features/agents/SettingsPage.module.css +++ b/src/features/agents/SettingsPage.module.css @@ -23,7 +23,7 @@ .title { margin: 0; - font-size: 16px; + font-size: var(--fs-input-large); font-weight: 600; color: var(--fg-strong); } @@ -67,8 +67,9 @@ gap: var(--space-1-5); padding: 6px 8px; border-radius: var(--radius-control); - background: color-mix(in srgb, var(--danger) 12%, transparent); - color: var(--danger); + background: var(--bg-feedback-error); + box-shadow: inset 0 0 0 1px var(--border-feedback-error); + color: var(--fg); font-size: var(--fs-small); white-space: pre-wrap; overflow-wrap: anywhere; @@ -133,12 +134,10 @@ justify-content: center; min-width: 18px; height: 18px; - padding: 0 6px; - border-radius: 999px; - background: var(--bg-hover); + padding: 0 4px; color: var(--fg-muted); - font-size: 11px; - font-weight: 600; + font-size: var(--fs-tiny); + font-variant-numeric: tabular-nums; line-height: 1; } @@ -216,21 +215,19 @@ gap: var(--space-1); height: 18px; padding: 0 6px; - border-radius: var(--radius-small, 3px); + border-radius: var(--radius-small); background: var(--bg-floating-toolbar); color: var(--fg-secondary); font-size: var(--fs-tiny); - font-weight: 500; white-space: nowrap; } +/* Tags share one neutral fill; only a warning colours its text. */ .tagAccent { - background: color-mix(in srgb, var(--accent) 18%, var(--bg-elev)); - color: var(--link); + color: var(--fg-strong); } .tagWarning { - background: color-mix(in srgb, var(--warning) 18%, var(--bg-elev)); color: var(--warning); } diff --git a/src/features/agents/session/ContextMeter.tsx b/src/features/agents/session/ContextMeter.tsx index 1beb3b4e4b..2368a5bb2d 100644 --- a/src/features/agents/session/ContextMeter.tsx +++ b/src/features/agents/session/ContextMeter.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react"; import type { AgentContextUsage, AgentTask, AgentUsage } from "@/bindings"; import { call, commands } from "@/platform/ipc"; import { useTx } from "@/platform/i18n"; -import { Popup, T, tooltipAttrs } from "@/ui"; +import { Button, Popup, T, tooltipAttrs } from "@/ui"; import { usageLabel } from "../composerModel"; import { isBusy } from "../model"; import { resendMessage } from "../store"; @@ -166,14 +166,14 @@ function ContextDetails({ task, onClose, closing }: { task: AgentTask; onClose: )} {task.commands.some((c) => c.name === "compact") && ( - + )} )} diff --git a/src/features/agents/session/ProcessRows.tsx b/src/features/agents/session/ProcessRows.tsx index fda73de5c9..51ba70c330 100644 --- a/src/features/agents/session/ProcessRows.tsx +++ b/src/features/agents/session/ProcessRows.tsx @@ -135,7 +135,9 @@ export const ProcessRun = memo(function ProcessRun({ summary={ - {parts.join(" · ")} + + {parts.join(" · ")} + {added > 0 && +{added}} {removed > 0 && −{removed}} {current && {current}} diff --git a/src/features/agents/session/toolEntries.tsx b/src/features/agents/session/toolEntries.tsx index 1a0e357049..3f6905cbfa 100644 --- a/src/features/agents/session/toolEntries.tsx +++ b/src/features/agents/session/toolEntries.tsx @@ -111,7 +111,7 @@ export const ToolEntry = memo(function ToolEntry({ const head = ( <> - + {title} {links.map((path) => ( @@ -144,8 +144,8 @@ export const ToolEntry = memo(function ToolEntry({ +{d.added} −{d.removed} ))} - {run?.exitCode != null && ( - + {run?.exitCode != null && run.exitCode !== 0 && ( + {run.exitCode} )} @@ -161,7 +161,7 @@ export const ToolEntry = memo(function ToolEntry({ ); - const className = clsx(styles.process, styles.toolEntry, styles[`kind-${entry.kind}`], live && styles.toolLive); + const className = clsx(styles.process, styles.toolEntry); if (!entry.output) return (
From 8c23c589ca60f5ba49e9f8bba7c77acc7152d1bf Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 25 Nov 2026 14:15:08 +0900 Subject: [PATCH 08/86] feat(run): run JUnit 5 tests of Maven modules without Maven (#5571) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Gutter Run / Debug of JUnit 5 tests in Maven modules now starts OpenIDEA's own JUnit Platform runner (java/junit-runner, built from the in-tree source and embedded by ide-sdk) on the language server's test classpath instead of mvn test, as IDEA runs Maven tests unless build/run actions are delegated to Maven. The runner reports TeamCity service messages to the existing test tree; Debug and Rerun Failed Tests reuse it. The launcher jar of the engine's version comes from the classpath, else from the engine's Maven/Gradle repository folder, else is downloaded once from Maven Central. The runner JVM gets the module's Surefire configuration like IDEA's MavenJUnitPatcher: argLine (with @{...} late replacement), systemPropertyVariables / systemProperties, environmentVariables, workingDirectory, additionalClasspathElements and classpathDependencyExcludes, read from the cached effective POM (else the module POM); the console lists what was applied. Settings › Build Tools › Maven › Run tests using: OpenIDEA (default) or Maven (the previous mvn test -Dtest=... path). JUnit 4-only, TestNG and Gradle tests keep their current runners. Closes #5553 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-build/src/lib.rs | 1 + crates/ide-build/src/surefire.rs | 216 ++++++++++++++++++ crates/ide-core/src/settings.rs | 15 ++ crates/ide-host/src/ops/java.rs | 154 ++++++++++++- crates/ide-sdk/src/java.rs | 84 +++++++ docs/en/guide/build-tools.mdx | 23 +- docs/en/languages/java.mdx | 16 +- docs/zh/guide/build-tools.mdx | 23 +- docs/zh/languages/java.mdx | 16 +- java/junit-runner/README.md | 20 ++ java/junit-runner/build-dependencies.sha256 | 8 + java/junit-runner/build.py | 69 ++++++ java/junit-runner/openidea-junit-runner.jar | Bin 0 -> 5731 bytes .../src/ai/openidea/junit/Runner.java | 198 ++++++++++++++++ java/junit-runner/tests/SampleTest.java | 43 ++++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 30 +++ src/features/run/application.ts | 44 +++- src/features/run/gradleRun.ts | 2 +- src/features/run/java.test.ts | 61 +++++ src/features/run/javaDebug.ts | 3 + src/features/run/javaModule.test.ts | 37 +++ src/features/run/targets.ts | 14 +- src/features/run/testing/index.ts | 2 + src/features/run/testing/rerun.ts | 6 + .../settings/__tests__/languages.test.ts | 3 + .../settings/languages/LanguagePages.tsx | 15 ++ src/features/settings/pages/execution.tsx | 3 + src/platform/javaLaunch.ts | 20 +- src/platform/languageSettings.ts | 4 + src/platform/locales/text/en.json | 3 + src/platform/locales/text/zh.json | 3 + 32 files changed, 1089 insertions(+), 48 deletions(-) create mode 100644 crates/ide-build/src/surefire.rs create mode 100644 java/junit-runner/README.md create mode 100644 java/junit-runner/build-dependencies.sha256 create mode 100644 java/junit-runner/build.py create mode 100644 java/junit-runner/openidea-junit-runner.jar create mode 100644 java/junit-runner/src/ai/openidea/junit/Runner.java create mode 100644 java/junit-runner/tests/SampleTest.java diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs index 6d86c4242b..94e8d7b5bf 100644 --- a/crates/ide-build/src/lib.rs +++ b/crates/ide-build/src/lib.rs @@ -16,6 +16,7 @@ mod process; #[cfg(test)] mod process_numbers; pub mod sbt; +pub mod surefire; mod sync; pub mod web; mod xml; diff --git a/crates/ide-build/src/surefire.rs b/crates/ide-build/src/surefire.rs new file mode 100644 index 0000000000..6ff50410f5 --- /dev/null +++ b/crates/ide-build/src/surefire.rs @@ -0,0 +1,216 @@ +//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of +//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM. +//! +//! Read from the effective POM the last sync cached (Maven merged parents, profiles and +//! `pluginManagement` there), else from the module's own `pom.xml` and its ``. + +use crate::maven::{MavenModel, interpolate}; +use crate::xml::{self, Element}; +use std::collections::{BTreeMap, HashMap}; +use std::path::Path; + +const SUREFIRE: &str = "maven-surefire-plugin"; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SurefireConfig { + /// ``, split into JVM options. + pub arg_line: Vec, + /// `` and the older ``. + pub system_properties: BTreeMap, + /// ``. + pub environment: BTreeMap, + pub working_directory: Option, + /// ``. + pub additional_classpath: Vec, + /// ``: `groupId:artifactId`. + pub classpath_excludes: Vec, +} + +/// The Surefire configuration of the Maven module at `module` (absolute), if it is one. +pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option { + let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok(); + let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?; + let pom = root.join(&project.pom); + let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok(); + // A cache written before the POM last changed would apply an old configuration. + let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| { + let name = path.file_name()?.to_str()?; + if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) { + return None; + } + let root = xml::parse(&xml::read_text(&path)?)?; + let projects: Vec = if root.name == "projects" { + root.children.into_iter().filter(|p| p.name == "project").collect() + } else { + vec![root] + }; + projects.into_iter().find(|p| { + let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned())); + group.as_deref() == Some(project.group_id.as_str()) + && p.text_of("artifactId").as_deref() == Some(&project.artifact_id) + }) + }); + let (element, own) = match effective { + Some(e) => (e, false), + // ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them. + None => (xml::parse(&xml::read_text(&pom)?)?, true), + }; + let mut props: HashMap = element + .child("properties") + .map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect()) + .unwrap_or_default(); + let dir = module.to_string_lossy().into_owned(); + for (key, value) in [ + ("basedir", dir.clone()), + ("project.basedir", dir.clone()), + ("project.build.directory", format!("{dir}/target")), + ("project.groupId", project.group_id.clone()), + ("project.artifactId", project.artifact_id.clone()), + ("project.version", project.version.clone()), + ] { + props.entry(key.into()).or_insert(value); + } + Some(read(&element, &props, own)) +} + +/// `` Surefire's configuration, then its `default-test` execution's. +fn read(project: &Element, props: &HashMap, own: bool) -> SurefireConfig { + let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE); + let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect(); + if own && plugins.is_empty() { + plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect(); + } + let mut configurations: Vec<&Element> = Vec::new(); + for plugin in plugins { + configurations.extend(plugin.child("configuration")); + let default_test = plugin + .list("executions", "execution") + .into_iter() + .find(|e| e.text_of("id").as_deref() == Some("default-test")); + configurations.extend(default_test.and_then(|e| e.child("configuration"))); + } + let value = |text: &str| resolve(text.trim(), props); + let mut config = SurefireConfig::default(); + for c in configurations { + if let Some(arg_line) = c.child("argLine") { + config.arg_line = split_arg_line(&value(&arg_line.text)); + } + for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) { + config.system_properties.insert(p.name.clone(), value(&p.text)); + } + // ``: `` (deprecated, still honoured). + for p in c.list("systemProperties", "property") { + if let Some(name) = p.text_of("name") { + config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default())); + } + } + for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) { + config.environment.insert(e.name.clone(), value(&e.text)); + } + if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) { + config.working_directory = Some(dir); + } + let texts = |list: &str, item: &str| -> Vec { + c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect() + }; + config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement")); + config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude")); + } + config +} + +/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin +/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA). +fn resolve(text: &str, props: &HashMap) -> String { + let mut out = interpolate(text, props); + for open in ["@{", "${"] { + while let Some(start) = out.find(open) { + let Some(len) = out[start..].find('}') else { break }; + let key = &out[start + 2..start + len]; + let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() }; + out.replace_range(start..=start + len, &replacement); + } + } + out.trim().to_owned() +} + +/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes. +fn split_arg_line(line: &str) -> Vec { + let mut out = Vec::new(); + let mut current: Option = None; + let mut quote: Option = None; + for c in line.chars() { + match quote { + Some(q) if c == q => quote = None, + Some(_) => current.get_or_insert_default().push(c), + None if c == '"' || c == '\'' => { + quote = Some(c); + current.get_or_insert_default(); + } + None if c.is_whitespace() => out.extend(current.take()), + None => current.get_or_insert_default().push(c), + } + } + out.extend(current); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const POM: &str = r#" + com.exampleorders1 + true/m2/mockito.jar + + maven-surefire-plugin + + @{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined} + ${openideaFail}${project.build.directory} + oldstyle + UTC + ${basedir}/extra + org.slf4j:slf4j-simple + + default-test${basedir}/work + + "#; + + fn model(dir: &Path) -> MavenModel { + crate::maven::load(dir) + } + + #[test] + fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::write(root.join("pom.xml"), POM).unwrap(); + let cache = root.join("cache"); + std::fs::create_dir_all(&cache).unwrap(); + let config = surefire_config(root, &cache, &model(root), root).unwrap(); + let d = root.to_string_lossy(); + assert_eq!( + config.arg_line, + ["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="] + ); + assert_eq!(config.system_properties["openidea.fail"], "true"); + assert_eq!(config.system_properties["dir"], format!("{d}/target")); + assert_eq!(config.system_properties["old"], "style"); + assert_eq!(config.environment["TZ"], "UTC"); + assert_eq!(config.working_directory, Some(format!("{d}/work"))); + assert_eq!(config.additional_classpath, [format!("{d}/extra")]); + assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]); + + // A sync's effective POM wins: it has what the module inherits. + let effective = POM.replace("", "-Xmx1g ").replace("UTC", "Asia/Tokyo"); + std::fs::write(cache.join("effective-pom-0.xml"), format!("{effective}")).unwrap(); + let config = surefire_config(root, &cache, &model(root), root).unwrap(); + assert_eq!(config.arg_line[0], "-Xmx1g"); + assert_eq!(config.environment["TZ"], "Asia/Tokyo"); + } + + #[test] + fn splits_arg_line_like_surefire() { + assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]); + } +} diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 8b0b579ba0..86703c0cf8 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1657,6 +1657,20 @@ pub struct MavenSettings { /// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT /// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`). pub update_snapshots: bool, + /// Who runs the JUnit 5 tests of the gutter's Run / Debug. + pub run_tests_using: MavenRunTestsUsing, +} + +/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build +/// and run actions are delegated to Maven. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum MavenRunTestsUsing { + /// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`). + #[default] + Ide, + /// Surefire (`mvn test -Dtest=…`). + Maven, } impl MavenSettings { @@ -2318,6 +2332,7 @@ mod maven_linkage_tests { let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap(); assert!(old.runner_jre.is_empty()); assert!(!old.delegate_build); + assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide); assert!(MavenSettings::default().runner_jre.is_empty()); let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old }; let encoded = serde_json::to_string(&settings).unwrap(); diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index f18000ad93..c58512ddc0 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -646,6 +646,129 @@ pub async fn java_build_workspace( result } +/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath: +/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the +/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and, +/// for a Maven module, what its Surefire configuration gives the forked test JVM. +#[command(trust = trusted)] +pub async fn java_junit_runner( + host: &Host, + window: &str, + module: PathBuf, + class_paths: Vec, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + let module = ide_core::project_roots::resolve(&project.root, &module); + let data_dir = host.local_data_dir.clone(); + tokio::task::spawn_blocking(move || { + let scope = workspace::scope_for(&project, &module)?; + let model = load_launch_model(&scope); + let surefire = model + .maven + .as_ref() + .and_then(|maven| ide_build::surefire::surefire_config(&scope.root, &scope.cache, maven, &module)) + .unwrap_or_default(); + let runner = ide_sdk::java::junit_runner_jar(&data_dir) + .ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?; + let launcher = match ide_sdk::java::junit_launcher(&class_paths) { + ide_sdk::java::JunitLauncher::OnClasspath => None, + ide_sdk::java::JunitLauncher::Found(path) => Some(path), + ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?), + ide_sdk::java::JunitLauncher::NoPlatform => { + return Err(IdeError::unavailable( + "No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \ + Maven, set Settings › Build Tools › Maven › Run tests using to Maven.", + )); + } + }; + Ok(junit_launch(&module, class_paths, surefire, [Some(runner), launcher].into_iter().flatten())) + }) + .await + .map_err(|e| IdeError::internal(e.to_string()))? +} + +/// The test JVM of OpenIDEA's JUnit runner. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct JunitLaunch { + pub class_paths: Vec, + /// Surefire's `argLine`, then its system properties as `-Dkey=value`. + pub vm_args: Vec, + pub env: std::collections::BTreeMap, + pub working_directory: Option, + /// The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console. + pub surefire: Vec, +} + +fn junit_launch( + module: &Path, + class_paths: Vec, + surefire: ide_build::surefire::SurefireConfig, + runner: impl Iterator, +) -> JunitLaunch { + let mut applied = Vec::new(); + let mut note = |used: bool, name: &str| { + if used { + applied.push(name.to_owned()); + } + }; + note(!surefire.arg_line.is_empty(), "argLine"); + note(!surefire.system_properties.is_empty(), "systemPropertyVariables"); + note(!surefire.environment.is_empty(), "environmentVariables"); + note(surefire.working_directory.is_some(), "workingDirectory"); + note(!surefire.additional_classpath.is_empty(), "additionalClasspathElements"); + note(!surefire.classpath_excludes.is_empty(), "classpathDependencyExcludes"); + // `group:artifact` in a Maven repository (`g/r/p/artifact/…`) or the Gradle cache (`g.r.p/artifact/…`). + let excluded = |path: &str| { + let path = path.replace('\\', "/"); + surefire.classpath_excludes.iter().any(|e| { + e.split_once(':').is_some_and(|(group, artifact)| { + path.contains(&format!("/{}/{artifact}/", group.replace('.', "/"))) + || path.contains(&format!("/{group}/{artifact}/")) + }) + }) + }; + let mut class_paths: Vec = class_paths.into_iter().filter(|p| !excluded(p)).collect(); + class_paths.extend(surefire.additional_classpath); + class_paths.extend(runner.map(|p| p.to_string_lossy().into_owned())); + let mut vm_args = surefire.arg_line; + vm_args.extend(surefire.system_properties.into_iter().map(|(k, v)| format!("-D{k}={v}"))); + JunitLaunch { + class_paths, + vm_args, + env: surefire.environment, + working_directory: surefire.working_directory.map(|d| module.join(d).to_string_lossy().into_owned()), + surefire: applied, + } +} + +fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult { + if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) { + return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'"))); + } + let name = format!("junit-platform-launcher-{version}.jar"); + let dest = data_dir.join("junit").join(&name); + if dest.is_file() { + return Ok(dest); + } + std::fs::create_dir_all(dest.parent().expect("has a parent"))?; + let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}"); + let partial = dest.with_extension("jar.part"); + // ponytail: unverified like the Lombok download (Central publishes SHA-1 only); HTTPS from Central. + let fetched = ide_tools::Http::new(&ide_core::tool_path::search_path()) + .map(ide_tools::Http::https_only) + .and_then(|http| http.download(&url, &partial, None, &CancellationToken::new(), &|_| {})) + .and_then(|()| Ok(std::fs::rename(&partial, &dest)?)); + fetched.map(|()| dest).map_err(|e| { + IdeError::unavailable(format!( + "Cannot download {name} from Maven Central ({}). Add org.junit.platform:junit-platform-launcher to the \ + test dependencies, or set Settings › Build Tools › Maven › Run tests using to Maven.", + e.message + )) + }) +} + /// An annotation processor's error for writing a file this build already wrote (JDT's /// `IdeFilerImpl`: "Source file already created", javac's Filer: "Attempt to recreate a file"). fn processor_recreated_a_file(message: &str) -> bool { @@ -663,6 +786,35 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) { mod tests { use super::*; + #[test] + fn junit_launch_applies_the_surefire_configuration() { + let surefire = ide_build::surefire::SurefireConfig { + arg_line: vec!["-Xmx1g".into()], + system_properties: [("openidea.fail".to_owned(), "true".to_owned())].into(), + environment: [("TZ".to_owned(), "UTC".to_owned())].into(), + working_directory: Some("work".into()), + additional_classpath: vec!["/extra".into()], + classpath_excludes: vec!["org.slf4j:slf4j-simple".into(), "com.acme:gone".into()], + }; + let classpath = vec![ + "/m/target/test-classes".into(), + "/m2/org/slf4j/slf4j-simple/2.0/slf4j-simple-2.0.jar".into(), + "/gradle/files-2.1/com.acme/gone/1/abc/gone-1.jar".into(), + "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar".into(), + ]; + let launch = junit_launch(Path::new("/m"), classpath, surefire, [PathBuf::from("/runner.jar")].into_iter()); + assert_eq!( + launch.class_paths, + ["/m/target/test-classes", "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar", "/extra", "/runner.jar"] + ); + assert_eq!(launch.vm_args, ["-Xmx1g", "-Dopenidea.fail=true"]); + assert_eq!(launch.env["TZ"], "UTC"); + assert_eq!(launch.working_directory.as_deref(), Path::new("/m").join("work").to_str()); + assert_eq!(launch.surefire.len(), 6); + let plain = junit_launch(Path::new("/m"), vec![], Default::default(), std::iter::empty()); + assert!(plain.surefire.is_empty() && plain.vm_args.is_empty() && plain.working_directory.is_none()); + } + fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf { let bin = dir.join("bin"); std::fs::create_dir_all(&bin).unwrap(); @@ -946,4 +1098,4 @@ mod tests { } } -ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch); +ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_junit_runner, java_resolve_launch); diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index f9df8d5fa8..71804aeea9 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1644,6 +1644,90 @@ pub fn jdbc_bridge_jar(data_dir: &Path) -> Option { ) } +/// Extracts the JUnit Platform test runner (`java/junit-runner`) into the application's data directory. +pub fn junit_runner_jar(data_dir: &Path) -> Option { + install_bundle( + data_dir, + "junit-runner", + "1.0.0", + include_bytes!("../../../java/junit-runner/openidea-junit-runner.jar"), + ) +} + +/// The JUnit Platform launcher a test classpath needs to start the runner. +#[derive(Debug, PartialEq)] +pub enum JunitLauncher { + /// The classpath has `junit-platform-launcher` already. + OnClasspath, + /// `junit-platform-launcher` of the engine's version, next to the engine jar in its repository. + Found(PathBuf), + /// Not found locally: the engine's version, to download. + Missing(String), + /// No `junit-platform-engine` on the classpath (JUnit 4 alone, TestNG). + NoPlatform, +} + +/// Like IDEA, the launcher must match the engine's version: a project usually depends on +/// `junit-jupiter` only, which brings the engine but no launcher. The Maven local repository +/// (`…/junit-platform-engine//…jar`) and the Gradle cache (`…/junit-platform-engine///…jar`) +/// keep the launcher in a sibling folder. +pub fn junit_launcher(class_paths: &[String]) -> JunitLauncher { + let name = |p: &str| Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or_default().to_owned(); + if class_paths.iter().any(|p| name(p).starts_with("junit-platform-launcher-")) { + return JunitLauncher::OnClasspath; + } + let Some((engine, version)) = class_paths.iter().find_map(|p| { + let version = name(p).strip_prefix("junit-platform-engine-")?.strip_suffix(".jar")?.to_owned(); + Some((PathBuf::from(p), version)) + }) else { + return JunitLauncher::NoPlatform; + }; + let jar = format!("junit-platform-launcher-{version}.jar"); + let artifact = engine.ancestors().find(|a| a.file_name().is_some_and(|n| n == "junit-platform-engine")); + let launcher_dir = artifact.and_then(Path::parent).map(|d| d.join("junit-platform-launcher").join(&version)); + let found = launcher_dir.and_then(|dir| { + let direct = dir.join(&jar); + if direct.is_file() { + return Some(direct); + } + std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path().join(&jar)).find(|p| p.is_file()) + }); + match found { + Some(path) => JunitLauncher::Found(path), + None => JunitLauncher::Missing(version), + } +} + +#[cfg(test)] +mod junit_launcher_tests { + use super::{JunitLauncher, junit_launcher}; + + #[test] + fn finds_the_launcher_of_the_engine_version_in_maven_and_gradle_repositories() { + let dir = tempfile::tempdir().unwrap(); + let s = |p: &std::path::Path| p.to_string_lossy().into_owned(); + let maven = dir.path().join("m2/org/junit/platform"); + let maven_engine = maven.join("junit-platform-engine/1.11.3/junit-platform-engine-1.11.3.jar"); + let maven_launcher = maven.join("junit-platform-launcher/1.11.3/junit-platform-launcher-1.11.3.jar"); + let gradle = dir.path().join("gradle/files-2.1/org.junit.platform"); + let gradle_engine = gradle.join("junit-platform-engine/1.10.2/aaa/junit-platform-engine-1.10.2.jar"); + let gradle_launcher = gradle.join("junit-platform-launcher/1.10.2/bbb/junit-platform-launcher-1.10.2.jar"); + for jar in [&maven_engine, &maven_launcher, &gradle_engine, &gradle_launcher] { + std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); + std::fs::write(jar, "").unwrap(); + } + assert_eq!(junit_launcher(&["classes".into(), s(&maven_engine)]), JunitLauncher::Found(maven_launcher)); + assert_eq!(junit_launcher(&[s(&gradle_engine)]), JunitLauncher::Found(gradle_launcher)); + let other = dir.path().join("lib/junit-platform-engine-1.9.0.jar"); + assert_eq!(junit_launcher(&[s(&other)]), JunitLauncher::Missing("1.9.0".into())); + assert_eq!( + junit_launcher(&[s(&other), "/x/junit-platform-launcher-1.9.0.jar".into()]), + JunitLauncher::OnClasspath + ); + assert_eq!(junit_launcher(&["/x/junit-4.13.2.jar".into()]), JunitLauncher::NoPlatform); + } +} + /// Installs the app-owned JDT LS bundle that inspects java-debug's JVMs. pub fn jvm_inspect_bundle(data_dir: &Path) -> Option { install_bundle( diff --git a/docs/en/guide/build-tools.mdx b/docs/en/guide/build-tools.mdx index 4ad2cb0603..90ca774969 100644 --- a/docs/en/guide/build-tools.mdx +++ b/docs/en/guide/build-tools.mdx @@ -62,17 +62,18 @@ When you edit a POM in the editor, the tool window shows **Build files changed s **Settings › Build, Execution, Deployment › Maven**: -| Setting | What it does | -| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| **Delegate IDE build/run actions to Maven** | Run and Debug build Maven modules with Maven (`javac`) instead of jdtls | -| **JRE** | JDK for Maven sync, builds, goals and tests | -| **Maven home path** | A Maven installation to use instead of the project's `mvnw` | -| **User settings file** | Passed as `-s` | -| **Toolchains file** | Passed as `-t` | -| **Local repository** | Passed as `-Dmaven.repo.local` | -| **Active profiles** | Comma-separated profiles (`-P`); `!id` excludes one | -| **Thread count** | Passed as `-T` (for example `4` or `2C`) | -| **Use Maven Daemon (mvnd)** | Runs builds, sync and run configurations through `mvnd`; falls back to `mvn` if it is missing or the JDK is older than 17 | +| Setting | What it does | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Delegate IDE build/run actions to Maven** | Run and Debug build Maven modules with Maven (`javac`) instead of jdtls | +| **Run tests using** | **OpenIDEA** (default): a JUnit 5 test run from the gutter starts on jdtls' test classpath, without Maven, with the module's Surefire configuration. **Maven**: Surefire | +| **JRE** | JDK for Maven sync, builds, goals and tests | +| **Maven home path** | A Maven installation to use instead of the project's `mvnw` | +| **User settings file** | Passed as `-s` | +| **Toolchains file** | Passed as `-t` | +| **Local repository** | Passed as `-Dmaven.repo.local` | +| **Active profiles** | Comma-separated profiles (`-P`); `!id` excludes one | +| **Thread count** | Passed as `-T` (for example `4` or `2C`) | +| **Use Maven Daemon (mvnd)** | Runs builds, sync and run configurations through `mvnd`; falls back to `mvn` if it is missing or the JDK is older than 17 | ## Gradle diff --git a/docs/en/languages/java.mdx b/docs/en/languages/java.mdx index cc6949f822..9c804c8633 100644 --- a/docs/en/languages/java.mdx +++ b/docs/en/languages/java.mdx @@ -100,16 +100,18 @@ In a Maven project with Kotlin sources, OpenIDEA builds the Kotlin code in the b ## Run and test -| What | How it runs | -| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | -| `main` method | **Application** configuration on the module's runtime or test classpath. Java 25 instance `main` methods are recognized. | -| `@SpringBootApplication` class | **Spring Boot** configuration, with active profiles and update actions | -| Executable jar | **JAR Application** configuration | -| WAR | **Tomcat Server** configuration on a local Tomcat installation (the IDE never writes into it) | -| JUnit 4, JUnit 5 and TestNG tests | Maven (Surefire `-Dtest=…`) or Gradle (`--tests …`) test configurations | +| What | How it runs | +| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `main` method | **Application** configuration on the module's runtime or test classpath. Java 25 instance `main` methods are recognized. | +| `@SpringBootApplication` class | **Spring Boot** configuration, with active profiles and update actions | +| Executable jar | **JAR Application** configuration | +| WAR | **Tomcat Server** configuration on a local Tomcat installation (the IDE never writes into it) | +| JUnit 4, JUnit 5 and TestNG tests | Maven (Surefire `-Dtest=…`) or Gradle (`--tests …`) test configurations; JUnit 5 in a Maven module runs on jdtls' test classpath | Gutter icons on main methods, test classes and test methods create these configurations, and Maven and Gradle run configurations are detected from the build files. For Gradle, **Build and run using** decides whether an Application runs as a Gradle `JavaExec` task (the default) or is launched by OpenIDEA on the classpath reported by jdtls. +A JUnit 5 test class or method run from the gutter of a Maven module starts on jdtls' test classpath with OpenIDEA's JUnit Platform runner, without Maven, like IDEA (**Settings › Build, Execution, Deployment › Maven › Run tests using**). The runner adds `junit-platform-launcher` of the engine's version when the project has none (from the local repository, else downloaded once from Maven Central). As in IDEA, the test JVM gets the module's Surefire configuration: `argLine` (with `@{…}` late replacement), `systemPropertyVariables`, `environmentVariables`, `workingDirectory`, `additionalClasspathElements` and `classpathDependencyExcludes`, read from the effective POM of the last Maven sync (before a sync, from the module's own `pom.xml`). Resource filtering and Surefire's other settings (forking, includes, groups) don't apply; choose **Maven** to run through Surefire. + Test results are read from the JUnit XML reports Maven and Gradle write, so passed tests are listed as well. The test tree supports rerunning failed tests. VM options of a Gradle run configuration are applied to the JVMs Gradle forks (`run`, `bootRun`, `test`). When a classpath is too long for the command line (common on Windows), it is moved into an argument file or a manifest-only jar. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing). diff --git a/docs/zh/guide/build-tools.mdx b/docs/zh/guide/build-tools.mdx index c0169ba657..40a39d430d 100644 --- a/docs/zh/guide/build-tools.mdx +++ b/docs/zh/guide/build-tools.mdx @@ -62,17 +62,18 @@ Maven 和 Gradle 使用设置里配置的 wrapper 或本地安装(见下文) **设置 › 构建、执行、部署 › Maven**: -| 设置 | 作用 | -| ------------------------------------ | ------------------------------------------------------------------------------- | -| **将 IDE 构建/运行操作委托给 Maven** | 运行和调试时用 Maven(`javac`)构建 Maven 模块,而不是 jdtls | -| **JRE** | Maven 同步、构建、目标和测试使用的 JDK | -| **Maven 主路径** | 使用指定的 Maven 安装,而不是项目里的 `mvnw` | -| **用户设置文件** | 作为 `-s` 传入 | -| **Toolchains 文件** | 作为 `-t` 传入 | -| **本地仓库** | 作为 `-Dmaven.repo.local` 传入 | -| **活动 profiles** | 逗号分隔的 profile(`-P`),`!id` 表示排除 | -| **线程数** | 作为 `-T` 传入(如 `4` 或 `2C`) | -| **使用 Maven Daemon (mvnd)** | 构建、同步和运行配置都通过 `mvnd` 执行;找不到 mvnd 或 JDK 低于 17 时退回 `mvn` | +| 设置 | 作用 | +| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **将 IDE 构建/运行操作委托给 Maven** | 运行和调试时用 Maven(`javac`)构建 Maven 模块,而不是 jdtls | +| **运行测试使用** | **OpenIDEA**(默认):从装订区域运行的 JUnit 5 测试直接在 jdtls 的测试类路径上启动,不经过 Maven,并应用模块的 Surefire 配置;**Maven**:通过 Surefire 运行 | +| **JRE** | Maven 同步、构建、目标和测试使用的 JDK | +| **Maven 主路径** | 使用指定的 Maven 安装,而不是项目里的 `mvnw` | +| **用户设置文件** | 作为 `-s` 传入 | +| **Toolchains 文件** | 作为 `-t` 传入 | +| **本地仓库** | 作为 `-Dmaven.repo.local` 传入 | +| **活动 profiles** | 逗号分隔的 profile(`-P`),`!id` 表示排除 | +| **线程数** | 作为 `-T` 传入(如 `4` 或 `2C`) | +| **使用 Maven Daemon (mvnd)** | 构建、同步和运行配置都通过 `mvnd` 执行;找不到 mvnd 或 JDK 低于 17 时退回 `mvn` | ## Gradle diff --git a/docs/zh/languages/java.mdx b/docs/zh/languages/java.mdx index 7336c015dd..d8a6b55c0b 100644 --- a/docs/zh/languages/java.mdx +++ b/docs/zh/languages/java.mdx @@ -100,16 +100,18 @@ IDE 会把代理设置传给 jdtls,所以在代理环境下也能解析依赖 ## 运行与测试 -| 对象 | 运行方式 | -| ----------------------------- | -------------------------------------------------------------------------------- | -| `main` 方法 | **应用程序** 配置,使用模块的运行时或测试类路径;支持 Java 25 的实例 `main` 方法 | -| `@SpringBootApplication` 类 | **Spring Boot** 配置,可设置活动 profile 和更新操作 | -| 可执行 jar | **JAR 应用程序** 配置 | -| WAR | **Tomcat 服务器** 配置,运行在本地 Tomcat 安装上(IDE 不会往安装目录里写东西) | -| JUnit 4、JUnit 5、TestNG 测试 | Maven(Surefire `-Dtest=…`)或 Gradle(`--tests …`)测试配置 | +| 对象 | 运行方式 | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `main` 方法 | **应用程序** 配置,使用模块的运行时或测试类路径;支持 Java 25 的实例 `main` 方法 | +| `@SpringBootApplication` 类 | **Spring Boot** 配置,可设置活动 profile 和更新操作 | +| 可执行 jar | **JAR 应用程序** 配置 | +| WAR | **Tomcat 服务器** 配置,运行在本地 Tomcat 安装上(IDE 不会往安装目录里写东西) | +| JUnit 4、JUnit 5、TestNG 测试 | Maven(Surefire `-Dtest=…`)或 Gradle(`--tests …`)测试配置;Maven 模块中的 JUnit 5 直接在 jdtls 的测试类路径上运行 | main 方法、测试类和测试方法旁的边栏图标会创建这些配置;Maven 和 Gradle 的运行配置会从构建文件中自动检测。对 Gradle 项目,**构建和运行使用** 决定“应用程序”是作为 Gradle 的 `JavaExec` 任务运行(默认),还是由 OpenIDEA 用 jdtls 给出的类路径直接启动。 +在 Maven 模块的装订区域运行 JUnit 5 测试类或方法时,OpenIDEA 用自带的 JUnit Platform 运行器在 jdtls 的测试类路径上直接启动,不经过 Maven,与 IDEA 一致(**设置 › 构建、执行、部署 › Maven › 运行测试使用**)。项目没有 `junit-platform-launcher` 时,运行器会补上与 engine 同版本的 launcher(先找本地仓库,找不到再从 Maven Central 下载一次)。与 IDEA 一样,测试 JVM 会应用模块的 Surefire 配置:`argLine`(支持 `@{…}` 晚替换)、`systemPropertyVariables`、`environmentVariables`、`workingDirectory`、`additionalClasspathElements` 和 `classpathDependencyExcludes`,取自最近一次 Maven 同步的有效 POM(同步前取模块自己的 `pom.xml`)。资源过滤和 Surefire 的其他设置(fork、includes、groups)不会生效;需要时请选 **Maven**,通过 Surefire 运行。 + 测试结果从 Maven 和 Gradle 生成的 JUnit XML 报告中读取,通过的测试也会列出;测试树支持只重跑失败的测试。Gradle 运行配置的 VM 选项会作用到 Gradle fork 出来的 JVM(`run`、`bootRun`、`test`)。类路径超出命令行长度限制时(Windows 上常见),会改用参数文件或只含 manifest 的 jar。 另见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。 diff --git a/java/junit-runner/README.md b/java/junit-runner/README.md new file mode 100644 index 0000000000..ac96fc8028 --- /dev/null +++ b/java/junit-runner/README.md @@ -0,0 +1,20 @@ +# JUnit Platform runner + +`ai.openidea.junit.Runner` runs the JUnit Platform tests named by its arguments +(`com.acme.OrderTest`, `com.acme.OrderTest#method`; a method selects every overload, so +parameterized tests run too) and prints each test as the TeamCity service messages of +`src/features/run/gradleTests.gradle`, which the Run window's JVM parser already reads. It exits +with 1 when a test failed or none ran. + +OpenIDEA starts it for the gutter's JUnit 5 tests of Maven modules (Settings › Maven › Run tests +using: OpenIDEA) as `java -ea -cp :: ai.openidea.junit.Runner …`. +`ide_sdk::java::junit_launcher` picks `junit-platform-launcher` of the engine's version, and +`ide_build::surefire` reads the module's Surefire configuration for the JVM (IDEA's `MavenJUnitPatcher`). + +The jar is committed and embedded by `ide-sdk` (`junit_runner_jar`). Rebuild it after changing +the source, and check it against JUnit with: + +```sh +python3 build.py --test +python3 build.py +``` diff --git a/java/junit-runner/build-dependencies.sha256 b/java/junit-runner/build-dependencies.sha256 new file mode 100644 index 0000000000..ce6d9f8184 --- /dev/null +++ b/java/junit-runner/build-dependencies.sha256 @@ -0,0 +1,8 @@ +b4727459201b0011beb0742bd807421a1fc8426b116193031ed87825bc2d4f04 org/junit/platform/junit-platform-launcher/1.11.3/junit-platform-launcher-1.11.3.jar +0043f72f611664735da8dc9a308bf12ecd2236b05339351c4741edb4d8fab0da org/junit/platform/junit-platform-engine/1.11.3/junit-platform-engine-1.11.3.jar +be262964b0b6b48de977c61d4f931df8cf61e80e750cc3f3a0a39cdd21c1008c org/junit/platform/junit-platform-commons/1.11.3/junit-platform-commons-1.11.3.jar +b509448ac506d607319f182537f0b35d71007582ec741832a1f111e5b5b70b38 org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar +48e2df636cab6563ced64dcdff8abb2355627cb236ef0bf37598682ddf742f1b org/opentest4j/opentest4j/1.3.0/opentest4j-1.3.0.jar +5d8147a60f49453973e250ed68701b7ff055964fe2462fc2cb1ec1d6d44889ba org/junit/jupiter/junit-jupiter-api/5.11.3/junit-jupiter-api-5.11.3.jar +e62420c99f7c0d59a2159a2ef63e61877e9c80bd722c03ca8bf3bdcea050a589 org/junit/jupiter/junit-jupiter-engine/5.11.3/junit-jupiter-engine-5.11.3.jar +0f798ebec744c4e6605fd4f2072f41a8e989e2d469e21db5aa67cf799c0b51ec org/junit/jupiter/junit-jupiter-params/5.11.3/junit-jupiter-params-5.11.3.jar diff --git a/java/junit-runner/build.py b/java/junit-runner/build.py new file mode 100644 index 0000000000..cd879edfc0 --- /dev/null +++ b/java/junit-runner/build.py @@ -0,0 +1,69 @@ +"""Build the committed JUnit Platform runner (Java 8 bytecode), or test it: python3 build.py [--test]. + +Compiles against the JUnit jars of build-dependencies.sha256, taken from the local Maven +repository (MAVEN_REPO, default ~/.m2/repository; `mvn dependency:get` fetches a missing one). +--test runs tests/SampleTest.java through the runner and checks its service messages.""" +import hashlib +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import zipfile + +root = Path(__file__).resolve().parent +repo = Path(os.environ.get("MAVEN_REPO", Path.home() / ".m2" / "repository")) +java_home = os.environ.get("JAVA_HOME") +test = "--test" in sys.argv[1:] + + +def tool(name): + return str(Path(java_home) / "bin" / name) if java_home else name + + +jars = [] +for line in (root / "build-dependencies.sha256").read_text().splitlines(): + digest, path = line.split() + jar = repo / path + if hashlib.sha256(jar.read_bytes()).hexdigest() != digest: + sys.exit(f"{jar}: SHA-256 mismatch") + jars.append(str(jar)) +# The launcher API only: the runner must not depend on an engine. +api = [j for j in jars if "/junit-platform-" in j or "apiguardian" in j] + +with tempfile.TemporaryDirectory() as scratch: + classes = Path(scratch) / "classes" + sources = sorted((root / "src").rglob("*.java")) + subprocess.run([tool("javac"), "--release", "8", "-encoding", "UTF-8", "-g", "-Xlint:-options", + "-cp", os.pathsep.join(api), "-d", str(classes), *map(str, sources)], check=True) + if test: + sample = Path(scratch) / "sample" + cp = os.pathsep.join(jars) + subprocess.run([tool("javac"), "-encoding", "UTF-8", "-cp", cp, "-d", str(sample), + str(root / "tests" / "SampleTest.java")], check=True) + run = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]), + "ai.openidea.junit.Runner", "sample.SampleTest"], capture_output=True) + out = run.stdout.decode("utf-8") + print(out) + expected = [ + "##teamcity[testStarted name='passes' className='sample.SampleTest']", + "##teamcity[testStdOut name='passes' className='sample.SampleTest' out='hello |[ünï|]|n']", + "##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'", + "##teamcity[testIgnored name='disabled' className='sample.SampleTest'", + "##teamcity[testIgnored name='aborted' className='sample.SampleTest']", + "##teamcity[testFailed name='parameterized' className='sample.SampleTest'", + "##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=", + "7 tests completed, 2 failed, 2 skipped", + ] + missing = [e for e in expected if e not in out] + assert not missing, missing + assert run.returncode == 1, run.returncode + method = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]), + "ai.openidea.junit.Runner", "sample.SampleTest#parameterized"], capture_output=True) + assert method.stdout.decode().count("testStarted") == 2, method.stdout + print("ok") + sys.exit(0) + with zipfile.ZipFile(root / "openidea-junit-runner.jar", "w") as jar: + for path in sorted(classes.rglob("*.class")): + entry = zipfile.ZipInfo(path.relative_to(classes).as_posix(), (2026, 1, 1, 0, 0, 0)) + jar.writestr(entry, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED) diff --git a/java/junit-runner/openidea-junit-runner.jar b/java/junit-runner/openidea-junit-runner.jar new file mode 100644 index 0000000000000000000000000000000000000000..c9d74763bf2cc2d5aa8b03c7760a81377433dbaf GIT binary patch literal 5731 zcmaKwS2P@q7wrWRWe~j+z4wV0C39-ac1Hj3Cr-;m^Z#_MQ$GDLw%K0AFR%P5JqAPDT4# zYy1o>LdYM{t7L$-V~pu%9wXOgRae*MMe6S^)h}(E!TidfU8xaD^pw#NGqFCKDDAyz3D7s=!E=ff3><@P-5feD$1W=_MMGg~~0ya1*m0AiT7 zA6NW4ZMu?zZyeP3w~*K9opU0- zDud*pa*}Sl z9ZCjCcq(aKn_X~ehA#ojjK{nFRt(J-;WfPr~0CcpBs@sm1`%~%jB z>>omaA~a=WYBc_hs3~htQz`B9gGUB)_ec+r$2N;b?cM!C0b@?Py?%zm5S$A<8>#UY=kd|}Ph*0GeRMOFLpLjFh zD88Z^=k+Cl6K{I>ZU5ZPVw+ehzDj`kMV^GK@wg^OdYRHz0pU{XkJl!*5^9WzvJRWx z7wd%m!&!YbLC+`y>ptzgj?GA+66LPgcGvAia2j~I>ax-8Qj>0|dUEaXY9Y+*tOcj{ z+{r$w$tdNPxAJyxSPxG@`FUUaQpHx=&SFTatbbfo^?n)|I{Sksu_?RZvF0GNHMs*w z>s!qPuM(8S1O3=Z&6`IEi*e~L(ubmrKIv@!2=0y~s{3#%&-{ZC{3Uq+`NPu3dmqZ+ zWd<^!s&->Xu$(jlF0I^}WAA_92@P{1oRfz{s%PkrR-rE<3eJ@gnYk>w<)#L&II!_L zm;10QRNp_dl+}{sQkfwkYf9N<$*cZEc)}G}i8Fg89z~$vFUW8tw;cQX*{oXFa*-bwXeVRd*a?}eK6|TNp37wvJ%!uT zRmp=MVK*lj9S67VQsb};ROd8EdjN3Oj7%}yfRm9Y8YbnZv6HryE{l}0NJlzY2cSn8 zmzu?k`)uxl7bjq6{;3r7WV^U820>W7?Zuxw*_~K9Mq}5)Cz>znDI9DHDoe8l^G8$_smbeSA|D`Rx3~l6aI_y)fN?5tn|ysVde_8N@Q{uhc>mLm)mW z#rVo(n$Zil;p$Bp{uL_XhQhIz&1;vAL)9c+`b9rb^F0yjevD$Dhqv557}~#JnCy3t zBH9|injphTjP3ZLt>P%f+Ry{p^pfoprPge^R!O!r5~I}T+%byX;3f{G(<1}C!fvdX z%wnBjggqUh$;NEH-wa*tH68-WrJ5`-X<_h_QS>+T-P2_KaqfCURe`-2qal5DAEO%u zr9TCWix6)=AQeH)Dn*@bf1ONsrXbJ4*Dw0^Wh>6rpGJzjw(>m~Zb-T(US+vExn%zN zw%!#vBD#v&xs!oeZ^9d*+gq}mxJI{_f8lG)v?~)hlanb(oKtv(@CpYQa10*V>FB>X zcEW=tyz^Ae|G|TVx?1uul5nQ}UJSm#hL!9r;lZMQIv%Tp1c6iyJElCx$qOsKnr0{F z_=?~34E*-H@9Sl`;2v%-`0n&nwEQLFEPVf|hMIGW9>v?FhlSpW8wRI{ z=kTSuq$?LzE7dvO#y9sJk;WIKRxT}RZ|al@8WU>?ZSx*!9;$Z~@T>-oJq)PrnWkwg zyK?b8gI}^I2ccv#!91yJg5~JPI6IjQ;5qeQqR`&194uvv<;-7`2H+Hh0G-mVw$zWn zTt+-;PV5OdiH%$Pqzb=JDZ-DTn1Y2omkdff$x630RwKKQoI^Y=`l_|^>>}>@aCD1^ z>6IM>dbPQBqPFd#vl>5MeS6!cNJV~~Xa61g=XpK@F{nLDuQ^s|Q8UyUjVnG>0}r)0 zp8PY%A){J0hNr_Se{>6X%6rdOIi*?L-+4%GlUAIm%^4%82G5rt$m8u(FQW&>mo~mu z)sx^CRyYbYsr@((kW8P^&MKLAi*ot;rEb&y#13ZK<)$-Hk!JBZXBWFXkKXr^0qCS} z??Alw0Zz`aZS+2U2iZn$2#AF5i~bxfQ5glmg$!T@z+xu9Wh3Zl+XljZ>A(Rd)3?bDe4Xt^{F(F?sP*$8!hi+GPiuQE80# zwIgPwmwthMNo25=la5e}L|BZBj++si=`jQ*nuvkw)wW(E>2g;I&-el_0VQ8kr;Fn8 z+{xjs?rF?2`T63{^tW+Rmbfl9gM)rLUSG^kE7K68>!T)~v@aKEjqbK*lfJOA8v2f{ zB@;;cv4!5)iP;eG6hKHGGB_(}>I9qmNb%{6CTY%DKi%6C*v*$yC(Dywath=T(7HOG zb3=*xr~p2ZSBkYJ#Z4ZT>|^R)W?1|5`+agkPJAiB0CJ-h8fo~y{X``a*@W;uf$OG| zbYo9o&Pthagxa;|yw4nm&r&;8Iv}-*#xo(UR`Dy>FCDE9hFj_CVm9`6OM?z85U-5Z zxCPs@u*i(gkgh?JxYZm19LrLC2Zd1>I^W#hf@P7cPtO8XSp@Q)U466g--YAH#js?) z8RGcD5Y?vD;*0bxSq9aH)$_zvcxPGh37 z8@$_aUrjL8?^GY%q|6)&ymxAv@)PSTA^mOHl}RX}wm6eER}H^_>}2=QfsLbcF+!We zSO=t3$Y<#|_0dJ;vsaYpBFe`4N{Q9zzdnw2>#>5!`TX54q67ZfY?*@4r^c$-voF>% z7{-yag7S12&vBfa)>r%o_KtxuPH&p|+fA~#<1e0gfoUSn(F3oL|D>RQ^ceF9 z#wP38jSrff!ZXUl?)VIt^f}jM$JUQZCh6JAF9v^szbtvOQ4spBrUykka2Ge;aBUYx z=9bm`Yx^orLH<;2zumJajJJI^P*xQ;@O?6P#gPSI@#~Q}>ax_o{suxJ}=vs{kiQE~ubN#S07 z|5%$ihw=Jb86#@)9?Mk;Evx3Zqj_DEC&;#p$s_|!W-%cxU0LY~LVoolz12Mna81^P z@Qbv+DK#~zwF~niZPst3N5p|C?6y~rcPBF11+BXcua)#H-_+0Fw8^;ndyr;{$HXG( zLi5n8`(vmU3%ZqCzXYDmO-tr@E((OLfX{%;aP<`0rLk$H-N+8oY{q1>8X<@rJv-FB zwb3%X1T?bW5ji>sJgoWLs^n$b^Gl5&a0iTR)wF=^;#B?pGIene2AxN32z^)4J#wBxL=-rD zedA8Scu!)u$b`4R^r3rCM3bb?+&CQHfs{W9#m}kxP<4RH6exJIvsw1rM=MP(6ZTpm z`o7Xo%}Z57p^)Xu!U(D3VCQ#s_Zx&*^QHuwGxtRgWSj`p$|IZw)kRal(^keyzrt;i z^Yt^}qYB@Rc#Q|mrB1GZDAW&l7CU6d^Wmk?uhZ}g9?h2TEW@3P@;Mv3Xz9C|_0Pi% zmuY*I^HODU#dX_UYn6Qb^(f-iCKc7Qf>$A1zUZwk z>|%o_E5kF9|4d?oG7z^WLwS&)BglvnW{7V2z4(e&+)OOj$!qbq>oB_M{!^3pA)XT5 z(Iq#$U$%@*5@_nNJ*-Q-2c-cQp|og<;+8xhH7;YtV);QSj^FmQ3B9=PivcT$J!X$UJ>zw)(Q zK?CLMq!@Topz5Z|mMrqVxGZ~LA%S0~MS0^BTNZV^t&)e`b#xWjAI5-ZM+0HoOI$6e ze*l@#Gw)OJ*5w1;9Uq-`z5hxZsjn+;D4z3?+`mJQCkN?R#C>!Bn z-<>}(IADfJIPH4bS-;p&Ha$eyRFKsL%#O^ByIQ_;HyP<(jf}r}9v)7a?Zw@~WM3;A zL3A$dHek@IKcvWD*NQWL#Q9gelabpJO`|q9CDxA?Q)t5lQE^)5CeHtqTD@71QRXqO z7i9>T0iOBQ?VCe{6r{l_hCXqEr)fD&#wJ;E;tZT|n_(0SCn4bqsF@X1v22gtKZVi9 z$QBV$Sr5fj7;(+q5~#tV%+fFkSsU(2d!O=<##+Yd_W3-{eEHBE$88r}%~km`Z$#;g zk*MwHr*>ox>yZN5Ol?t!M3fFZ(18wlwi()b1`52rRS&yyW`PCa3d?xHEN`{^w1vW@ z5ymRn?1^_Ww9C3V?}cJ`Qp=jT%9`k`Pd}vROz)aVC+VvVeyTIdvalAu zfHgY>%5KR9#aXizGJX@q^a)ucNY$ufOR|n3Q~FVL*|Ga?KOB<~q9BWDGY z3lsxily9FhI4oeO;bp`0FqMCdoe7M7<`(oD2s`he23D`S#a=em#&)p(+l zZ!l=ze}|u2;`O5Q1@cM&ooq$Rcu|%8#nh?wYRYSM->~ft;?S)am9n&VlGKH`3dyLd z8T7Rn^8I5~T3VSIvjOM#B$n@G-WbW3ygGnc!0)`|n1`Q96aS1TyRf-`F1gJa8m+d& zwRcSf>Th@p)bTmDa_zI78q4#G8w$>W6zJhmKKIwCy##rmEb!*NaHvMCzbD$4!#~c*Ka#YLeEG2 ziJd;HyS?QBZ=4MUQiUYWc9@F0mjV6G?O)|C_((bY+c$y{#ojY%!nX1{A-&-S-}&T+ ze*LZuk2_B};ueM62T$ z#xwI9A!|GQVi45pF;T>pTmXPrCRfs?obQR|jgRlE@XiEj51yLD*+Rg6bCsq4gKq5U z$3g$-+22MyGc}7vsmtCOZ#y~j6f+-rPB;2NdLeVZ(r|Pd9pslg-<1NteoqTcyMoT| z3FxA$ePegHXTe&k0?6x6ZVu$kHtUhHbQ?Mi&)=U6PQ-SObT=c3$tC1?tLN`&WRoJH zTe-WL^NG4zlOg{}A#sAFXu3h3ZY->nE1fS6a|9fNMv2cCR20MV6zrqrs^_+sS;IteA;81QGV||(%Z>+-k3oUaYy?Ql@stAPMYt4 z#nS5{MbYBJW-(Gu`VPy|XFH z_2KYpq)w^q_~+-tl;vEt`O|HRkX^lDPU!J7EQ_UrULM!cn!hzxBE}oy)?JqAjN3PQ z{6v-RbkYot_Wp5^1mi{>5HSuGa3hli!NQu~XMaMiV5-N_??RRW>Ks$Hp%dN_7_mU| zEn>piD2Y_(zbBhAN22nLOjC_cM$>twF6k-3SykTU#t%ZQMSuFW|A15GZ=@GNWleG% z?RSS{f0CKc3#*r^?d3uGoKs*8xkTTj=3cW+ z@ocJCW7SzJ%$FHfHszBJxoVzo7T>&M(bsx{O^NgWM!^43;Qu=jPyT2Be;}-{^%U=a PUr+v%_Wzvvf9d}K|BxI{ literal 0 HcmV?d00001 diff --git a/java/junit-runner/src/ai/openidea/junit/Runner.java b/java/junit-runner/src/ai/openidea/junit/Runner.java new file mode 100644 index 0000000000..bf2352e1b3 --- /dev/null +++ b/java/junit-runner/src/ai/openidea/junit/Runner.java @@ -0,0 +1,198 @@ +package ai.openidea.junit; + +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.junit.platform.engine.DiscoverySelector; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.TestSource; +import org.junit.platform.engine.discovery.DiscoverySelectors; +import org.junit.platform.engine.reporting.ReportEntry; +import org.junit.platform.engine.support.descriptor.ClassSource; +import org.junit.platform.engine.support.descriptor.MethodSource; +import org.junit.platform.launcher.Launcher; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.TestPlan; +import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import org.junit.platform.launcher.core.LauncherFactory; + +/** + * Runs the JUnit Platform tests given as arguments ({@code com.acme.OrderTest} or + * {@code com.acme.OrderTest#method}) and reports each test as the TeamCity service messages + * OpenIDEA's Gradle test init script prints ({@code gradleTests.gradle}). Exits with 1 when a + * test failed. + */ +public final class Runner implements TestExecutionListener { + private final PrintStream out; + private final Map started = new HashMap<>(); + private TestPlan plan; + private int tests; + private int failed; + private int skipped; + + private Runner(PrintStream out) { + this.out = out; + } + + public static void main(String[] args) throws UnsupportedEncodingException { + // The original stdout: JUnit replaces System.out while it captures a test's output. + PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8"); + List selectors = new ArrayList<>(); + for (String arg : args) selectors.addAll(selectors(arg)); + Runner runner = new Runner(out); + Launcher launcher = LauncherFactory.create(); + launcher.execute( + LauncherDiscoveryRequestBuilder.request() + .selectors(selectors) + .configurationParameter("junit.platform.output.capture.stdout", "true") + .configurationParameter("junit.platform.output.capture.stderr", "true") + .build(), + runner); + StringBuilder summary = new StringBuilder().append(runner.tests).append(runner.tests == 1 ? " test" : " tests"); + summary.append(" completed"); + if (runner.failed > 0) summary.append(", ").append(runner.failed).append(" failed"); + if (runner.skipped > 0) summary.append(", ").append(runner.skipped).append(" skipped"); + out.println(summary); + out.flush(); + System.exit(runner.failed > 0 || runner.tests == 0 ? 1 : 0); + } + + /** Every method named {@code method} (parameterized ones too); the class when there is none. */ + static List selectors(String arg) { + int hash = arg.indexOf('#'); + List out = new ArrayList<>(); + if (hash < 0) { + out.add(DiscoverySelectors.selectClass(arg)); + return out; + } + String className = arg.substring(0, hash); + String name = arg.substring(hash + 1); + try { + Class type = Class.forName(className, false, Thread.currentThread().getContextClassLoader()); + for (Class c = type; c != null && c != Object.class; c = c.getSuperclass()) { + for (Method m : c.getDeclaredMethods()) { + if (m.getName().equals(name) && !m.isSynthetic()) out.add(DiscoverySelectors.selectMethod(type, m)); + } + if (!out.isEmpty()) break; + } + } catch (ClassNotFoundException | LinkageError e) { + // Discovery reports the missing class. + } + if (out.isEmpty()) out.add(DiscoverySelectors.selectClass(className)); + return out; + } + + @Override + public void testPlanExecutionStarted(TestPlan testPlan) { + plan = testPlan; + } + + @Override + public void executionStarted(TestIdentifier id) { + if (!id.isTest()) return; + started.put(id.getUniqueId(), System.currentTimeMillis()); + message("testStarted", id(id)); + } + + @Override + public void executionSkipped(TestIdentifier id, String reason) { + List skippedTests = new ArrayList<>(); + if (id.isTest()) skippedTests.add(id); + else for (TestIdentifier d : plan.getDescendants(id)) if (d.isTest()) skippedTests.add(d); + for (TestIdentifier test : skippedTests) { + tests++; + skipped++; + message("testStarted", id(test)); + message("testIgnored", id(test) + attr("message", reason)); + message("testFinished", id(test) + attr("duration", "0")); + } + } + + @Override + public void executionFinished(TestIdentifier id, TestExecutionResult result) { + TestExecutionResult.Status status = result.getStatus(); + if (!id.isTest()) { + // A class whose set-up failed (`@BeforeAll`): reported as a test, like JUnit 4's initializationError. + Optional className = className(id); + if (status != TestExecutionResult.Status.FAILED || !className.isPresent()) return; + String own = attr("name", "initializationError") + attr("className", className.get()); + message("testStarted", own); + failed(own, result); + message("testFinished", own + attr("duration", "0")); + tests++; + return; + } + tests++; + String own = id(id); + if (status == TestExecutionResult.Status.FAILED) failed(own, result); + else if (status == TestExecutionResult.Status.ABORTED) { + skipped++; + message("testIgnored", own); + } + Long start = started.remove(id.getUniqueId()); + long duration = start == null ? 0 : System.currentTimeMillis() - start; + message("testFinished", own + attr("duration", Long.toString(duration))); + } + + @Override + public void reportingEntryPublished(TestIdentifier id, ReportEntry entry) { + for (Map.Entry e : entry.getKeyValuePairs().entrySet()) { + String kind = e.getKey().equals("stdout") ? "testStdOut" : e.getKey().equals("stderr") ? "testStdErr" : null; + if (kind == null) continue; + // A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name. + String own = id.isTest() ? id(id) : className(id).map(c -> attr("className", c)).orElse(null); + if (own != null) message(kind, own + attr("out", e.getValue())); + } + } + + private void failed(String own, TestExecutionResult result) { + failed++; + Throwable error = result.getThrowable().orElse(null); + StringWriter trace = new StringWriter(); + if (error != null) error.printStackTrace(new PrintWriter(trace)); + message("testFailed", own + attr("message", error == null ? "" : error.toString()) + attr("details", trace.toString())); + } + + /** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */ + private String id(TestIdentifier id) { + for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) { + TestSource source = at.getSource().orElse(null); + if (source instanceof MethodSource) { + MethodSource m = (MethodSource) source; + return attr("name", m.getMethodName()) + attr("className", m.getClassName()); + } + if (source instanceof ClassSource) + return attr("name", id.getLegacyReportingName()) + attr("className", ((ClassSource) source).getClassName()); + } + return attr("name", id.getLegacyReportingName()) + attr("className", id.getDisplayName()); + } + + private Optional className(TestIdentifier id) { + TestSource source = id.getSource().orElse(null); + return source instanceof ClassSource ? Optional.of(((ClassSource) source).getClassName()) : Optional.empty(); + } + + private void message(String kind, String attrs) { + out.println("##teamcity[" + kind + attrs + "]"); + } + + private static String attr(String name, String value) { + return " " + name + "='" + escape(value) + "'"; + } + + static String escape(String s) { + if (s == null) return ""; + return s.replace("|", "||").replace("'", "|'").replace("\n", "|n").replace("\r", "|r") + .replace("[", "|[").replace("]", "|]"); + } +} diff --git a/java/junit-runner/tests/SampleTest.java b/java/junit-runner/tests/SampleTest.java new file mode 100644 index 0000000000..7a071316ce --- /dev/null +++ b/java/junit-runner/tests/SampleTest.java @@ -0,0 +1,43 @@ +package sample; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class SampleTest { + @Test + void passes() { + System.out.println("hello [ünï]"); + } + + @Test + void fails() { + assertEquals(1, 2, "it's wrong"); + } + + @Test + @Disabled + void disabled() {} + + @Test + void aborted() { + assumeTrue(false); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void parameterized(int n) { + assertEquals(1, n); + } + + @Nested + class Inner { + @Test + void nested() {} + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index e4fcacb02b..d2301e8a68 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -336,6 +336,7 @@ inspect_code trusted project_host bin java_build_workspace trusted project_host bindings async java_debug_adapter trusted project_host bindings sync java_debug_server trusted project_host bindings async +java_junit_runner trusted project_host bindings async java_resolve_launch trusted project_host bindings async jdk_download always project_host bindings async jdk_download_location always project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 7a67e7c9f6..578e0a9289 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -828,6 +828,13 @@ export const commands = { javaDebugAdapter: (module: string) => typedError(__TAURI_INVOKE("java_debug_adapter", { module })), /** Port of java-debug's DAP server inside the jdtls serving `module` (started on demand). */ javaDebugServer: (module: string) => typedError(__TAURI_INVOKE("java_debug_server", { module })), + /** + * The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath: + * the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the + * classpath has one; from the engine's repository, else downloaded once from Maven Central), and, + * for a Maven module, what its Surefire configuration gives the forked test JVM. + */ + javaJunitRunner: (module: string, classPaths: string[]) => typedError(__TAURI_INVOKE("java_junit_runner", { module, classPaths })), /** * Cancellable with `cancel_request(request)`. * Builds according to `policy`, then resolves the runtime (or test) @@ -8715,6 +8722,17 @@ export type JsResponseRule = { body: string, }; +/** The test JVM of OpenIDEA's JUnit runner. */ +export type JunitLaunch = { + classPaths: string[], + /** Surefire's `argLine`, then its system properties as `-Dkey=value`. */ + vmArgs: string[], + env: { [key in string]: string }, + workingDirectory: string | null, + /** The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console. */ + surefire: string[], +}; + /** The backend that reads a debugged JVM's objects (instances, fields, referrers). */ export type JvmBackendState = { kind: "ready" } | /** Turned off for the rest of the session: the debug adapter lacks what it needs. */ @@ -9553,6 +9571,16 @@ export type MavenProject = { env: { [key in string]: string }, }; +/** + * Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build + * and run actions are delegated to Maven. + */ +export type MavenRunTestsUsing = +/** OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`). */ +"ide" | +/** Surefire (`mvn test -Dtest=…`). */ +"maven"; + /** Build Tools › Maven. */ export type MavenSettings = { /** JDK home used to run Maven; empty = Project JDK, else the POM's Java version. */ @@ -9603,6 +9631,8 @@ export type MavenSettings = { * dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`). */ updateSnapshots?: boolean, + /** Who runs the JUnit 5 tests of the gutter's Run / Debug. */ + runTestsUsing?: MavenRunTestsUsing, }; /** What keeps an idle background project loaded. */ diff --git a/src/features/run/application.ts b/src/features/run/application.ts index 488d62daa7..3cf095678d 100644 --- a/src/features/run/application.ts +++ b/src/features/run/application.ts @@ -1,10 +1,12 @@ /** * IDEA-style "Application" run configurations for Java / Kotlin main classes * (Spring Boot applications get their own kind), the module a source file - * belongs to, and test configurations scoped to one class or method. + * belongs to, and test configurations scoped to one class or method: through Maven / Gradle, + * or for JUnit 5 in a Maven module, OpenIDEA's own runner (Settings › Maven › Run tests using). */ import type { RunConfig } from "@/platform/ipc"; -import { CLASSPATH, TEST_CLASSPATH, jvmModuleDir } from "@/platform/javaLaunch"; +import { CLASSPATH, JUNIT_RUNNER_MAIN, TEST_CLASSPATH, jvmModuleDir, parseJavaArgs } from "@/platform/javaLaunch"; +import { useProject } from "@/platform/project"; import { isTestPath, rootFor } from "@/platform/languageSettings"; import { currentRoots } from "@/platform/projectRoots"; import { simpleClassName } from "./jvmTargets"; @@ -81,3 +83,41 @@ export function jvmTestConfig(fileConfig: RunConfig, className: string, method: } return null; } + +/** A test file of JUnit Jupiter (JUnit 5): OpenIDEA's runner handles JUnit Platform engines only. */ +const JUPITER_IMPORT = /^\s*import\s+(?:static\s+)?org\.junit\.jupiter\./m; + +/** Settings › Build Tools › Maven › Run tests using: OpenIDEA (the default), not Surefire. */ +export function runsJunitInIde(fileConfig: RunConfig, content: string | undefined): boolean { + if (fileConfig.kind !== "maven" || !content || !JUPITER_IMPORT.test(content)) return false; + return useProject.getState().settings?.languages?.java?.maven?.runTestsUsing !== "maven"; +} + +/** + * A test class (`method` unset) or method run by OpenIDEA's JUnit Platform runner on the module's + * test classpath, like IDEA's JUnit configurations: `java -ea -cp ${testClasspath} Class#method`. + * Its working directory is the module's, as Surefire's. + */ +export function junitRunnerConfig( + className: string, + method: string | undefined, + relPath: string, + configs: readonly RunConfig[], +): RunConfig { + const app = applicationConfig({ className }, relPath, configs); + const selector = `${className}${method ? `#${method}` : ""}`; + const simple = simpleClassName(className); + return { + ...app, + id: `junit:${app.module ? `${app.module}:` : ""}${selector}`, + name: method ? `${simple}.${method}` : simple, + args: ["-ea", "-cp", TEST_CLASSPATH, JUNIT_RUNNER_MAIN, selector], + cwd: app.module || null, + isTest: true, + }; +} + +/** A configuration run by OpenIDEA's JUnit runner (its arguments after the main class select the tests). */ +export function isJunitRunner(config: Pick): boolean { + return config.kind === "application" && parseJavaArgs(config.args).mainClass === JUNIT_RUNNER_MAIN; +} diff --git a/src/features/run/gradleRun.ts b/src/features/run/gradleRun.ts index 7192d5d645..d34fcc16a3 100644 --- a/src/features/run/gradleRun.ts +++ b/src/features/run/gradleRun.ts @@ -180,7 +180,7 @@ export async function gradleBootLaunch(config: T): Promise< * modules; null to launch it on the language server's classpath. */ export async function gradleDelegation(config: RunConfig): Promise { - if (!isTauri() || !isJvmApplication(config)) return null; + if (!isTauri() || !isJvmApplication(config) || config.isTest) return null; const { project, settings } = useProject.getState(); if (!project?.root || settings?.languages?.java?.gradle?.runUsing === "ide") return null; const { model, gradleOffline } = useBuildModel.getState(); diff --git a/src/features/run/java.test.ts b/src/features/run/java.test.ts index 35eb29ec43..526046d300 100644 --- a/src/features/run/java.test.ts +++ b/src/features/run/java.test.ts @@ -12,6 +12,8 @@ import { import { usePlatform } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; import { applicationConfig, jvmModuleDir, jvmTestConfig } from "./application"; +import { frameworkFor } from "./testing"; +import { rerunFailedConfig } from "./testing/rerun"; import { buildRows } from "./ConfigChooser"; import { jdwpLaunch } from "./javaDebug"; import { DELEGATED_DEBUG } from "./gradleRun"; @@ -288,6 +290,65 @@ describe("application configurations", () => { }); }); +describe("JUnit 5 through OpenIDEA's runner (Maven › Run tests using)", () => { + const rel = "shop/src/test/java/a/OrderTest.java"; + const jupiter = `package a; +import org.junit.jupiter.api.Test; +class OrderTest { + @Test + void adds() {} +}`; + const junit4 = jupiter.replace("org.junit.jupiter.api.Test", "org.junit.Test"); + const maven = [cfg({ id: "maven:test", kind: "maven", args: ["test"], cwd: "shop", isTest: true })]; + const gradle = [cfg({ id: "gradle:test", kind: "gradle", args: ["test"], cwd: "shop", isTest: true })]; + const target = (src: string, name: string) => + detectRunTargets(src, rel).find((t) => t.path.at(-1) === name || t.name === name)!; + const useTests = (runTestsUsing: "ide" | "maven" | undefined) => + useProject.setState({ + settings: runTestsUsing ? { languages: { java: { maven: { runTestsUsing } } } } : undefined, + } as never); + beforeEach(() => useTests(undefined)); + + it("runs a method or class of a Maven module with the runner on the test classpath, without Maven", () => { + expect(targetConfig(target(jupiter, "adds"), rel, maven, jupiter)).toMatchObject({ + id: "junit:shop:a.OrderTest#adds", + name: "OrderTest.adds", + kind: "application", + command: "java", + args: ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.OrderTest#adds"], + module: "shop", + cwd: "shop", + isTest: true, + debugAdapter: "java-debug", + }); + expect(targetConfig(target(jupiter, "OrderTest"), rel, maven, jupiter)!.args.at(-1)).toBe("a.OrderTest"); + }); + + it("keeps Surefire for the Maven setting, JUnit 4 and Gradle", () => { + useTests("maven"); + expect(targetConfig(target(jupiter, "adds"), rel, maven, jupiter)!.kind).toBe("maven"); + useTests("ide"); + expect(targetConfig(target(junit4, "adds"), rel, maven, junit4)!.kind).toBe("maven"); + expect(targetConfig(target(jupiter, "adds"), rel, gradle, jupiter)!.kind).toBe("gradle"); + }); + + it("reports through the JVM parser, debugs with a waiting agent and reruns failed tests by selector", () => { + const config = targetConfig(target(jupiter, "OrderTest"), rel, maven, jupiter)!; + expect(frameworkFor(config)).toBe("jvm"); + expect(jdwpLaunch(config)!.args).toEqual([JDWP_AGENT, ...config.args]); + const failed = rerunFailedConfig(config, [["a.OrderTest", "adds"], ["a.OrderTest$Nested", "b"], ["a.Other"]]); + expect((failed as RunConfig).args).toEqual([ + "-ea", + "-cp", + "${testClasspath}", + "ai.openidea.junit.Runner", + "a.OrderTest#adds", + "a.OrderTest$Nested#b", + "a.Other", + ]); + }); +}); + describe("java compile errors", () => { const base: Omit = { build: "withErrors", diff --git a/src/features/run/javaDebug.ts b/src/features/run/javaDebug.ts index 8c0d1aab8b..de0894bbff 100644 --- a/src/features/run/javaDebug.ts +++ b/src/features/run/javaDebug.ts @@ -20,6 +20,7 @@ import { } from "@/platform/javaLaunch"; import { applyBuildPolicyToCommand } from "./buildCommand"; import { startRun, useRun } from "./store"; +import { isJunitRunner } from "./application"; import { DELEGATED_ATTACH_LISTENER, DELEGATED_DEBUG, DELEGATED_MAIN } from "./gradleRun"; import { isWindows } from "./jvmTypes"; @@ -112,6 +113,8 @@ export function jdwpLaunch(config: RunConfig, jdwpPort?: number): RunConfig | nu if (!args.some(isGradleJvmTask)) return null; return args.includes("--debug-jvm") ? config : { ...config, args: [...args, "--debug-jvm"] }; } + // OpenIDEA's JUnit runner keeps its test tree in the Run tab: the agent waits there, the debugger attaches. + if (isJunitRunner(config)) return { ...config, args: [JDWP_AGENT, ...args] }; // Application / Spring Boot configurations are launched by java-debug itself. if (JVM_ADAPTERS.includes(config.debugAdapter ?? "") && !isJvmApplication(config)) return { diff --git a/src/features/run/javaModule.test.ts b/src/features/run/javaModule.test.ts index 90acadff48..24959da378 100644 --- a/src/features/run/javaModule.test.ts +++ b/src/features/run/javaModule.test.ts @@ -29,6 +29,7 @@ const ipc = vi.hoisted(() => { projectRoot: "/p", classPaths: ["/p/app/target/classes"], modulePaths: [], + pathListSeparator: ":", javaHome: null, javaExec: "java", shortenCommandLine: null, @@ -37,6 +38,15 @@ const ipc = vi.hoisted(() => { hints: [], }), ), + javaJunitRunner: vi.fn(() => + ok({ + classPaths: ["/p/app/target/test-classes", "/runner.jar"], + vmArgs: ["-Xmx1g", "-Dopenidea.fail=true"], + env: { TZ: "UTC" }, + workingDirectory: "/p/app/work", + surefire: ["argLine", "systemPropertyVariables"], + }), + ), }; }); vi.mock("@/platform/ipc", async (original) => { @@ -310,3 +320,30 @@ it("does not resolve or launch when saving fails", async () => { expect(ipc.javaResolveLaunch).not.toHaveBeenCalled(); expect(ipc.runStart).not.toHaveBeenCalled(); }); + +it("gives the JUnit runner's JVM the module's Surefire configuration", async () => { + const report = vi.fn(); + const junit: RunConfig = { + ...config, + module: "app", + isTest: true, + args: ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.MainTest#adds"], + env: { TZ: "Europe/Paris" }, + }; + const { resolved } = await prepareJavaLaunch(junit, { request: 1, signal: new AbortController().signal, report }); + expect(ipc.javaJunitRunner).toHaveBeenCalledWith("app", ["/p/app/target/classes"]); + expect(resolved).toMatchObject({ + args: [ + "-Xmx1g", + "-Dopenidea.fail=true", + "-ea", + "-cp", + "/p/app/target/test-classes:/runner.jar", + "ai.openidea.junit.Runner", + "a.MainTest#adds", + ], + env: { TZ: "Europe/Paris" }, + cwd: "/p/app/work", + }); + expect(report).toHaveBeenCalledWith("Applying the Surefire configuration: argLine, systemPropertyVariables\n"); +}); diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 0b0c3577e4..6e1b61b19b 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -10,7 +10,7 @@ import { goTargets } from "./goTargets"; import { csharpTargets } from "./csharpTargets"; import { formatArgs } from "./configs"; import type { RunConfig } from "@/platform/ipc"; -import { applicationConfig, jvmTestConfig } from "./application"; +import { applicationConfig, junitRunnerConfig, jvmTestConfig, runsJunitInIde } from "./application"; import { goTestParts, withoutGoSelection } from "./goArguments"; import { contextConfig, relToCwd, testConfigFor } from "./context"; import { djangoLabel, djangoTestsOf } from "./djangoTypes"; @@ -466,12 +466,12 @@ export function targetConfig( } const file = testConfigFor(relPath, configs, base, content); if (!file) return null; - if (target.className && (file.kind === "maven" || file.kind === "gradle")) - return jvmTestConfig( - file, - target.className, - target.kind === "test" ? target.path[target.path.length - 1] : undefined, - ); + if (target.className && (file.kind === "maven" || file.kind === "gradle")) { + const method = target.kind === "test" ? target.path[target.path.length - 1] : undefined; + return runsJunitInIde(file, content) + ? junitRunnerConfig(target.className, method, relPath, configs) + : jvmTestConfig(file, target.className, method); + } const shortName = target.kind === "suite" ? target.path[target.path.length - 1]! : target.name; const named = (args: string[]): RunConfig => ({ ...file, diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 3b5b7cd330..52f5064ac9 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -1,5 +1,6 @@ /** Picks the test output parser for a run configuration. */ import type { RunConfig } from "@/platform/ipc"; +import { isJunitRunner } from "../application"; import { cargoParser } from "./cargo"; import { goParser } from "./go"; import { jsParser } from "./js"; @@ -66,6 +67,7 @@ export function frameworkFor(config: FrameworkConfig): Framework { if (config.testRunner === "node-test" || /(^|[\s/\\])(node|tsx)(\.exe)?(\s+-\S*)*\s+--test(\s|$)/.test(cmd)) return "node-test"; if (config.testRunner === "mocha" || /(^|[\s/\\])_?mocha(\.cmd|\.js)?(\s|$)/.test(cmd)) return "mocha"; + if (isJunitRunner(config)) return "jvm"; switch (config.kind) { case "dotnet-test": return "dotnet"; diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index 6bc0e4bbe2..4768d9b636 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -6,6 +6,8 @@ import { selectPluginTests } from "@/workbench/contributions"; import { phpunitArgs, phpunitFilter } from "./phpunit"; import type { RunConfig } from "@/platform/ipc"; import { formatArgs, parseArgs } from "../configs"; +import { isJunitRunner } from "../application"; +import { JUNIT_RUNNER_MAIN } from "@/platform/javaLaunch"; import { appendScriptArgs } from "../scriptArgs"; import { djangoTestsOf } from "../djangoTypes"; import { goTestParts, withoutGoSelection } from "../goArguments"; @@ -151,6 +153,10 @@ function jvmArgs(config: RunConfig, paths: string[][]): string[] | null { .map((p) => ({ cls: p[0]!, method: p[p.length - 1]!.replace(/\(\)$/, "") })); const classes = unique(paths.filter((p) => p.length === 1).map((p) => p[0]!)); if (!tests.length && !classes.length) return null; + if (isJunitRunner(config)) { + const runner = config.args.slice(0, config.args.indexOf(JUNIT_RUNNER_MAIN) + 1); + return [...runner, ...unique(tests.map((t) => `${t.cls}#${t.method}`)), ...classes]; + } if (config.kind === "maven" || /\bmvnw?\b/.test(config.command)) { const byClass = new Map(); for (const t of tests) byClass.set(t.cls, [...(byClass.get(t.cls) ?? []), t.method]); diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index 790ed555a2..2a771ebf3f 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -66,6 +66,7 @@ describe("languages settings", () => { delegateBuild: false, downloadSources: false, updateSnapshots: false, + runTestsUsing: "ide", }); expect(validateSettings({}).languages).toEqual(DEFAULT_LANGUAGES); expect(validateLanguages({ java: { maven: { threads: 4 } } }).java.maven.threads).toBe(""); @@ -79,6 +80,8 @@ describe("languages settings", () => { expect(validateLanguages({ java: { maven: { delegateBuild: "yes" } } }).java.maven.delegateBuild).toBe(false); expect(validateLanguages({ java: { maven: { downloadSources: true } } }).java.maven.downloadSources).toBe(true); expect(validateLanguages({ java: { maven: { updateSnapshots: true } } }).java.maven.updateSnapshots).toBe(true); + expect(validateLanguages({ java: { maven: { runTestsUsing: "maven" } } }).java.maven.runTestsUsing).toBe("maven"); + expect(validateLanguages({ java: { maven: { runTestsUsing: "gradle" } } }).java.maven.runTestsUsing).toBe("ide"); const settings = validateSettings({ languages: { java: { maven: { runnerJre: " ./jdks/21 " } } } }); expect(validateSettings(settings).languages.java.maven.runnerJre).toBe("./jdks/21"); }); diff --git a/src/features/settings/languages/LanguagePages.tsx b/src/features/settings/languages/LanguagePages.tsx index 3b1dd890aa..c9abbb048c 100644 --- a/src/features/settings/languages/LanguagePages.tsx +++ b/src/features/settings/languages/LanguagePages.tsx @@ -579,6 +579,7 @@ export function GradlePage() { export function MavenPage() { const [delegateBuild, setDelegateBuild] = useSetting("languages.java.maven.delegateBuild"); + const [runTestsUsing, setRunTestsUsing] = useSetting("languages.java.maven.runTestsUsing"); const [daemon, setDaemon] = useSetting("languages.java.maven.daemon"); const [downloadSources, setDownloadSources] = useSetting("languages.java.maven.downloadSources"); const [updateSnapshots, setUpdateSnapshots] = useSetting("languages.java.maven.updateSnapshots"); @@ -674,6 +675,20 @@ export function MavenPage() { onChange={setDelegateBuild} hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server." /> + + ", + "css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }" + }, + { + "name": "Chip", + "kind": "chip", + "refersTo": "chip", + "description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.", + "html": "", + "css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }" + }, + { + "name": "Tree Rows", + "kind": "custom", + "refersTo": "list-row-selected", + "description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.", + "html": "
src
main.tsx
workbench
", + "css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }" + }, + { + "name": "Island on Frame", + "kind": "card", + "description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.", + "html": "
Project
fn main() {}
", + "css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }" + }, + { + "name": "Tooltip", + "kind": "custom", + "refersTo": "tooltip", + "description": "Floating hover help: one of the few surfaces allowed a shadow.", + "html": "
Run 'main' ⌃R
", + "css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }" + } + ], + "narrative": { + "northStar": "The Quiet Workbench", + "overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.", + "keyCharacteristics": [ + "JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.", + "Grey frame, rounded content islands, tonal layering only.", + "A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.", + "High density on a 4px grid. Compact mode is a first-class variant.", + "Controls are quiet at rest: toolbar buttons and chips have no frame until hover.", + "Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.", + "Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins." + ], + "rules": [ + { + "name": "The IDEA Reference Rule", + "body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.", + "section": "overview" + }, + { + "name": "The One Accent Rule", + "body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.", + "section": "colors" + }, + { + "name": "The Token Only Rule", + "body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.", + "section": "colors" + }, + { + "name": "The Flat Scale Rule", + "body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.", + "section": "typography" + }, + { + "name": "The User Owns Size Rule", + "body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.", + "section": "typography" + }, + { + "name": "The Flat at Rest Rule", + "body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.", + "section": "elevation" + } + ], + "dos": [ + "**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).", + "**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.", + "**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.", + "**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.", + "**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.", + "**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.", + "**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.", + "**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`." + ], + "donts": [ + "**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.", + "**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.", + "**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.", + "**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.", + "**Don't** put shadows on docked panels, islands, rows or controls.", + "**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.", + "**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.", + "**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature." + ] + } +} diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000000..b27ef66307 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,323 @@ +--- +name: OpenIDEA +description: The IDE you know, rebuilt in Rust. +colors: + workbench-blue: "#3871e1" + link-blue: "#2f5eb9" + frame-grey: "#e9eaee" + island-white: "#ffffff" + raised-paper: "#f7f8f9" + ink: "#000000" + ink-secondary: "#5f6269" + ink-muted: "#6c707e" + ink-faint: "#9fa2a8" + hairline: "#e9eaee" + control-edge: "#d1d3d9" + selection-wash: "#d0dffe" + tab-wash: "#e3ebfe" + danger: "#c54e58" + warning: "#a56906" + success: "#338555" + frame-grey-dark: "#26282c" + island-dark: "#191a1c" + ink-dark: "#d1d3d9" + ink-strong-dark: "#dfe1e5" + ink-muted-dark: "#8c8f95" + control-edge-dark: "#40434a" + selection-wash-dark: "#2a4371" +typography: + title: + fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif" + fontSize: "13px" + fontWeight: 600 + lineHeight: 1.4 + body: + fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif" + fontSize: "13px" + fontWeight: 400 + lineHeight: 1.4 + label: + fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif" + fontSize: "12px" + fontWeight: 400 + lineHeight: 1.4 + label-tiny: + fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif" + fontSize: "11px" + fontWeight: 400 + lineHeight: 1.4 + input-large: + fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif" + fontSize: "15px" + fontWeight: 400 + code: + fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace" + fontSize: "13px" + fontWeight: 400 + lineHeight: "22px" + fontFeature: "\"liga\" 0" +rounded: + small: "4px" + control: "4px" + row: "4px" + selection: "5px" + tab: "6px" + toolbar-button: "6px" + tooltip: "6px" + popup: "8px" + island: "10px" + popup-large: "10px" + dialog: "10px" +spacing: + space-0-5: "2px" + space-1: "4px" + space-1-5: "6px" + space-2: "8px" + space-3: "12px" + space-4: "16px" +components: + button-primary: + backgroundColor: "{colors.workbench-blue}" + textColor: "{colors.island-white}" + typography: "{typography.body}" + rounded: "{rounded.control}" + padding: "0 16px" + height: "28px" + button-secondary: + backgroundColor: "{colors.island-white}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.control}" + padding: "0 16px" + height: "28px" + button-ghost: + textColor: "{colors.ink-secondary}" + typography: "{typography.body}" + rounded: "{rounded.control}" + padding: "0 8px" + height: "28px" + icon-button: + textColor: "{colors.ink-muted}" + rounded: "{rounded.toolbar-button}" + size: "24px" + icon-button-selected: + backgroundColor: "{colors.selection-wash}" + textColor: "{colors.ink}" + rounded: "{rounded.toolbar-button}" + size: "24px" + input: + backgroundColor: "{colors.island-white}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.control}" + padding: "0 8px" + height: "28px" + chip: + textColor: "{colors.ink-secondary}" + typography: "{typography.label}" + rounded: "{rounded.toolbar-button}" + padding: "0 6px" + height: "22px" + tooltip: + backgroundColor: "{colors.island-white}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.tooltip}" + padding: "6px 10px" + list-row-selected: + backgroundColor: "{colors.selection-wash}" + textColor: "{colors.ink}" + rounded: "{rounded.row}" + height: "24px" +--- + +# Design System: OpenIDEA + +## Overview + +**Creative North Star: "The Quiet Workbench"** + +The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm. + +The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice. + +Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them. + +The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken. + +Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation. + +### Named Rules + +**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment. + +**Key Characteristics:** + +- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys. +- Grey frame, rounded content islands, tonal layering only. +- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window. +- High density on a 4px grid. Compact mode is a first-class variant. +- Controls are quiet at rest: toolbar buttons and chips have no frame until hover. +- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration. +- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins. + +## Colors + +A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes. + +### Project colour + +- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome. + +### Primary + +- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex. +- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands. + +### Neutral + +- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars). +- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives. +- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island. +- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text. +- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons. +- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`. + +### Functional vocabularies + +- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners. +- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks. +- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme. + +### Named Rules + +**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship. + +**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards. + +## Typography + +**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks) +**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks) +**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus + +**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size. + +### Hierarchy + +- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis. +- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons. +- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints. +- **Label Tiny** (400, 11px): stripe labels, counters and badges. +- **Input Large** (400, 15px): Search Everywhere and similar large query fields. +- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size. + +### Named Rules + +**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size. + +**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size. + +## Layout + +The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island. + +Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px. + +**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes. + +The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island. + +## Elevation & Depth + +Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit. + +### Shadow Vocabulary + +- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar. +- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow. +- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications. + +### Named Rules + +**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step. + +## Shapes + +Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px. + +## Components + +Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom. + +### Buttons + +- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding. +- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog. +- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%. +- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash. +- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame. +- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border. + +### Icon Buttons (toolbar actions) + +- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest. +- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`. +- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button. +- Tone variants (`danger`, `accent`) recolour only the icon. + +### Chips + +- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon. +- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover. + +### Inputs / Fields + +- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink. +- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow. +- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame. +- Search fields have a muted leading icon. Monospace fields use the code font. + +### Lists and Trees + +- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar. +- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`. + +### Popups, Menus and Dialogs + +- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow. +- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes. + +### Tabs + +- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding. +- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair. +- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow. + +### Tool Window Stripes (signature) + +The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window. + +## Do's and Don'ts + +### Do: + +- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`). +- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one. +- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow. +- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target. +- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible. +- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics. +- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion. +- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`. + +### Don't: + +- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration. +- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory. +- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning. +- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration. +- **Don't** put shadows on docked panels, islands, rows or controls. +- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change. +- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles. +- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature. diff --git a/PRODUCT.md b/PRODUCT.md new file mode 100644 index 0000000000..a5b2b2d763 --- /dev/null +++ b/PRODUCT.md @@ -0,0 +1,73 @@ +# Product + + + +## Platform + +web + +The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope. + +## Users + +- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients. +- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server. +- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in. + +## Product Purpose + +OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory. + +## Positioning + +"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app. + +## Operating Context + +- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol). +- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend. +- Agent tasks running alongside the developer's own work, with diff review and permission prompts. +- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes. + +## Capabilities and Constraints + +Hard constraints future work must preserve: + +1. The default keymap and interaction habits stay the same as IDEA's. +2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`). +3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this. +4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`. +5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse. +6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry. +7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down. + +Other facts: + +- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview. +- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout. + +## Brand Commitments + +- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`). +- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o. +- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives. + +## Evidence on Hand + +- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD. +- Demo video linked from `README.md`. +- No testimonials, customer logos or user counts exist. Do not fabricate them. + +## Product Principles + +1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory. +2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness. +3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound. +4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions. +5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on. + +## Accessibility & Inclusion + +- Use real `