From f9455549a746c919fb375604fe844e55f85f0a0e Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 00:45:28 +0800 Subject: [PATCH 01/15] fix(vcs): keep branch rows readable in narrow popups (#4551) Git Branches uses the interface font for branch names, tracked branches and refs, tapers indentation at deeper levels and limits the width of secondary refs, so deeply nested branches keep room for the name, commit counts and submenu arrow. The full branch and tracked ref show on hover. --- e2e/branchesPopupResize.spec.ts | 42 ++++++++++++++++++++++-- src/features/vcs/BranchWidget.module.css | 29 +++++++--------- src/features/vcs/BranchWidget.tsx | 21 ++++++++---- 3 files changed, 67 insertions(+), 25 deletions(-) diff --git a/e2e/branchesPopupResize.spec.ts b/e2e/branchesPopupResize.spec.ts index 11b80ec03..7c1a6c5f7 100644 --- a/e2e/branchesPopupResize.spec.ts +++ b/e2e/branchesPopupResize.spec.ts @@ -6,6 +6,9 @@ import type { Page } from "@playwright/test"; import { expect, stubDesktop, test } from "./fixtures"; const ROOT = "/dev/acme-api"; +const NESTED_REF = "teams/payments/reporting/month-end/exports/regions/europe/accounting/invoice-export"; +const TRACKING_REF = "origin/releases/payments/month-end/reconciliation/invoice-export"; +const BRANCH_FIXTURE = { root: ROOT, ref: NESTED_REF, upstream: TRACKING_REF }; async function openBranches(page: Page) { await page.evaluate(async () => { @@ -22,7 +25,7 @@ async function openBranches(page: Page) { test.beforeEach(async ({ workbench: page }) => { await stubDesktop(page); - await page.evaluate(async (root) => { + await page.evaluate(async ({ root, ref, upstream }) => { const h = window.__ipc.handlers; const branch = (name: string, current = false) => ({ name, @@ -47,6 +50,7 @@ test.beforeEach(async ({ workbench: page }) => { h.vcs_tags = () => []; h.vcs_branches = () => [ branch("main", true), + { ...branch(ref), upstream, ahead: 2, behind: 3 }, ...Array.from({ length: 40 }, (_, i) => branch(`task-${i}-a-long-branch-name-that-gets-cut-off`)), ]; const vcsModule = "/src/features/vcs/store.ts"; @@ -54,7 +58,41 @@ test.beforeEach(async ({ workbench: page }) => { useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); await refreshNow(); await loadBranches(); - }, ROOT); + }, BRANCH_FIXTURE); +}); + +test("narrow Git Branches keeps a deeply nested branch and its controls readable", async ({ workbench: page }) => { + await page.evaluate(() => { + localStorage.setItem("openidea.vcs.branchesPopup.size", JSON.stringify({ w: 280, h: 420 })); + }); + const popup = await openBranches(page); + const search = popup.getByRole("textbox", { name: "Search branches and actions" }); + await search.fill("invoice-export"); + const row = popup.getByRole("option", { name: /invoice-export/ }); + await expect(row).toBeVisible(); + const name = row.locator("[class*=branchName]"); + const tracking = row.getByText(TRACKING_REF, { exact: true }); + const chevron = row.locator("svg").last(); + const folder = popup.getByRole("option", { name: "accounting", exact: true }); + const rowBox = (await row.boundingBox())!; + const nameBox = (await name.boundingBox())!; + const trackingBox = (await tracking.boundingBox())!; + const chevronBox = (await chevron.boundingBox())!; + const indent = (option: typeof row) => + option.locator("[data-row-key]").evaluate((el) => parseFloat(getComputedStyle(el).paddingInlineStart)); + expect(await indent(row)).toBeGreaterThan(await indent(folder)); + expect(chevronBox.x + chevronBox.width).toBeLessThanOrEqual(rowBox.x + rowBox.width); + expect(nameBox.width).toBeGreaterThan(42); + expect(trackingBox.width).toBeGreaterThan(12); + expect(trackingBox.width).toBeLessThan(rowBox.width * 0.4); + await expect(name).toHaveCSS("font-size", "13px"); + await expect(tracking).toHaveCSS("font-size", "13px"); + await expect(row.getByRole("img", { name: "3 incoming commits" })).toBeVisible(); + await expect(row.getByRole("img", { name: "2 outgoing commits" })).toBeVisible(); + await expect(row.locator("[data-row-key]")).toHaveAttribute("title", NESTED_REF); + await expect(tracking).toHaveAttribute("title", TRACKING_REF); + await chevron.click(); + await expect(page.getByRole("menu", { name: `Branch ${NESTED_REF}` })).toBeVisible(); }); test("Git Branches resizes by its corner and right edge and reopens at that size", async ({ workbench: page }) => { diff --git a/src/features/vcs/BranchWidget.module.css b/src/features/vcs/BranchWidget.module.css index 5bde6b0ac..6e244a211 100644 --- a/src/features/vcs/BranchWidget.module.css +++ b/src/features/vcs/BranchWidget.module.css @@ -96,8 +96,13 @@ text-overflow: ellipsis; } .branchName { - font-family: var(--font-mono); - font-size: var(--fs-small); + min-width: 0; +} +.branchName, +.upstream, +.repoHead { + font-family: var(--font-ui); + font-size: var(--fs-ui); } .current { color: var(--fg-strong); @@ -111,15 +116,15 @@ font-size: var(--fs-tiny); line-height: 15px; } -.upstream { +.upstream, +.repoHead { flex: 0 4 auto; margin-left: auto; - min-width: 0; + min-width: min(3ch, 35%); + max-width: 35%; overflow: hidden; text-overflow: ellipsis; - color: var(--fg-faint); - font-family: var(--font-mono); - font-size: var(--fs-tiny); + color: var(--fg-muted); } .keys { margin-left: auto; @@ -175,16 +180,6 @@ margin: 0 2px; border-radius: 2px; } -.repoHead { - flex: 0 4 auto; - margin-left: auto; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - color: var(--fg-muted); - font-family: var(--font-mono); - font-size: var(--fs-small); -} .subChevron { flex: none; color: var(--fg-faint); diff --git a/src/features/vcs/BranchWidget.tsx b/src/features/vcs/BranchWidget.tsx index 4afa1af02..f308ebc43 100644 --- a/src/features/vcs/BranchWidget.tsx +++ b/src/features/vcs/BranchWidget.tsx @@ -862,6 +862,11 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi ); } +function branchIndent(depth: number) { + // Leave room for the row controls while keeping each deeper level indented. + return depth ? { paddingInlineStart: `min(${depth * INDENT}px, ${(30 * depth) / (depth + 3)}%)` } : undefined; +} + function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) { switch (row.type) { case "action": @@ -886,7 +891,7 @@ function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) { return ; case "common": return ( - + @@ -928,7 +933,7 @@ function GroupRowView({ row }: { row: { key: string; label: string; expanded: bo } function BranchRowView({ row }: { row: BranchRow | Extract }) { - const indent = "depth" in row && row.depth ? { paddingLeft: row.depth * INDENT } : undefined; + const indent = "depth" in row ? branchIndent(row.depth) : undefined; if (row.type === "action") { const keys = shortcutLabel(row.action.id); return ( @@ -949,7 +954,7 @@ function BranchRowView({ row }: { row: BranchRow | Extract + + {b.current ? ( ) : ( @@ -997,7 +1002,11 @@ function BranchRowView({ row }: { row: BranchRow | Extract )} - {!b.remote && b.upstream && {b.upstream}} + {!b.remote && b.upstream && ( + + {b.upstream} + + )} ); From d5f29ea2567d94cfc1eb463d757668ed36463e02 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 01:06:13 +0800 Subject: [PATCH 02/15] fix(build-tools): keep toolbar actions reachable in narrow panes (#4558) The Maven and Gradle toolbars used one fixed row, which clipped actions in narrow panes. Narrow panes keep reload or cancel, run and execute visible and group the rest in More Actions; widening the pane restores the full toolbar, keeping the offline and skip-tests toggle states. --- e2e/buildToolToolbar.spec.ts | 99 ++++++++++++++ src/features/build-tools/BuildToolView.tsx | 122 +++++++++++++----- .../build-tools/BuildTools.module.css | 3 + 3 files changed, 193 insertions(+), 31 deletions(-) create mode 100644 e2e/buildToolToolbar.spec.ts diff --git a/e2e/buildToolToolbar.spec.ts b/e2e/buildToolToolbar.spec.ts new file mode 100644 index 000000000..ffcc5be54 --- /dev/null +++ b/e2e/buildToolToolbar.spec.ts @@ -0,0 +1,99 @@ +import type { Page } from "@playwright/test"; +import type { BuildModel, BuildTool } from "../src/platform/ipc"; +import { expect, stubDesktop, test } from "./fixtures"; + +const model: BuildModel = { + maven: { + projects: [ + { + pom: "pom.xml", + dir: "", + groupId: "com.example", + artifactId: "orders", + version: "1.0.0", + packaging: "jar", + displayName: "Orders service", + parent: null, + modules: [], + aggregated: false, + plugins: [], + dependencies: [], + profiles: [], + javaVersion: 21, + command: "mvn", + options: [], + env: {}, + }, + ], + profiles: [], + syncedAt: 1, + stale: false, + syncError: null, + }, + gradle: [ + { + dir: "", + command: "gradle", + env: {}, + javaVersion: 21, + syncedAt: 1, + stale: false, + syncError: null, + projects: [{ path: ":", name: "orders", dir: "", buildFile: "build.gradle", tasks: [] }], + }, + ], +}; + +async function showTool(page: Page, tool: BuildTool) { + await stubDesktop(page); + await page.evaluate( + async ({ tool, model }) => { + window.__ipc.handlers.build_model = () => model; + window.__ipc.handlers.run_configs = () => []; + const buildStore = "/src/features/build-tools/store.ts"; + await (await import(/* @vite-ignore */ buildStore)).loadModel(); + const layout = "/src/workbench/toolwindows/store.ts"; + const { setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layout); + showToolWindow(tool, true); + setToolWindowSize("right", 190); + }, + { tool, model }, + ); +} + +async function setWidth(page: Page, width: number) { + await page.evaluate(async (px) => { + const layout = "/src/workbench/toolwindows/store.ts"; + (await import(/* @vite-ignore */ layout)).setToolWindowSize("right", px); + }, width); +} + +for (const tool of ["maven", "gradle"] as const) { + const name = tool === "maven" ? "Maven" : "Gradle"; + test(`${name} keeps its toolbar actions reachable as the pane resizes`, async ({ workbench: page }) => { + await showTool(page, tool); + const toolbar = page.getByRole("toolbar", { name: `${name} actions` }); + const more = toolbar.getByRole("button", { name: "More Actions", exact: true }); + const menu = page.getByRole("menu", { name: "More Actions", exact: true }); + const skipTests = "Toggle 'Skip Tests' Mode"; + await expect(toolbar.getByRole("button", { name: `Reload All ${name} Projects` })).toBeVisible(); + await expect(toolbar.getByRole("button", { name: new RegExp(`Execute ${name}`) })).toBeVisible(); + await expect(page.getByRole("tree", { name: `${name} projects` })).toBeVisible(); + expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await more.click(); + await expect(menu.getByRole("menuitem", { name: "Analyze Dependencies…" })).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: "Expand All" })).toBeVisible(); + await menu.getByRole("menuitemcheckbox", { name: skipTests, checked: false }).click(); + await expect(menu).toBeHidden(); + await more.click(); + await expect(menu.getByRole("menuitemcheckbox", { name: skipTests, checked: true })).toBeVisible(); + await setWidth(page, 360); + await expect(menu).toBeHidden(); + await expect(more).toBeHidden(); + await expect(toolbar.getByRole("button", { name: skipTests, pressed: true })).toBeVisible(); + await expect(toolbar.getByRole("button", { name: "Collapse All" })).toBeVisible(); + await setWidth(page, 190); + await expect(more).toBeVisible(); + await expect(menu).toBeHidden(); + }); +} diff --git a/src/features/build-tools/BuildToolView.tsx b/src/features/build-tools/BuildToolView.tsx index fabf69c79..0a34bce6b 100644 --- a/src/features/build-tools/BuildToolView.tsx +++ b/src/features/build-tools/BuildToolView.tsx @@ -1,6 +1,6 @@ /** The Maven and Gradle tool windows: toolbar, status banner and the project tree. */ import { writeClipboardText } from "@/platform/clipboard"; -import { useCallback, useEffect, useMemo, useState, type MouseEvent } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react"; import clsx from "clsx"; import type { BuildTool, GradleModel, MavenModel, RunConfig } from "@/platform/ipc"; import { downloadJdkActions } from "@/platform/jdk"; @@ -12,6 +12,7 @@ import { EmptyState, Icon, IconButton, + Menu, Spinner, Tree, showContextMenu, @@ -125,25 +126,99 @@ function nodeProject(n: BuildNode): string | undefined { return undefined; } +type ToolbarItem = Extract & { icon: string }; + +function toolbarButton({ action, icon, checked, label }: ToolbarItem) { + return ; +} + +function MoreActions({ items }: { items: MenuItem[] }) { + const anchor = useRef(null); + const [open, setOpen] = useState(false); + return ( + <> + setOpen((value) => !value)} + /> + setOpen(false)} + placement="bottom-end" + aria-label={tx("More Actions")} + items={items} + /> + + ); +} + +// Small buttons, separators, gaps and padding in the full toolbar. +const FULL_TOOLBAR_WIDTH: Record = { maven: 274, gradle: 230 }; + function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[] }) { + const toolbar = useRef(null); + const [compact, setCompact] = useState(false); const syncing = useBuild((s) => !!s.syncing[tool]); - const settings = useBuild((s) => s.settings); + const settings = useBuild((s) => s.settings[tool]); const model = useBuild((s) => s.model); + useLayoutEffect(() => { + const node = toolbar.current; + if (!node) return; + const measure = () => { + if (node.clientWidth > 0) setCompact(node.clientWidth < FULL_TOOLBAR_WIDTH[tool]); + }; + measure(); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(measure); + observer.observe(node); + return () => observer.disconnect(); + }, [tool]); const config = model && nodeConfig(selection.filter(isRunnable), model); const runSelected = () => { if (config) runConfig(config, "run"); }; const maven = tool === "maven"; + const projectActions: ToolbarItem[] = [ + ...(maven ? [{ kind: "action" as const, action: "maven.generateSources", icon: "folder-generated-source" }] : []), + { kind: "action", action: maven ? "maven.addProjects" : "gradle.linkProjects", icon: "plus" }, + ]; + const buildActions: ToolbarItem[] = [ + { kind: "action", action: `${tool}.toggleOffline`, icon: "build-offline", checked: settings.offline }, + { kind: "action", action: `${tool}.analyzeDependencies`, icon: "build-dependencies" }, + { kind: "action", action: `${tool}.toggleSkipTests`, icon: "skip-tests", checked: settings.skipTests }, + ]; + const treeActions: ToolbarItem[] = [ + { kind: "action", action: `${tool}.expandAll`, icon: "expand-all" }, + { kind: "action", action: `${tool}.collapseAll`, icon: "collapse-all" }, + ...(maven + ? [{ kind: "action" as const, action: "maven.settings", icon: "settings", label: "Maven Settings…" }] + : []), + ]; return ( -
+
{syncing ? ( ) : ( )} - {maven && } - - + {!compact && ( + <> + {projectActions.map(toolbarButton)} + + + )} - - - - - - - {maven && ( - + {compact ? ( + + ) : ( + <> + {buildActions.map(toolbarButton)} + + {treeActions.map(toolbarButton)} + )}
); diff --git a/src/features/build-tools/BuildTools.module.css b/src/features/build-tools/BuildTools.module.css index d064d29f4..3bd08d32d 100644 --- a/src/features/build-tools/BuildTools.module.css +++ b/src/features/build-tools/BuildTools.module.css @@ -12,6 +12,9 @@ gap: var(--space-0-5); padding: 0 6px; } +.toolbarMore { + margin-left: auto; +} .sep { width: 1px; height: 16px; From 639c76d54c42bfb15bff597eb5b79663b9955272 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:21:12 +0200 Subject: [PATCH 03/15] test(documents): protect dirty state on failed saves (#4567) Tests that a failed save keeps the edited buffer dirty and emits no clean-state event: text the encoding can't represent, permission denial (Unix, with a retry after restoring permissions) and a file replaced by a directory. Disk bytes and the replacement directory stay untouched. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- crates/ide-workspace/tests/documents.rs | 103 ++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index d5eb4f1ef..e91334caf 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -228,6 +228,109 @@ fn dirty_events(events: &[IdeEvent]) -> Vec { events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect() } +fn assert_failed_save_preserves_edit(f: &Fixture, doc: DocId, text: &str, before: usize) { + let snapshot = f.docs.snapshot(doc).unwrap(); + assert!(snapshot.dirty, "failed save marked the document clean"); + assert_eq!(snapshot.text, text, "failed save changed the unsaved buffer"); + assert!(!dirty_events(&f.events.lock()[before..]).contains(&false), "failed save emitted a clean-state event"); +} + +#[test] +fn unencodable_save_preserves_the_dirty_buffer_and_disk_bytes() { + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, b"caf\xe9").unwrap(); + let doc = f.docs.open(&path).unwrap().id; + assert_eq!(f.docs.set_encoding(doc, "windows-1252", true).unwrap().encoding, "windows-1252"); + let reloaded = f.docs.snapshot(doc).unwrap(); + assert_eq!(reloaded.text, "café"); + f.docs.edit(doc, reloaded.version, change(4, 4, "漢")).unwrap(); + let original = fs::read(&path).unwrap(); + + let before = f.events.lock().len(); + let err = f.docs.save(doc).expect_err("Windows-1252 cannot encode the edit"); + + assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}"); + assert_failed_save_preserves_edit(&f, doc, "café漢", before); + assert_eq!(fs::read(&path).unwrap(), original, "failed encoding changed disk bytes"); +} + +#[cfg(unix)] +#[test] +fn permission_denied_save_preserves_the_edit_and_can_be_retried() { + use std::os::unix::fs::PermissionsExt; + + struct RestorePermissions<'a>(&'a Path, fs::Permissions); + + impl Drop for RestorePermissions<'_> { + fn drop(&mut self) { + let result = fs::set_permissions(self.0, self.1.clone()); + if !std::thread::panicking() { + result.expect("restore fixture permissions"); + } + } + } + + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, b"original").unwrap(); + let doc = f.docs.open(&path).unwrap().id; + f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap(); + + { + let _dir_permissions = RestorePermissions(&f.root, fs::metadata(&f.root).unwrap().permissions()); + let _file_permissions = RestorePermissions(&path, fs::metadata(&path).unwrap().permissions()); + // Deny both sibling temp-file creation and the fallback write to the existing file. + fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap(); + fs::set_permissions(&f.root, fs::Permissions::from_mode(0o555)).unwrap(); + let sibling = fs::OpenOptions::new().write(true).create_new(true).open(f.root.join("probe")); + let in_place = fs::OpenOptions::new().write(true).open(&path); + for (probe, access) in [(sibling, "create a sibling file"), (in_place, "open the target for writing")] { + match probe { + Ok(_) => { + eprintln!("skipping permission-denied save: test process can {access} despite permission bits"); + return; + } + Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{access}: {err}"), + } + } + + let before = f.events.lock().len(); + let err = f.docs.save(doc).expect_err("neither atomic nor in-place save should be writable"); + + assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err}"); + assert_failed_save_preserves_edit(&f, doc, "edited", before); + assert_eq!(fs::read(&path).unwrap(), b"original", "failed write changed disk bytes"); + } + + let before = f.events.lock().len(); + f.docs.save(doc).expect("retry after restoring file and directory permissions"); + + assert_eq!(fs::read(&path).unwrap(), b"edited"); + assert!(!f.docs.snapshot(doc).unwrap().dirty, "successful retry left the document dirty"); + assert_eq!(dirty_events(&f.events.lock()[before..]), vec![false]); +} + +#[test] +fn save_to_a_path_replaced_by_a_directory_preserves_the_dirty_buffer() { + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, b"original").unwrap(); + let doc = f.docs.open(&path).unwrap().id; + f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap(); + assert!(f.docs.snapshot(doc).unwrap().dirty); + fs::remove_file(&path).unwrap(); + fs::create_dir(&path).unwrap(); + + let before = f.events.lock().len(); + f.docs.save(doc).expect_err("save must not replace a directory with a file"); + + assert_failed_save_preserves_edit(&f, doc, "edited", before); + assert!(fs::symlink_metadata(&path).unwrap().is_dir(), "save removed the replacement directory"); + assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "save left artifacts inside the replacement directory"); + assert_eq!(fs::read_dir(&f.root).unwrap().count(), 1, "save left artifacts beside the replacement directory"); +} + #[test] fn autosave_leaves_a_file_changed_on_disk_after_an_edit() { let f = fixture(); From 39523bc419d3045b4ad85414e9f8e64aca931a7c Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 01:23:38 +0800 Subject: [PATCH 04/15] fix(terminal): float search over the output area (#4560) Find in Terminal took a full-width row and shrank the grid. Wide, tall panes now show a compact search bar over the output's upper-right corner, keeping the full grid; it moves to the lower right when it would cover the active match. Short panes use an inline bar and narrow panes put the controls in two rows. --- e2e/terminal-ui.spec.ts | 64 +++++++++++++++++++++++ src/features/terminal/FindBar.tsx | 47 +++++++++++++++-- src/features/terminal/Terminal.module.css | 36 +++++++++---- src/features/terminal/TerminalView.tsx | 32 ++++++------ src/features/terminal/session.ts | 4 +- 5 files changed, 155 insertions(+), 28 deletions(-) diff --git a/e2e/terminal-ui.spec.ts b/e2e/terminal-ui.spec.ts index 599da22d2..f33e35a74 100644 --- a/e2e/terminal-ui.spec.ts +++ b/e2e/terminal-ui.spec.ts @@ -60,6 +60,70 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 }, }); } +test("wide terminal search leaves the grid in place and avoids covering the active match", async ({ + workbench: page, +}) => { + await page.evaluate(async () => { + const path = "/src/workbench/toolwindows/store.ts"; + const layout = await import(path); + layout.setToolWindowSize("bottom", 280); + layout.showToolWindow("terminal", true); + }); + const terminal = page.getByRole("region", { name: "Terminal", exact: true }); + await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused(); + const panel = terminal.getByRole("tabpanel"); + const before = (await panel.boundingBox())!; + await page.evaluate(async () => { + const path = "/src/features/terminal/runtime.ts"; + const { activeSession } = await import(path); + const { term } = activeSession(); + await new Promise((resolve) => + term.write(`\x1b[2J\x1b[1;${term.cols - 16}Hright-edge\x1b[1;2Hleft-side\x1b[6;1H`, resolve), + ); + }); + + await page.keyboard.press("Meta+f"); + const search = terminal.getByRole("search", { name: "Find in terminal" }); + const input = search.getByRole("textbox", { name: "Find in terminal" }); + await expect(input).toBeFocused(); + expect(await panel.boundingBox()).toEqual(before); + const top = (await search.boundingBox())!; + expect(top.y).toBeCloseTo(before.y, 0); + expect(top.x + top.width).toBeCloseTo(before.x + before.width, 0); + expect(top.width).toBeLessThan(before.width); + + await input.fill("right-edge"); + await expect(search.locator("[aria-live=polite]")).toHaveText("1/1"); + await expect + .poll(async () => { + const box = (await search.boundingBox())!; + return box.y + box.height; + }) + .toBeCloseTo(before.y + before.height, 0); + await expect(input).toBeFocused(); + expect(await panel.boundingBox()).toEqual(before); + + await input.fill("left-side"); + await expect(search.locator("[aria-live=polite]")).toHaveText("1/1"); + await expect.poll(async () => (await search.boundingBox())!.y).toBeCloseTo(before.y, 0); + + await page.evaluate(async () => { + const path = "/src/workbench/toolwindows/store.ts"; + const { setToolWindowSize } = await import(path); + setToolWindowSize("bottom", 130); + }); + await expect + .poll(async () => { + const box = (await search.boundingBox())!; + return box.y + box.height - (await panel.boundingBox())!.y; + }) + .toBeCloseTo(0, 0); + await expect(input).toHaveValue("left-side"); + await page.keyboard.press("Escape"); + await expect(search).toBeHidden(); + await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused(); +}); + test("terminal highlights visible occurrences of selected text in a single overlay layer", async ({ workbench: page, }) => { diff --git a/src/features/terminal/FindBar.tsx b/src/features/terminal/FindBar.tsx index d646736d5..50155ba18 100644 --- a/src/features/terminal/FindBar.tsx +++ b/src/features/terminal/FindBar.tsx @@ -1,9 +1,9 @@ /** ⌘F in the terminal: search the scrollback (xterm addon-search) with Match Case / Words / Regex. */ -import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { create } from "zustand"; import { IconButton, SearchField } from "@/ui"; -import type { TerminalSearchOptions, TerminalSearchResult } from "./session"; +import { ACTIVE_SEARCH_DECORATION_CLASS, type TerminalSearchOptions, type TerminalSearchResult } from "./session"; import { activeSession } from "./store"; import styles from "./Terminal.module.css"; import { formatBinding, hasPrimaryModifier } from "@/platform/keymap"; @@ -52,6 +52,7 @@ let focusedSeq = 0; export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) { const { open, seq, query, options } = useTerminalFind(); + const bar = useRef(null); const input = useRef(null); const [result, setResult] = useState(null); @@ -79,6 +80,46 @@ export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) { }; }, [open, query, options, sessionKey]); + // Measure against the bar's default upper-right position, even when it has moved. + useLayoutEffect(() => { + if (!open) return; + const element = bar.current; + const output = element?.parentElement; + const session = activeSession(); + if (!element || !output || !session) return; + let frame = 0; + const update = () => { + if (frame) return; + frame = requestAnimationFrame(() => { + frame = 0; + const match = session.isSearchSelection + ? session.host.querySelector(`.${ACTIVE_SEARCH_DECORATION_CLASS}`)?.getBoundingClientRect() + : undefined; + if (!match?.width) { + element.removeAttribute("data-match-covered"); + return; + } + const top = output.getBoundingClientRect().top; + const { left, right, height } = element.getBoundingClientRect(); + element.toggleAttribute( + "data-match-covered", + match.bottom > top && match.top < top + height && match.right > left && match.left < right, + ); + }); + }; + const render = session.term.onRender(update); + const observer = new ResizeObserver(update); + observer.observe(output); + observer.observe(element); + update(); + return () => { + render.dispose(); + observer.disconnect(); + cancelAnimationFrame(frame); + element.removeAttribute("data-match-covered"); + }; + }, [open, sessionKey]); + if (!open) return null; const find = (direction: "next" | "previous") => activeSession()?.find(query, options, direction); @@ -110,6 +151,7 @@ export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) { return (
find("next")} /> -
); diff --git a/src/features/terminal/Terminal.module.css b/src/features/terminal/Terminal.module.css index aad71fc08..211c1d00f 100644 --- a/src/features/terminal/Terminal.module.css +++ b/src/features/terminal/Terminal.module.css @@ -27,7 +27,6 @@ /* A tab group: its header (while split) over its tabs' terminals. */ .group { - container: terminal-group / inline-size; flex: 1; display: flex; flex-direction: column; @@ -35,6 +34,15 @@ min-height: 0; } +.output { + container: terminal-output / size; + flex: 1; + min-height: 0; + position: relative; + display: flex; + flex-direction: column; +} + .panels { flex: 1; position: relative; @@ -160,12 +168,12 @@ border-bottom: 1px solid var(--border); } .findField { - flex: 0 1 360px; + flex: 1; min-width: 160px; } .findCount { - font-family: var(--font-mono); font-size: var(--fs-small); + font-variant-numeric: tabular-nums; color: var(--fg-subtle); padding: 0 6px; white-space: nowrap; @@ -174,11 +182,24 @@ .findCountNone { color: var(--danger); } -.findSpacer { - flex: 1; +@container terminal-output (min-width: 500px) and (min-height: 160px) { + .find { + position: absolute; + top: 0; + right: 0; + z-index: 6; + width: 500px; + border-left: 1px solid var(--border); + } + .find[data-match-covered] { + top: auto; + bottom: 0; + border-top: 1px solid var(--border); + border-bottom: 0; + } } -@container terminal-group (max-width: 360px) { +@container terminal-output (max-width: 360px) { .find { display: grid; grid-template-columns: minmax(0, 1fr) repeat(3, var(--h-control-small)); @@ -187,7 +208,4 @@ grid-column: 1 / -1; min-width: 0; } - .findSpacer { - display: none; - } } diff --git a/src/features/terminal/TerminalView.tsx b/src/features/terminal/TerminalView.tsx index 77b23cd66..3797ce7d2 100644 --- a/src/features/terminal/TerminalView.tsx +++ b/src/features/terminal/TerminalView.tsx @@ -218,21 +218,23 @@ function TabGroup({ group, corners }: { group: string; corners: Corners | null } )} - {active && } -
- {dropZone &&
} - {tabs.map((t) => ( - - ))} +
+ {active && } +
+ {dropZone &&
} + {tabs.map((t) => ( + + ))} +
); diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts index 48a98e32a..5c795410a 100644 --- a/src/features/terminal/session.ts +++ b/src/features/terminal/session.ts @@ -45,6 +45,8 @@ import { } from "./theme"; import { wheelZoomStep } from "@/platform/wheelZoom"; +export const ACTIVE_SEARCH_DECORATION_CLASS = "xterm-find-active-result-decoration"; + export interface TerminalSearchOptions { caseSensitive: boolean; regex: boolean; @@ -350,7 +352,7 @@ export class TerminalSession { const active = this.searchDecorations?.activeMatchBackground; const isActive = !!active && options.backgroundColor?.toLowerCase() === active.toLowerCase(); const d = registerDecoration(isActive ? { ...options, layer: "top" } : options); - if (d && isActive) d.onRender((el) => el.classList.add("xterm-find-active-result-decoration")); + if (d && isActive) d.onRender((el) => el.classList.add(ACTIVE_SEARCH_DECORATION_CLASS)); return d; }; const runSearch = From 67a4797cf43c891204678fb7c82af30856d2e483 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:28:48 +0200 Subject: [PATCH 05/15] fix(editor): preserve dirty state across concurrent saves (#4571) Typing while a save was pending could leave the editor clean although the newest edit was not written: the save reply cleared the dirty flag even after a dirty event for a newer version, and a delayed clean event for the earlier write could clear it too. DocDirty now carries the document version from under the backend lock; the editor applies a clean transition only when that version is the synced one and no edits are pending, and a save reply only confirms the version it sent. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- crates/ide-core/src/event.rs | 2 + crates/ide-workspace/src/documents.rs | 2 +- crates/ide-workspace/tests/documents.rs | 10 ++ docs/en/guide/editor.mdx | 2 + docs/zh/guide/editor.mdx | 2 + src/bindings.ts | 4 +- src/editor/core/backend.ts | 10 +- src/editor/core/model/document.test.ts | 168 ++++++++++++++++++ src/editor/core/model/document.ts | 44 +++-- src/editor/core/sync/DocSync.ts | 4 + src/editor/core/untitled.test.ts | 34 ++++ src/features/app/__tests__/closeGuard.test.ts | 8 +- 12 files changed, 269 insertions(+), 21 deletions(-) diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index 4cbc4cc7d..2a9865d97 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -89,6 +89,8 @@ pub enum IdeEvent { DocDirty { doc: DocId, dirty: bool, + /// Text version when this transition occurred, including when it was saved. + version: u32, }, /// A complete workspace edit can be undone as one operation. WorkspaceEditApplied { diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index 148cff21a..f33d08c93 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -672,7 +672,7 @@ impl Documents { fn set_dirty(&self, doc: DocId, st: &mut DocState, dirty: bool) { if st.dirty != dirty { st.dirty = dirty; - self.sink.emit(IdeEvent::DocDirty { doc, dirty }); + self.sink.emit(IdeEvent::DocDirty { doc, dirty, version: st.doc.version() }); } } diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index e91334caf..9b288b05c 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -352,6 +352,16 @@ fn autosave_leaves_a_file_changed_on_disk_after_an_edit() { f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap(); assert!(f.docs.autosave(info.id).unwrap()); assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n"); + let transitions: Vec<_> = f + .events + .lock() + .iter() + .filter_map(|event| match event { + IdeEvent::DocDirty { doc, dirty, version } if *doc == info.id => Some((*version, *dirty)), + _ => None, + }) + .collect(); + assert_eq!(transitions, [(1, true), (1, false), (2, true), (2, false)]); } #[test] diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index c70709e76..31e0d95cf 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -136,6 +136,8 @@ With tabs placed left or right, the tab column is as wide as its longest name, u As in IntelliJ IDEA, there is no per-file save: files are saved when you switch to another application or to the built-in terminal, and **File › Save All** (`⌘S` / `Ctrl+S`) saves everything at once. **Settings › Appearance & Behavior › System Settings**, section **Autosave**, can also save after the IDE has been idle for a while. +If you keep typing during a save, edits not included in that write stay marked as unsaved. + Changes made outside the IDE are picked up when you switch back to its window. **Reload from Disk** (`⌥⌘Y` / `Ctrl+Alt+Y`) reloads the current file now. ## Related diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index a636d67e2..9760bedfc 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -136,6 +136,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。 +如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。 + 在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。 ## 相关页面 diff --git a/src/bindings.ts b/src/bindings.ts index 6159407e7..85284a39c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -7043,7 +7043,9 @@ ignoreRules?: IpcPath[] } | /** Part of a grouped transaction; the editor must not record a file-local undo. */ workspaceEdit?: boolean } | /** A document's dirty flag changed (saved / modified externally). */ -{ type: "docDirty"; doc: DocId; dirty: boolean } | +{ type: "docDirty"; doc: DocId; dirty: boolean; +/** Text version when this transition occurred, including when it was saved. */ +version: number } | /** A complete workspace edit can be undone as one operation. */ { type: "workspaceEditApplied"; id: number; paths: IpcPath[]; /** diff --git a/src/editor/core/backend.ts b/src/editor/core/backend.ts index aa2bfa35f..c17138cf7 100644 --- a/src/editor/core/backend.ts +++ b/src/editor/core/backend.ts @@ -16,6 +16,7 @@ import { type DocumentInfo, type DocumentLanguage, type FoldRange, + type IdeEvent, type LanguageInfo_Serialize, type LineEnding, type OutlineItem, @@ -38,6 +39,8 @@ export interface DocPatchedEvent { changes: TextChange[]; } +export type DocDirtyEvent = Extract; + export interface DocBackend { open(path: string): Promise; /** Opens a read-only language-server document (library or disk class contents). */ @@ -71,7 +74,7 @@ export interface DocBackend { */ languageOf?(path: string, firstLine?: string): Promise; onPatched(handler: (e: DocPatchedEvent) => void): () => void; - onDirty(handler: (e: { doc: DocId; dirty: boolean }) => void): () => void; + onDirty(handler: (e: DocDirtyEvent) => void): () => void; /** Files changed on disk (used to refresh nothing but closed-file state). */ onFsChanged?(handler: (e: { removed: string[] }) => void): () => void; /** @@ -393,7 +396,7 @@ export function createMemoryBackend(files: Record = {}): MemoryB const docs = new Map(); const byPath = new Map(); const patched = new Set<(e: DocPatchedEvent) => void>(); - const dirtyHandlers = new Set<(e: { doc: DocId; dirty: boolean }) => void>(); + const dirtyHandlers = new Set<(e: DocDirtyEvent) => void>(); let nextId = 1; const store = new Map(Object.entries(files)); const savedBoms = new Map(); @@ -442,7 +445,8 @@ export function createMemoryBackend(files: Record = {}): MemoryB }; const setDirty = (d: MemDoc, before: boolean) => { const now = d.text !== d.saved || d.hasBom !== d.savedBom; - if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now })); + if (now !== before) + dirtyHandlers.forEach((h) => h({ type: "docDirty", doc: d.id, dirty: now, version: d.version })); }; const delay = (v: () => T): Promise => backend.latency > 0 diff --git a/src/editor/core/model/document.test.ts b/src/editor/core/model/document.test.ts index 23aeed487..ec343a92a 100644 --- a/src/editor/core/model/document.test.ts +++ b/src/editor/core/model/document.test.ts @@ -30,6 +30,14 @@ async function settle() { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); } +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + function setup(files: Record, settings = {}) { _resetLanguages(); const backend: MemoryBackend = createMemoryBackend(files); @@ -217,6 +225,166 @@ describe("DocumentManager + slots", () => { expect(useDocMeta.getState()["/p/a.txt"]?.dirty).toBe(false); }); + it.each(["dirty before response", "dirty after response", "clean and dirty after response"] as const)( + "keeps a newer edit dirty with %s", + async (order) => { + const path = "/p/a.txt"; + const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } }); + const model = await manager.acquire(path); + const slot = new EditorSlot(model, "t1", host); + const events: Array<() => void> = []; + const originalOnDirty = backend.onDirty.bind(backend); + let deferDirty = false; + const onDirty = vi.spyOn(backend, "onDirty").mockImplementation((handler) => + originalOnDirty((event) => { + if (deferDirty) events.push(() => handler(event)); + else handler(event); + }), + ); + manager.stop(); + manager.start(); + const response = deferred(); + const originalSave = backend.save.bind(backend); + const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => { + await originalSave(doc); + await response.promise; + }); + const transitions: boolean[] = []; + const unsubscribe = useDocMeta.subscribe((state, previous) => { + const dirty = state[path]?.dirty; + if (dirty !== undefined && dirty !== previous[path]?.dirty) transitions.push(dirty); + }); + let pending: Promise | undefined; + try { + slot.dispatchLocal({ changes: { from: 4, insert: " saved" } }); + await model.sync.whenIdle(); + expect(transitions).toEqual([true]); + + deferDirty = order === "clean and dirty after response"; + pending = model.save("explicit"); + await vi.waitFor(() => expect(backend.files.get(path)).toBe("base saved\n")); + expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false }); + + transitions.length = 0; + deferDirty = order !== "dirty before response"; + slot.dispatchLocal({ changes: { from: 10, insert: " newer" } }); + await model.sync.whenIdle(); + expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: true }); + + response.resolve(); + await pending; + expect(slot.currentState().doc.toString()).toBe("base saved newer\n"); + expect(backend.files.get(path)).toBe("base saved\n"); + expect(model.getMeta().dirty).toBe(true); + const deferredCount = order === "dirty before response" ? 0 : order === "dirty after response" ? 1 : 2; + expect(events).toHaveLength(deferredCount); + events.splice(0).forEach((deliver) => deliver()); + expect(useDocMeta.getState()[path]?.dirty).toBe(true); + expect(transitions).not.toContain(false); + + deferDirty = false; + await model.save("explicit"); + expect(backend.files.get(path)).toBe("base saved newer\n"); + expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: false }); + expect(useDocMeta.getState()[path]?.dirty).toBe(false); + expect(transitions.at(-1)).toBe(false); + } finally { + response.resolve(); + try { + await pending; + } finally { + unsubscribe(); + save.mockRestore(); + onDirty.mockRestore(); + slot.dispose(); + manager.releaseProjectDocuments(); + manager.stop(); + } + } + }, + ); + + it("marks an unchanged buffer clean when its save succeeds", async () => { + const path = "/p/a.txt"; + const { backend, manager } = setup({ [path]: "base\n" }); + const model = await manager.acquire(path); + const slot = new EditorSlot(model, "t1", host); + const transitions: Array<{ dirty: boolean; persisted: string | undefined }> = []; + const unsubscribe = useDocMeta.subscribe((state, previous) => { + const dirty = state[path]?.dirty; + if (dirty !== undefined && dirty !== previous[path]?.dirty) + transitions.push({ dirty, persisted: backend.files.get(path) }); + }); + try { + slot.dispatchLocal({ changes: { from: 4, insert: " saved" } }); + await model.save("explicit"); + expect(slot.currentState().doc.toString()).toBe("base saved\n"); + expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false }); + expect(transitions).toEqual([ + { dirty: true, persisted: "base\n" }, + { dirty: false, persisted: "base saved\n" }, + ]); + } finally { + unsubscribe(); + slot.dispose(); + manager.releaseProjectDocuments(); + manager.stop(); + } + }); + + it("reconciles a save that includes an edit whose acknowledgement is still pending", async () => { + const path = "/p/a.txt"; + const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } }); + const model = await manager.acquire(path); + const slot = new EditorSlot(model, "t1", host); + const write = deferred(); + const editReply = deferred(); + const originalSave = backend.save.bind(backend); + const originalEdit = backend.edit.bind(backend); + const edit = vi.spyOn(backend, "edit"); + const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => { + await write.promise; + await originalSave(doc); + }); + let pending: Promise | undefined; + try { + slot.dispatchLocal({ changes: { from: 4, insert: " first" } }); + await model.sync.whenIdle(); + pending = model.save("explicit"); + await vi.waitFor(() => expect(save).toHaveBeenCalledWith(model.doc)); + + edit.mockImplementationOnce(async (...args) => { + const version = await originalEdit(...args); + await editReply.promise; + return version; + }); + slot.dispatchLocal({ changes: { from: 10, insert: " second" } }); + const synced = model.sync.whenIdle(); + await vi.waitFor(async () => { + expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base first second\n", dirty: true }); + }); + write.resolve(); + await pending; + editReply.resolve(); + await synced; + expect(slot.currentState().doc.toString()).toBe("base first second\n"); + expect(backend.files.get(path)).toBe("base first second\n"); + expect(useDocMeta.getState()[path]?.dirty).toBe(false); + } finally { + editReply.resolve(); + write.resolve(); + try { + await pending; + } finally { + edit.mockRestore(); + save.mockRestore(); + slot.dispose(); + manager.releaseProjectDocuments(); + manager.stop(); + } + } + }); + it.each(["explicit", "auto"] as const)( "%s save leaves untouched documents byte-for-byte unchanged", async (reason) => { diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts index 5ba127836..2b8a630ad 100644 --- a/src/editor/core/model/document.ts +++ b/src/editor/core/model/document.ts @@ -28,7 +28,7 @@ import { } from "@/editor/api"; import { isUntitledUri, isVirtualUri } from "@/platform/virtualDocs"; import { DocSync, type Scheduler, frameScheduler } from "../sync/DocSync"; -import type { DocBackend, LanguageInfo } from "../backend"; +import type { DocBackend, DocDirtyEvent, LanguageInfo } from "../backend"; import { findLanguageDescription, languageInfo, @@ -261,6 +261,7 @@ export class DocModel { handoffRelease = false; private refreshTimer: ReturnType | undefined; private saving: Promise = Promise.resolve(); + private backendDirty: DocDirtyEvent | null = null; private meta: DocMeta; constructor( @@ -321,6 +322,7 @@ export class DocModel { changes: eventChanges, }); }, + onSynced: () => this.applyBackendClean(), onDiscarded: (reason) => { logError(`document ${this.path}: unsaved edits replaced by the file's content`, reason); manager.notify({ @@ -345,6 +347,26 @@ export class DocModel { if (!this.closed) useDocMeta.setState({ [this.path]: this.meta }); } + onBackendDirty(event: DocDirtyEvent) { + if (this.backendDirty && event.version < this.backendDirty.version) return; + this.backendDirty = event; + if (event.dirty) { + if (!this.meta.dirty) this.setMeta({ dirty: true }); + } else this.applyBackendClean(); + } + + private applyBackendClean() { + const event = this.backendDirty; + if (event && !event.dirty) this.markClean(event.version); + } + + private markClean(version: number) { + // A clean event can arrive before an edit acknowledgement or after a newer edit. + if (!this.meta.dirty || !this.sync.idle || this.sync.serverVersion !== version) return; + this.modified.clear(); + this.setMeta({ dirty: false }); + } + ctx(): EditorDocContext { return { doc: this.doc, @@ -713,16 +735,20 @@ export class DocModel { // an explicit save asks for one (Save As re-points the buffer, or stays // dirty on Cancel). if (reason === "auto") return; - if (await this.manager.saveAs(this)) this.modified.clear(); + await this.manager.saveAs(this); return; } const backend = this.manager.backend; + const version = this.sync.serverVersion; + const observedDirty = this.backendDirty; // Autosave never overwrites external changes made after the buffer was edited. if (reason === "auto" && backend.autosave) { if (!(await backend.autosave(this.doc))) return; } else await backend.save(this.doc); - this.modified.clear(); - this.setMeta({ dirty: false }); + // The reply does not identify what was saved. It only confirms the version + // we sent if the buffer and the observed backend dirty state haven't moved on. + if (this.backendDirty === observedDirty && (!observedDirty || observedDirty.version <= version)) + this.markClean(version); _emitEditorEvent({ type: "docSaved", doc: this.doc, path: this.path }); }; this.saving = this.saving.then(run, run); @@ -732,6 +758,7 @@ export class DocModel { /** Save As turned this untitled buffer into the file `info` points at. */ retarget(info: DocumentInfo) { const old = this.path; + if (!this.backendDirty?.dirty || this.backendDirty.version < info.version) this.markClean(info.version); this.path = info.path; this.info = languageInfo(info.language); this.editorconfig = info.editorconfig ?? null; @@ -743,7 +770,6 @@ export class DocModel { hasBom: info.hasBom, lineEnding: info.lineEnding, canReloadEncoding: info.canReloadEncoding, - dirty: false, }; useDocMeta.setState((s) => { const next = { ...s }; @@ -803,13 +829,7 @@ export class DocumentManager { this.workspaceHistory.start(), this.backend.onPatched((e) => this.byId.get(e.doc)?.sync.remote(e)), this.backend.onLanguage?.((e) => this.byId.get(e.doc)?.setLanguage(e.language, e.uiMode)) ?? (() => {}), - this.backend.onDirty((e) => { - const m = this.byId.get(e.doc); - if (m && m.getMeta().dirty !== e.dirty) { - m.setMeta({ dirty: e.dirty }); - if (!e.dirty) m.modified.clear(); - } - }), + this.backend.onDirty((e) => this.byId.get(e.doc)?.onBackendDirty(e)), ); let prev = useEditorRegistry.getState().contributions; this.disposers.push( diff --git a/src/editor/core/sync/DocSync.ts b/src/editor/core/sync/DocSync.ts index a1f148ead..8bd433fd8 100644 --- a/src/editor/core/sync/DocSync.ts +++ b/src/editor/core/sync/DocSync.ts @@ -38,6 +38,8 @@ export interface SyncHost { applyRemote(changes: ChangeSet, workspaceEdit?: boolean): void; /** A locally produced batch accepted by the versioned backend. */ onLocalCommitted?(baseVersion: number, version: number, changes: ChangeSet): void; + /** The local buffer has no pending edits or resync. */ + onSynced?(): void; /** Called after a hard resync discarded local changes the backend never saw. */ onDiscarded?(reason: unknown): void; /** Non-recoverable transport errors (logged by default). */ @@ -157,6 +159,7 @@ export class DocSync { if (this.disposed || patch.version <= this.serverVersion) return; this.pendingRemote.push(patch); this.drainRemote(); + this.resolveIdle(); } dispose() { @@ -356,6 +359,7 @@ export class DocSync { private resolveIdle(force = false) { if (!force && !this.idle) return; + if (this.idle && !this.disposed) this.host.onSynced?.(); const waiters = this.idleWaiters; this.idleWaiters = []; waiters.forEach((w) => w()); diff --git a/src/editor/core/untitled.test.ts b/src/editor/core/untitled.test.ts index 93f81cc69..58445a4c5 100644 --- a/src/editor/core/untitled.test.ts +++ b/src/editor/core/untitled.test.ts @@ -101,6 +101,40 @@ describe("untitled editor input", () => { expect(JSON.stringify(session)).not.toContain("untitled:"); }); + it("keeps edits made after a Save As write dirty when retargeting the tab", async () => { + await ctrl!.openUntitled({ focus: false }); + const slot = ctrl!.slotFor(activeTab().id)!; + const model = await editActive("draft"); + const path = "/p/saved.txt"; + vi.mocked(save).mockResolvedValue(path); + let release!: () => void; + const response = new Promise((resolve) => { + release = resolve; + }); + const originalSaveAs = backend.saveAs.bind(backend); + const saveAs = vi.spyOn(backend, "saveAs").mockImplementationOnce(async (...args) => { + const info = await originalSaveAs(...args); + await response; + return info; + }); + const pending = model.save("explicit"); + try { + await vi.waitFor(() => expect(backend.files.get(path)).toBe("draft\n")); + slot.dispatchLocal({ changes: { from: 5, insert: " newer" } }); + await model.sync.whenIdle(); + release(); + await pending; + expect(activeTab().input.path).toBe(path); + expect(slot.currentState().doc.toString()).toBe("draft newer\n"); + expect(backend.files.get(path)).toBe("draft\n"); + expect(await backend.snapshot(model.doc)).toMatchObject({ text: "draft newer\n", dirty: true }); + expect(useDocMeta.getState()[path]?.dirty).toBe(true); + } finally { + release(); + await pending.finally(() => saveAs.mockRestore()); + } + }); + it("offers the registered languages as save-as types", async () => { await ctrl!.openUntitled({ focus: false }); const slot = ctrl!.slotFor(activeTab().id)!; diff --git a/src/features/app/__tests__/closeGuard.test.ts b/src/features/app/__tests__/closeGuard.test.ts index 4d7c30a7f..23accbfd8 100644 --- a/src/features/app/__tests__/closeGuard.test.ts +++ b/src/features/app/__tests__/closeGuard.test.ts @@ -260,14 +260,14 @@ it("includes pending local edits and restored dirty buffers before backend dirty const uninstall = installCloseGuard(d); const spy = vi.spyOn(service, "maybeEditorService").mockReturnValue({ dirtyDocumentIds: () => [10, 11] } as never); try { - emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: true }); - emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: true }); + emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: true, version: 1 }); + emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: true, version: 1 }); expect(dirtyCount()).toBe(3); await expect(confirmLeave(d)).resolves.toBe(false); expect(asked[0]?.body).toContain("3"); } finally { - emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: false }); - emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: false }); + emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: false, version: 1 }); + emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: false, version: 1 }); uninstall(); spy.mockRestore(); } From da1bcd67cd47a0237e8031766cdc8d3581305af8 Mon Sep 17 00:00:00 2001 From: Vadim Lazuk Date: Thu, 19 Nov 2026 20:30:22 +0300 Subject: [PATCH 06/15] fix(http-client): keep the request method across redirects and show the hops (#4519) reqwest's automatic redirects turned a POST into a plain GET on a 301 or 302, such as the http to https redirect in #4486, and hid the redirect. Redirects are now followed by hand, as IntelliJ's HTTP Client does: 301, 302, 303, 307 and 308, at most 50 times. A 303 continues as GET without the body; the other statuses keep the method and body. Authorization and cookie headers are not re-sent to another host. The followed hops are listed in the response view. Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com> --- crates/ide-http/src/client.rs | 17 +- crates/ide-http/src/exec.rs | 303 +++++++++++++++++- docs/en/guide/http-client.mdx | 2 +- docs/zh/guide/http-client.mdx | 2 +- src/bindings.ts | 9 + .../http-client/HttpClient.module.css | 15 + src/features/http-client/HttpClientView.tsx | 10 + .../http-client/responseFind.test.tsx | 1 + 8 files changed, 341 insertions(+), 18 deletions(-) diff --git a/crates/ide-http/src/client.rs b/crates/ide-http/src/client.rs index 6813ff07f..aeba2dded 100644 --- a/crates/ide-http/src/client.rs +++ b/crates/ide-http/src/client.rs @@ -65,8 +65,23 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P /// The client for the current proxy settings, rebuilt when they change. pub fn shared() -> IdeResult { static CLIENT: Mutex, reqwest::Client)>> = Mutex::new(None); + cached_client(&CLIENT, build) +} + +/// The client the HTTP Client executes requests with: redirects off, `exec` +/// follows them by hand — that is what lets a `POST` stay a `POST` on a +/// 301/302 and puts the redirect chain into the response. +pub fn shared_without_redirects() -> IdeResult { + static CLIENT: Mutex, reqwest::Client)>> = Mutex::new(None); + cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none())) +} + +fn cached_client( + slot: &Mutex, reqwest::Client)>>, + build: fn(&ProxySettings) -> IdeResult, +) -> IdeResult { let proxy = ide_core::proxy_settings::proxy(); - let mut cached = CLIENT.lock(); + let mut cached = slot.lock(); if let Some((settings, client)) = cached.as_ref() && **settings == *proxy { diff --git a/crates/ide-http/src/exec.rs b/crates/ide-http/src/exec.rs index 8c99f80f3..c51d53b1e 100644 --- a/crates/ide-http/src/exec.rs +++ b/crates/ide-http/src/exec.rs @@ -13,6 +13,19 @@ use std::time::Instant; /// Bodies above this are cut (the full size is still reported). pub const MAX_BODY: usize = 16 * 1024 * 1024; +/// Redirects followed per request; beyond this the redirect response itself is +/// returned (IntelliJ's HTTP Client follows the same number). +pub const MAX_REDIRECTS: usize = 50; + +/// Responses whose `Location` is followed: 301, 302, 303, 307 and 308, the set +/// IntelliJ's HTTP Client redirects on. +const REDIRECT_STATUSES: [u16; 5] = [301, 302, 303, 307, 308]; + +/// Request headers not re-sent to a redirect on another host. IntelliJ's HTTP +/// Client strips the same set and restores it when the redirect stays on the +/// original host. +const SENSITIVE_HEADERS: [&str; 5] = ["authorization", "cookie", "cookie2", "www-authenticate", "proxy-authorization"]; + /// A request ready to send: variables substituted, includes read. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -24,6 +37,15 @@ pub struct PreparedRequest { pub body: Option, } +/// One followed redirect: the response and the `Location` it pointed to. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct RedirectHop { + pub status: u16, + pub status_text: String, + pub location: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct HttpResponse { @@ -32,6 +54,9 @@ pub struct HttpResponse { pub version: String, pub headers: Vec<(String, String)>, pub content_type: Option, + /// Followed redirects, first hop first; empty when not redirected. + #[serde(default)] + pub redirects: Vec, /// Body as text (lossy UTF-8); `None` for binary bodies. pub body: Option, /// Size in bytes as received (after decompression). @@ -128,25 +153,84 @@ fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool { } } -/// Sends `req`; cancelled when `cancel` fires. +/// The request for one hop: `req`'s headers and body against `url`, the +/// sensitive headers dropped when the redirect crosses to another host. +fn request_to( + client: &reqwest::Client, + method: &reqwest::Method, + req: &PreparedRequest, + body: Option<&str>, + original: &reqwest::Url, + url: &reqwest::Url, +) -> IdeResult { + let same_host = url.host_str() == original.host_str(); + let mut builder = client.request(method.clone(), url.clone()); + for (k, v) in &req.headers { + if same_host || !SENSITIVE_HEADERS.iter().any(|s| k.eq_ignore_ascii_case(s)) { + builder = builder.header(k, v); + } + } + if let Some(body) = body { + builder = builder.body(body.to_owned()); + } + builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}"))) +} + +/// Sends `request`; cancelled when `cancel` fires. +async fn send( + client: &reqwest::Client, + request: reqwest::Request, + cancel: &CancellationToken, +) -> IdeResult { + let send = client.execute(request); + tokio::select! { + r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e))), + () = cancel.cancelled() => Err(IdeError::cancelled()), + } +} + +/// Sends `req`, following redirects the way IntelliJ's HTTP Client does: +/// 301, 302, 303, 307 and 308 up to [`MAX_REDIRECTS`] times, `303` continuing +/// as `GET` without the body, the other statuses keeping the method and body — +/// so a `POST` redirected to `https` on the same host is re-sent as a `POST`. +/// Sensitive headers (Authorization, cookies, proxy credentials) are not +/// re-sent across hosts. The followed hops are reported in the response. +/// Cancelled when `cancel` fires. pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeResult { - let client = crate::client::shared()?; + let client = crate::client::shared_without_redirects()?; let method = reqwest::Method::from_bytes(req.method.as_bytes()) .map_err(|_| IdeError::invalid(format!("invalid method {}", req.method)))?; - let mut builder = client.request(method, &req.url); - for (k, v) in &req.headers { - builder = builder.header(k, v); - } - if let Some(body) = &req.body { - builder = builder.body(body.clone()); - } - let request = builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?; + let original = req.url.parse::().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?; + let mut url = original.clone(); + let mut method = method; + let mut body = req.body.clone(); + let mut redirects = Vec::new(); let started = Instant::now(); - let send = client.execute(request); - let mut response = tokio::select! { - r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e)))?, - () = cancel.cancelled() => return Err(IdeError::cancelled()), - }; + let mut response; + loop { + let request = request_to(&client, &method, req, body.as_deref(), &original, &url)?; + response = send(&client, request, cancel).await?; + let status = response.status(); + if redirects.len() >= MAX_REDIRECTS || !REDIRECT_STATUSES.contains(&status.as_u16()) { + break; + } + let next = response + .headers() + .get(reqwest::header::LOCATION) + .and_then(|v| v.to_str().ok()) + .and_then(|location| url.join(location).ok()); + let Some(next) = next else { break }; + redirects.push(RedirectHop { + status: status.as_u16(), + status_text: status.canonical_reason().unwrap_or("").to_owned(), + location: next.to_string(), + }); + if status == reqwest::StatusCode::SEE_OTHER { + method = reqwest::Method::GET; + body = None; + } + url = next; + } let ttfb = started.elapsed(); let status = response.status(); let version = format!("{:?}", response.version()); @@ -179,6 +263,7 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe version, headers, content_type, + redirects, body, size: size as f64, truncated: size > bytes.len(), @@ -249,6 +334,47 @@ mod tests { assert_eq!(url("GET https://api.test/cb?u=http://x\n"), "https://api.test/cb?u=http://x"); } + /// A loopback server answering each accepted connection with the next of + /// `responses`, returning every request as its head and body. + async fn scripted(responses: Vec) -> (u16, tokio::task::JoinHandle>) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let handle = tokio::spawn(async move { + let mut seen = Vec::new(); + for response in responses { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let (head, body) = loop { + let mut buffer = [0u8; 4096]; + let read = socket.read(&mut buffer).await.unwrap(); + assert!(read > 0, "request ended before its body"); + request.extend_from_slice(&buffer[..read]); + let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else { continue }; + let head = String::from_utf8_lossy(&request[..end]).into_owned(); + let length: usize = head + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap()) + }) + .unwrap_or(0); + if request.len() >= end + 4 + length { + break (head, String::from_utf8_lossy(&request[end + 4..end + 4 + length]).into_owned()); + } + }; + seen.push((head, body)); + socket.write_all(response.as_bytes()).await.unwrap(); + } + seen + }); + (port, handle) + } + + fn response(status_line: &str, headers: &str, body: &str) -> String { + format!("HTTP/1.1 {status_line}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()) + } + #[tokio::test] async fn sends_exact_environment_numbers_to_a_local_server() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -341,6 +467,7 @@ mod tests { assert_eq!(r.status_text, "Created"); assert_eq!(r.body.as_deref(), Some("{\"ok\":true}")); assert!(r.headers.iter().any(|(k, v)| k == "x-a" && v == "b")); + assert!(r.redirects.is_empty()); assert!(r.total_ms >= r.ttfb_ms); } @@ -369,4 +496,150 @@ mod tests { let err = execute(&req, &cancel).await.unwrap_err(); assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled); } + + #[tokio::test] + async fn post_keeps_method_and_body_on_301_302_307_308() { + for status_line in ["301 Moved Permanently", "302 Found", "307 Temporary Redirect", "308 Permanent Redirect"] { + let status: u16 = status_line[..3].parse().unwrap(); + let (port, server) = + scripted(vec![response(status_line, "Location: /landing\r\n", ""), response("200 OK", "", "ok")]).await; + let req = PreparedRequest { + name: None, + method: "POST".into(), + url: format!("http://127.0.0.1:{port}/submit"), + headers: vec![("Content-Type".into(), "application/json".into())], + body: Some("{\"a\":1}".into()), + }; + let r = execute(&req, &CancellationToken::new()).await.unwrap(); + let seen = server.await.unwrap(); + let (head, body) = &seen[1]; + assert_eq!(head.lines().next().unwrap(), "POST /landing HTTP/1.1", "{status_line}"); + assert!(head.to_ascii_lowercase().contains("content-type: application/json"), "{head}"); + assert_eq!(body, "{\"a\":1}", "{status_line}"); + assert_eq!(r.status, 200, "{status_line}"); + assert_eq!(r.body.as_deref(), Some("ok"), "{status_line}"); + assert_eq!( + r.redirects, + vec![RedirectHop { + status, + status_text: status_line[4..].to_owned(), + location: format!("http://127.0.0.1:{port}/landing"), + }], + "{status_line}" + ); + } + } + + #[tokio::test] + async fn see_other_303_resends_as_get_without_the_body() { + let (port, server) = + scripted(vec![response("303 See Other", "Location: /after\r\n", ""), response("200 OK", "", "done")]).await; + let req = PreparedRequest { + name: None, + method: "POST".into(), + url: format!("http://127.0.0.1:{port}/submit"), + headers: vec![], + body: Some("{\"a\":1}".into()), + }; + let r = execute(&req, &CancellationToken::new()).await.unwrap(); + let seen = server.await.unwrap(); + assert_eq!(seen[1].0.lines().next().unwrap(), "GET /after HTTP/1.1"); + assert_eq!(seen[1].1, ""); + assert_eq!(r.status, 200); + assert_eq!(r.body.as_deref(), Some("done")); + assert_eq!(r.redirects[0].status, 303); + } + + #[tokio::test] + async fn same_host_redirect_keeps_authorization() { + let (port, server) = scripted(vec![ + response("301 Moved Permanently", "Location: /landing\r\n", ""), + response("200 OK", "", "ok"), + ]) + .await; + let req = PreparedRequest { + name: None, + method: "GET".into(), + url: format!("http://127.0.0.1:{port}/start"), + headers: vec![("Authorization".into(), "Bearer secret".into())], + body: None, + }; + execute(&req, &CancellationToken::new()).await.unwrap(); + let seen = server.await.unwrap(); + assert!(seen[1].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen[1].0); + } + + #[tokio::test] + async fn cross_host_redirect_keeps_the_method_but_drops_authorization() { + let (port_b, server_b) = scripted(vec![response("200 OK", "", "moved")]).await; + let (port_a, server_a) = scripted(vec![response( + "301 Moved Permanently", + &format!("Location: http://127.0.0.1:{port_b}/x\r\n"), + "", + )]) + .await; + let req = PreparedRequest { + name: None, + method: "POST".into(), + url: format!("http://localhost:{port_a}/start"), + headers: vec![("Authorization".into(), "Bearer secret".into())], + body: Some("{\"a\":1}".into()), + }; + let r = execute(&req, &CancellationToken::new()).await.unwrap(); + let seen_a = server_a.await.unwrap(); + let seen_b = server_b.await.unwrap(); + assert!(seen_a[0].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen_a[0].0); + assert_eq!(seen_b[0].0.lines().next().unwrap(), "POST /x HTTP/1.1"); + assert!(!seen_b[0].0.to_ascii_lowercase().contains("authorization"), "{}", seen_b[0].0); + assert_eq!(seen_b[0].1, "{\"a\":1}"); + assert_eq!(r.status, 200); + assert_eq!(r.body.as_deref(), Some("moved")); + assert_eq!(r.redirects.len(), 1); + } + + #[tokio::test] + async fn redirects_beyond_the_limit_return_the_last_redirect_response() { + let responses = vec![response("301 Moved Permanently", "Location: /loop\r\n", ""); MAX_REDIRECTS + 1]; + let (port, server) = scripted(responses).await; + let req = PreparedRequest { + name: None, + method: "GET".into(), + url: format!("http://127.0.0.1:{port}/start"), + headers: vec![], + body: None, + }; + let r = execute(&req, &CancellationToken::new()).await.unwrap(); + let seen = server.await.unwrap(); + assert_eq!(r.status, 301); + assert_eq!(r.status_text, "Moved Permanently"); + assert_eq!(r.redirects.len(), MAX_REDIRECTS); + assert_eq!(seen.len(), MAX_REDIRECTS + 1); + } + + #[tokio::test] + async fn redirect_chain_is_recorded_across_hops() { + let (port, server) = scripted(vec![ + response("302 Found", "Location: /b\r\n", ""), + response("302 Found", "Location: /c\r\n", ""), + response("200 OK", "", "end"), + ]) + .await; + let req = PreparedRequest { + name: None, + method: "GET".into(), + url: format!("http://127.0.0.1:{port}/a"), + headers: vec![], + body: None, + }; + let r = execute(&req, &CancellationToken::new()).await.unwrap(); + let seen = server.await.unwrap(); + assert_eq!(r.status, 200); + assert_eq!(r.body.as_deref(), Some("end")); + assert_eq!(r.redirects.len(), 2); + assert_eq!(r.redirects[0].status, 302); + assert_eq!(r.redirects[0].location, format!("http://127.0.0.1:{port}/b")); + assert_eq!(r.redirects[1].status, 302); + assert_eq!(r.redirects[1].location, format!("http://127.0.0.1:{port}/c")); + assert_eq!(seen[2].0.lines().next().unwrap(), "GET /c HTTP/1.1"); + } } diff --git a/docs/en/guide/http-client.mdx b/docs/en/guide/http-client.mdx index 0b43bf776..e4f7e2410 100644 --- a/docs/en/guide/http-client.mdx +++ b/docs/en/guide/http-client.mdx @@ -111,7 +111,7 @@ The toolbar has **Stop Request**, **Reload History** and **Clear History**. The - HTTP/1.1 and HTTP/2. gzip, deflate and brotli responses are decoded. - TLS certificates are verified against the system trust store. -- Redirects are followed. +- Redirects are followed (up to 50): a 303 continues as GET without the body, other redirects keep the method and body, and the hops are shown in the response. - Cookies are not kept between requests. - Connections time out after 30 seconds; there is no overall request timeout. - The proxy comes from **Settings › Appearance & Behavior › System Settings › HTTP Proxy**. diff --git a/docs/zh/guide/http-client.mdx b/docs/zh/guide/http-client.mdx index 13a97fd74..560f4e4f0 100644 --- a/docs/zh/guide/http-client.mdx +++ b/docs/zh/guide/http-client.mdx @@ -111,7 +111,7 @@ OpenIDEA 会从请求文件所在目录开始,逐级向上查找到项目根 - 支持 HTTP/1.1 和 HTTP/2,自动解码 gzip、deflate 和 brotli。 - TLS 证书按系统信任库校验。 -- 自动跟随重定向。 +- 自动跟随重定向(最多 50 次):303 之后以不带请求体的 GET 继续,其余重定向保留方法与请求体,并在响应中显示跳转链。 - 请求之间不保留 Cookie。 - 连接超时为 30 秒,没有整体请求超时。 - 代理使用 **设置 › 外观与行为 › 系统设置 › HTTP 代理** 中的配置。 diff --git a/src/bindings.ts b/src/bindings.ts index 85284a39c..08e2cd677 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -6974,6 +6974,8 @@ export type HttpResponse = { version: string, headers: ([string, string])[], contentType: string | null, + /** Followed redirects, first hop first; empty when not redirected. */ + redirects?: RedirectHop[], /** Body as text (lossy UTF-8); `None` for binary bodies. */ body: string | null, /** Size in bytes as received (after decompression). */ @@ -10317,6 +10319,13 @@ export type RecentProjectGroup = { expanded?: boolean, }; +/** One followed redirect: the response and the `Location` it pointed to. */ +export type RedirectHop = { + status: number, + statusText: string, + location: string, +}; + export type RefactoringProblem = { severity: ProblemSeverity, message: string, diff --git a/src/features/http-client/HttpClient.module.css b/src/features/http-client/HttpClient.module.css index df66a70e5..8a4e813c6 100644 --- a/src/features/http-client/HttpClient.module.css +++ b/src/features/http-client/HttpClient.module.css @@ -132,6 +132,21 @@ font-size: var(--fs-small); text-align: right; } +.redirects { + display: flex; + flex-direction: column; + gap: 2px; + padding: 2px 8px; + border-bottom: 1px solid var(--border); + font-family: var(--font-mono); + font-size: var(--fs-small); + color: var(--fg-secondary); +} +.redirectHop { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} .tabBody { flex: 1; min-height: 0; diff --git a/src/features/http-client/HttpClientView.tsx b/src/features/http-client/HttpClientView.tsx index bd3d6e1dc..7e811e46b 100644 --- a/src/features/http-client/HttpClientView.tsx +++ b/src/features/http-client/HttpClientView.tsx @@ -127,6 +127,16 @@ function ExchangeView({ ex }: { ex: HttpExchange }) { {ex.request.method} {ex.request.url}
+ {r != null && (r.redirects?.length ?? 0) > 0 && ( +
+ {r.redirects?.map((hop, i) => ( + // A redirect loop repeats locations: the hop's position is its identity. +
+ {hop.status} {hop.statusText} → {hop.location} +
+ ))} +
+ )} Date: Fri, 20 Nov 2026 00:31:29 +0700 Subject: [PATCH 07/15] feat(run): Sort Alphabetically / Sort by Duration in the test results toolbar (#4576) The test results toolbar gets Sorting Options with Sort Alphabetically (by name at every level, ignoring case, numbers by value) and Sort by Duration (slowest first at every level, a suite by its total, untimed last; disabled and not applied while the run is in progress). The two replace each other, run after the filters and are kept with Show Passed / Show Ignored. Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com> --- src/features/run/TestTreeView.test.tsx | 112 ++++++++++++++++++ src/features/run/TestTreeView.tsx | 64 +++++++++- src/platform/locales/text/en.json | 4 +- src/platform/locales/text/zh.json | 4 +- .../runConfigurations/sortByDuration.svg | 7 ++ .../runConfigurations/sortByDuration_dark.svg | 7 ++ src/ui/icons.tsx | 1 + 7 files changed, 191 insertions(+), 8 deletions(-) create mode 100644 src/ui/expui/runConfigurations/sortByDuration.svg create mode 100644 src/ui/expui/runConfigurations/sortByDuration_dark.svg diff --git a/src/features/run/TestTreeView.test.tsx b/src/features/run/TestTreeView.test.tsx index da928cdaf..be22eeef8 100644 --- a/src/features/run/TestTreeView.test.tsx +++ b/src/features/run/TestTreeView.test.tsx @@ -332,3 +332,115 @@ describe("Export Test Results", () => { expect(testTree.exportResults).not.toBeNull(); }); }); + +describe("Sorting Options", () => { + beforeEach(() => localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true }))); + afterEach(() => localStorage.clear()); + + /** Run order: beta (item10, Item2, item1), Alpha (zeta); item1 reported no duration. */ + function timed() { + const r = new TestResults(); + r.apply([ + { type: "result", path: ["beta", "item10()"], status: "passed", durationMs: 5 }, + { type: "result", path: ["beta", "Item2()"], status: "passed", durationMs: 30 }, + { type: "result", path: ["beta", "item1()"], status: "failed" }, + { type: "result", path: ["Alpha", "zeta()"], status: "passed", durationMs: 100 }, + ]); + r.finish(1); + return r; + } + const view = (results: TestResults, running = false) => ( + {}} running={running} /> + ); + const rows = () => screen.getAllByRole("treeitem").map((el) => el.textContent!.replace(/[\d.]+ m?s$/, "")); + const option = (name: string) => { + fireEvent.click(screen.getByRole("button", { name: "Sorting Options" })); + return screen.getByRole("menuitemcheckbox", { name }); + }; + + it("keeps the run order until a sort is chosen", () => { + render(view(timed())); + expect(rows()).toEqual(["beta", "item10()", "Item2()", "item1()", "Alpha", "zeta()"]); + expect(screen.getByRole("button", { name: "Sorting Options" })).toHaveAttribute("aria-pressed", "false"); + }); + + it("Sort Alphabetically orders suites and tests by name, ignoring case and comparing numbers, and is remembered", () => { + const { unmount } = render(view(timed())); + fireEvent.click(option("Sort Alphabetically")); + expect(rows()).toEqual(["Alpha", "zeta()", "beta", "item1()", "Item2()", "item10()"]); + expect(screen.getByRole("button", { name: "Sorting Options" })).toHaveAttribute("aria-pressed", "true"); + unmount(); + render(view(timed())); + expect(rows()).toEqual(["Alpha", "zeta()", "beta", "item1()", "Item2()", "item10()"]); + fireEvent.click(option("Sort Alphabetically")); + expect(rows()).toEqual(["beta", "item10()", "Item2()", "item1()", "Alpha", "zeta()"]); + }); + + it("Sort by Duration puts the slowest first at each level, tests without a duration last", () => { + render(view(timed())); + fireEvent.click(option("Sort by Duration")); + expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]); + }); + + it("the two sorts replace each other, as in IDEA", () => { + render(view(timed())); + fireEvent.click(option("Sort by Duration")); + expect(option("Sort by Duration")).toHaveAttribute("aria-checked", "true"); + fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Sort Alphabetically" })); + expect(option("Sort Alphabetically")).toHaveAttribute("aria-checked", "true"); + expect(screen.getByRole("menuitemcheckbox", { name: "Sort by Duration" })).toHaveAttribute("aria-checked", "false"); + fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Sort by Duration" })); + expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]); + expect(option("Sort Alphabetically")).toHaveAttribute("aria-checked", "false"); + }); + + it("a saved pair of sorts loads as Sort by Duration alone", () => { + localStorage.setItem( + "openidea.run.testFilters", + JSON.stringify({ showPassed: true, sortAlphabetically: true, sortByDuration: true }), + ); + render(view(timed())); + expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]); + expect(option("Sort Alphabetically")).toHaveAttribute("aria-checked", "false"); + }); + + it("the button opens and closes the menu", () => { + render(view(timed())); + const button = screen.getByRole("button", { name: "Sorting Options" }); + expect(button).toHaveAttribute("aria-haspopup", "menu"); + fireEvent.click(button); + expect(button).toHaveAttribute("aria-expanded", "true"); + fireEvent.click(button); + expect(button).toHaveAttribute("aria-expanded", "false"); + expect(screen.queryByRole("menuitemcheckbox", { name: "Sort by Duration" })).toBeNull(); + }); + + it("Sort by Duration waits for the run to finish", () => { + localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true, sortByDuration: true })); + const { rerender } = render(view(timed(), true)); + expect(rows()).toEqual(["beta", "item10()", "Item2()", "item1()", "Alpha", "zeta()"]); + expect(option("Sort by Duration")).toHaveAttribute("aria-disabled", "true"); + fireEvent.keyDown(document.activeElement!, { key: "Escape" }); + rerender(view(timed(), false)); + expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]); + }); + + it("Previous / Next Failed Test follow the sorted order", () => { + const r = new TestResults(); + r.apply([ + { type: "result", path: ["s", "b()"], status: "failed" }, + { type: "result", path: ["s", "a()"], status: "failed" }, + ]); + r.finish(1); + function Selecting() { + const [selected, setSelected] = useState(null); + return ( + + ); + } + render(); + fireEvent.click(option("Sort Alphabetically")); + act(() => void occurrenceNavigator("run")!.go(1, false)); + expect(screen.getByRole("treeitem", { selected: true }).textContent).toBe("a()"); + }); +}); diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx index d8674964d..3f3b221d0 100644 --- a/src/features/run/TestTreeView.tsx +++ b/src/features/run/TestTreeView.tsx @@ -5,6 +5,7 @@ import { findOccurrence, Icon, IconButton, + Menu, showContextMenu, useContextMenuStore, Spinner, @@ -21,21 +22,28 @@ import { ExportTestResultsDialog } from "./ExportTestResultsDialog"; import styles from "./Run.module.css"; import { tx } from "@/platform/i18n"; -/** Test tree filters, kept across runs and restarts (IDEA hides passed tests by default). */ +/** Test tree filters and sorting, kept across runs and restarts (IDEA hides passed tests by default). */ const FILTERS_KEY = "openidea.run.testFilters"; interface TestFilters { showPassed: boolean; showIgnored: boolean; + sortAlphabetically: boolean; + sortByDuration: boolean; } export function loadTestFilters(): TestFilters { try { const raw = globalThis.localStorage?.getItem(FILTERS_KEY); const v = raw ? (JSON.parse(raw) as Partial) : {}; - return { showPassed: v.showPassed === true, showIgnored: v.showIgnored !== false }; + return { + showPassed: v.showPassed === true, + showIgnored: v.showIgnored !== false, + sortAlphabetically: v.sortAlphabetically === true && v.sortByDuration !== true, + sortByDuration: v.sortByDuration === true, + }; } catch { - return { showPassed: false, showIgnored: true }; + return { showPassed: false, showIgnored: true, sortAlphabetically: false, sortByDuration: false }; } } @@ -106,6 +114,17 @@ function filterTree(nodes: readonly TestNode[], keep: (n: TestNode) => boolean): return out; } +/** IDEA's test tree sorts: by name (ignoring case, numbers by value), or slowest first with untimed nodes last. */ +const names = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }); +const byName = (a: TestNode, b: TestNode) => names.compare(a.name, b.name); + +function sortTree(nodes: readonly TestNode[], byDuration: boolean): TestNode[] { + const sorted = nodes.map((n) => (n.children.length ? { ...n, children: sortTree(n.children, byDuration) } : n)); + if (!byDuration) return sorted.sort(byName); + const duration = new Map(sorted.map((n) => [n, nodeDuration(n) ?? -1])); + return sorted.sort((a, b) => duration.get(b)! - duration.get(a)!); +} + export interface TestTreeViewProps { results: TestResults; version: number; @@ -132,13 +151,18 @@ export function TestTreeView({ canRunTests, }: TestTreeViewProps) { const [filters, setFilters] = useState(loadTestFilters); - const { showPassed, showIgnored } = filters; + const { showPassed, showIgnored, sortAlphabetically, sortByDuration } = filters; const toggle = (key: keyof TestFilters) => setFilters((f) => { const next = { ...f, [key]: !f[key] }; + // The sorts replace each other, as in IDEA. + if (key === "sortAlphabetically" && next.sortAlphabetically) next.sortByDuration = false; + if (key === "sortByDuration" && next.sortByDuration) next.sortAlphabetically = false; saveTestFilters(next); return next; }); + const sortButton = useRef(null); + const [sortMenu, setSortMenu] = useState(false); const [expanded, setExpanded] = useState | null>(null); const [exporting, setExporting] = useState(false); const [selection, setSelection] = useState>(new Set()); @@ -203,10 +227,13 @@ export function TestTreeView({ }; const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps + // Like IDEA, Sort by Duration applies once the run has finished, so rows don't jump while tests report. + const byDuration = sortByDuration && !running; const roots = useMemo(() => { const keep = (n: TestNode) => (showPassed || n.own !== "passed") && (showIgnored || n.own !== "skipped"); - return showPassed && showIgnored ? [...results.roots] : filterTree(results.roots, keep); - }, [results, version, showPassed, showIgnored]); // eslint-disable-line react-hooks/exhaustive-deps + const shown = showPassed && showIgnored ? [...results.roots] : filterTree(results.roots, keep); + return byDuration || sortAlphabetically ? sortTree(shown, byDuration) : shown; + }, [results, version, showPassed, showIgnored, sortAlphabetically, byDuration]); // eslint-disable-line react-hooks/exhaustive-deps // Expand failed suites by default (IDEA reveals failures); the user's toggles win afterwards. const effectiveExpanded = useMemo(() => { @@ -280,6 +307,31 @@ export function TestTreeView({ pressed={showIgnored} onClick={() => toggle("showIgnored")} /> + setSortMenu((v) => !v)} + /> + toggle("sortAlphabetically") }, + { + label: "Sort by Duration", + checked: sortByDuration, + disabled: running, + run: () => toggle("sortByDuration"), + }, + ]} + onClose={() => setSortMenu(false)} + /> + + + + + + diff --git a/src/ui/expui/runConfigurations/sortByDuration_dark.svg b/src/ui/expui/runConfigurations/sortByDuration_dark.svg new file mode 100644 index 000000000..5d7836fc4 --- /dev/null +++ b/src/ui/expui/runConfigurations/sortByDuration_dark.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index ee69d1efd..1a202869b 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -448,6 +448,7 @@ const ICONS = { "test-pending": "run/testNotRunYet", "test-show-passed": "run/showPassed", "test-show-ignored": "run/showIgnored", + "test-sort": "runConfigurations/sortByDuration", debug: "run/debug", "run-coverage": "run/runWithCoverage", profile: "run/profile", From b9256a7260a12459eb3f29698ffa2582ee71c847 Mon Sep 17 00:00:00 2001 From: Gabriel Gondim <52431033+GGVidal@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:28:50 -0300 Subject: [PATCH 08/15] fix(deployment): use Commit selection for upload shortcuts (#4585) Deployment actions run by shortcut, Find Action or the Tools menu used the Project view's selection (else the editor's file) even in the Commit tool window, where only the context menu passed the selected changes. The changes tree now provides its selection while Commit or Git > Local Changes is focused, without deleted files, and Deployment takes it after a menu's paths. Co-authored-by: GGVidal <52431033+GGVidal@users.noreply.github.com> --- src/features/deployment/actions.test.tsx | 1 + src/features/deployment/actions.tsx | 12 +++++++--- src/features/deployment/model.test.ts | 26 +++++++++++++++++++++ src/features/deployment/model.ts | 29 ++++++++++++++++-------- src/features/vcs/CommitView.tsx | 4 ++-- src/features/vcs/index.ts | 22 +++++++++++++++--- src/features/vcs/store.ts | 3 +++ src/platform/locales/text/en.json | 2 ++ src/platform/locales/text/es.json | 4 ++-- src/platform/locales/text/fr.json | 4 ++-- src/platform/locales/text/ko.json | 4 ++-- src/platform/locales/text/pl.json | 4 ++-- src/platform/locales/text/pt.json | 4 ++-- src/platform/locales/text/zh.json | 3 ++- src/workbench/contributions.ts | 14 ++++++++++++ 15 files changed, 108 insertions(+), 28 deletions(-) diff --git a/src/features/deployment/actions.test.tsx b/src/features/deployment/actions.test.tsx index ae39b5a8b..a8be124ee 100644 --- a/src/features/deployment/actions.test.tsx +++ b/src/features/deployment/actions.test.tsx @@ -46,6 +46,7 @@ vi.mock("@/platform/workflowSettings", () => ({ vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify }), projectViewSelection: () => [], + changesViewSelection: () => [], toolWindowService: vi.fn(), })); vi.mock("@/workbench/inputDialogs", () => ({ chooseItem: mocks.choose })); diff --git a/src/features/deployment/actions.tsx b/src/features/deployment/actions.tsx index 227d90426..f061794f9 100644 --- a/src/features/deployment/actions.tsx +++ b/src/features/deployment/actions.tsx @@ -22,7 +22,12 @@ import { type DeploymentServerValid, } from "@/platform/remoteSettings"; import { workflowSettings } from "@/platform/workflowSettings"; -import { notifications, projectViewSelection, toolWindowService } from "@/workbench/contributions"; +import { + changesViewSelection, + notifications, + projectViewSelection, + toolWindowService, +} from "@/workbench/contributions"; import { chooseItem } from "@/workbench/inputDialogs"; import { confirm } from "@/workbench/messages"; import { defaultGroup, initialSyncChoices, resolveServer, serverLabel, summarizeReport, targetPaths } from "./model"; @@ -37,12 +42,13 @@ const errorText = (e: unknown) => txTemplate(e instanceof Error ? e.message : St const projectRoot = () => useProject.getState().project?.root ?? null; const deployment = () => workflowSettings().deployment; -/** The files an action works on (menu argument, project view selection or the editor's file). */ +/** The files an action works on (menu, Commit selection, Project view or the editor). */ export function actionTargets(arg: unknown): string[] { const editorPath = getContext().editorPath; return targetPaths(arg, { part: useDeployment.getState().part, selection: projectViewSelection(), + changesSelection: changesViewSelection(), editorPath: typeof editorPath === "string" ? editorPath : null, projectRoot: projectRoot(), }); @@ -61,7 +67,7 @@ function notifyNoServers() { function notifyNoTargets() { notifications().notify({ level: "info", - title: "Select files in the Project view or open a file in the editor", + title: "Select files in the Project view, Commit tool window, or open a file in the editor", group: GROUP, key: "deployment.noTarget", }); diff --git a/src/features/deployment/model.test.ts b/src/features/deployment/model.test.ts index dd542a930..bfe573b5d 100644 --- a/src/features/deployment/model.test.ts +++ b/src/features/deployment/model.test.ts @@ -45,6 +45,32 @@ describe("targetPaths", () => { expect(targetPaths(undefined, { ...ctx, part: "editor", selection: [`${ROOT}/src`] })).toEqual([]); }); + it("prefers the Commit / Local Changes selection over Project view and the editor", () => { + const changes = [`${ROOT}/a.php`, `${ROOT}/b.php`]; + expect( + targetPaths(undefined, { + ...ctx, + part: "project", + selection: [`${ROOT}/only-project`], + editorPath: `${ROOT}/editor.php`, + changesSelection: changes, + }), + ).toEqual(changes); + // Menu arg still wins. + expect( + targetPaths({ paths: [`${ROOT}/menu.php`] }, { ...ctx, changesSelection: changes, part: "project" }), + ).toEqual([`${ROOT}/menu.php`]); + // Empty changes selection falls through to Project / editor. + expect( + targetPaths(undefined, { + ...ctx, + part: "project", + selection: [`${ROOT}/proj`], + changesSelection: [], + }), + ).toEqual([`${ROOT}/proj`]); + }); + it("drops paths outside the project and paths inside selected folders", () => { expect(targetPaths([`${ROOT}/src`, `${ROOT}/src/a.php`, "/elsewhere/b", `${ROOT}/srcx`], ctx)).toEqual([ `${ROOT}/src`, diff --git a/src/features/deployment/model.ts b/src/features/deployment/model.ts index ee31ba4b9..636d28770 100644 --- a/src/features/deployment/model.ts +++ b/src/features/deployment/model.ts @@ -16,24 +16,35 @@ export function pathsFromArg(arg: unknown): string[] | null { } /** - * Files an action works on: the paths passed by a menu, else the project view + * Files an action works on: the paths passed by a menu, else the Commit / Local + * Changes selection while that window is focused, else the project view * selection when it had focus last, else the active editor's file. Paths * outside the project are dropped. */ export function targetPaths( arg: unknown, - ctx: { part: FocusedPart; selection: readonly string[]; editorPath: string | null; projectRoot: string | null }, + ctx: { + part: FocusedPart; + selection: readonly string[]; + /** Absolute paths from the Commit/Local Changes tree while it has focus. */ + changesSelection?: readonly string[]; + editorPath: string | null; + projectRoot: string | null; + }, ): string[] { const passed = pathsFromArg(arg); + const changes = ctx.changesSelection?.length ? [...ctx.changesSelection] : null; const picked = passed ? passed - : ctx.part === "project" && ctx.selection.length - ? [...ctx.selection] - : ctx.editorPath - ? [ctx.editorPath] - : ctx.selection.length && ctx.part !== "editor" - ? [...ctx.selection] - : []; + : changes + ? changes + : ctx.part === "project" && ctx.selection.length + ? [...ctx.selection] + : ctx.editorPath + ? [ctx.editorPath] + : ctx.selection.length && ctx.part !== "editor" + ? [...ctx.selection] + : []; const root = ctx.projectRoot; if (!root) return []; const inside = picked.filter((p) => p === root || p.startsWith(`${root}/`)); diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx index c8c6f989a..89e56df56 100644 --- a/src/features/vcs/CommitView.tsx +++ b/src/features/vcs/CommitView.tsx @@ -109,7 +109,7 @@ import { showChangesDiff, toLogChanges, type LogChange } from "./logChanges"; import { OperationBanner } from "./operations"; import { runOp } from "./ops"; import { ShelfPanel, loadShelves, useShelf } from "./shelf"; -import { refreshNow, repoName, selectRepo, useVcs } from "./store"; +import { existsOnDisk, refreshNow, repoName, selectRepo, useVcs } from "./store"; import { saveVcsSetting } from "./settingsUi"; import styles from "./CommitView.module.css"; @@ -302,7 +302,7 @@ export function listMenu(id: string, active: boolean, files: readonly FileStatus /** Paths Delete… applies to: only when every selected file is unversioned (versioned ones are rolled back). */ /** The selected files that still exist in the working tree (Delete… removes them from disk). */ /** Whether the change leaves the file in the working tree. */ -const onDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged); +const onDisk = existsOnDisk; export function deletableFiles(nodes: ChangeNode[]): string[] { const files = filesOf(nodes); diff --git a/src/features/vcs/index.ts b/src/features/vcs/index.ts index be23a90a8..a756ef441 100644 --- a/src/features/vcs/index.ts +++ b/src/features/vcs/index.ts @@ -7,6 +7,7 @@ import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowS import { editorsFor, registerEditorContribution } from "@/editor/api"; import { notifications, + provideChangesViewSelection, registerEditorKind, registerMenuGroup, registerOverlay, @@ -16,7 +17,7 @@ import { import { executeAction, registerActions } from "@/platform/actions"; import { getContext } from "@/platform/context"; import { lazyComponent } from "@/ui"; -import { registerVcsActions } from "./actions"; +import { commitWindowFocused, registerVcsActions } from "./actions"; import { installChangelists } from "./changelists"; import { registerHistoryActions, trackOperationContext } from "./historyActions"; import { registerLogPaneActions } from "./logPaneActions"; @@ -39,7 +40,7 @@ import { SELECTION_HISTORY_KIND, type SelectionHistoryData } from "./selectionHi import { registerLocalHistoryActions } from "./localHistoryActions"; import { MERGE_KIND, type MergeData } from "./mergeKind"; import { registerMergeActions } from "./mergeActions"; -import { baseName } from "./model"; +import { baseName, stripSlash } from "./model"; import { installCommitChecks, installDiagnosticsTracking } from "./commitChecks"; import { installPreparedMessage, useCommit } from "./commitStore"; import { installDraftRevision, provideCommit } from "./commitSelection"; @@ -49,7 +50,7 @@ import { MergeRebaseWidget } from "./MergeRebaseWidget"; import { installFileConfirmations } from "./confirmations"; import { installIncomingCheck } from "./incoming"; import { closeLogTab, installGitLog, selectGitTab, useGitLog } from "./logStore"; -import { installVcsStore, onConflictsAppeared, onConflictsCleared, useVcs } from "./store"; +import { existsOnDisk, installVcsStore, onConflictsAppeared, onConflictsCleared, useVcs } from "./store"; import { installRootSync } from "./rootSync"; import { tx } from "@/platform/i18n"; import { openOnRemoteActions, registerOpenOnRemote } from "./openOnRemote"; @@ -203,6 +204,21 @@ export function activate(): () => void { installPreparedMessage(), installDraftRevision(), provideCommit(), + // Deployment shortcuts (and similar) use this while Commit / Local Changes is focused. + provideChangesViewSelection(() => { + if (!commitWindowFocused()) return []; + // As the context menu: deleted files have nothing to upload. + const deleted = new Set( + useVcs + .getState() + .status.filter((f) => !existsOnDisk(f)) + .map((f) => f.path), + ); + return useCommit + .getState() + .selection.filter((p) => !deleted.has(p)) + .map(stripSlash); + }), installIncomingCheck(), installFileConfirmations(), installDiffEditorHost(), diff --git a/src/features/vcs/store.ts b/src/features/vcs/store.ts index 8dc5b76b5..584f8a891 100644 --- a/src/features/vcs/store.ts +++ b/src/features/vcs/store.ts @@ -145,6 +145,9 @@ export async function focusRepo(root: string): Promise { if (!useVcs.getState().branchesLoaded) await loadBranches(); } +/** Whether the changed file still exists in the working tree (not deleted there). */ +export const existsOnDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged); + export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState().status): FileStatus[] { return status.filter((f) => effectiveKind(f) === "conflicted"); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index b730e5c87..45ced14ee 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -855,6 +855,8 @@ "Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.": "Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.", "devcontainer up exited with {status}": "devcontainer up exited with {status}", "Select an item to view details": "Select an item to view details", + "Select files in the Project view, Commit tool window, or open a file in the editor": "Select files in the Project view, Commit tool window, or open a file in the editor", + "Nothing to show": "Nothing to show", "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory", "Invalid log stream configuration": "Invalid log stream configuration", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index bce9a51e2..9de9fc00e 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -4363,7 +4363,6 @@ "Edit the deployment servers and options": "Editar los servidores y opciones de despliegue", "Configuration…": "Configuración…", "No deployment server configured": "No hay ningún servidor de despliegue configurado", - "Select files in the Project view or open a file in the editor": "Seleccione archivos en la vista Proyecto o abra un archivo en el editor", "Upload to": "Subir a", "Download from": "Descargar de", "Sync with Deployed to": "Sincronizar con lo desplegado en", @@ -6137,5 +6136,6 @@ "Plugin update available": "Actualización de plugin disponible", "{length} plugin updates available": "{length} actualizaciones de plugins disponibles", "Updated {updated} plugins": "Se actualizaron {updated} plugins", - "This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Esta versión está firmada con una clave diferente a la instalada y la clave anterior del editor no la avala. Continúe solo si sabe que el editor cambió de clave." + "This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Esta versión está firmada con una clave diferente a la instalada y la clave anterior del editor no la avala. Continúe solo si sabe que el editor cambió de clave.", + "Select files in the Project view, Commit tool window, or open a file in the editor": "Seleccione archivos en la vista Proyecto, la ventana de Confirmación, o abra un archivo en el editor" } diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index e8ee02bfb..21153c4d1 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -4219,7 +4219,6 @@ "Edit the deployment servers and options": "Modifier les serveurs et les options de déploiement", "Configuration…": "Configuration…", "No deployment server configured": "Aucun serveur de déploiement configuré", - "Select files in the Project view or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet ou ouvrez un fichier dans l'éditeur", "Upload to": "Envoyer vers", "Download from": "Télécharger depuis", "Sync with Deployed to": "Synchroniser avec la version déployée sur", @@ -5765,5 +5764,6 @@ "Keep abstract": "Garder abstrait", "Methods pulled up to an interface are declared abstract there.": "Les méthodes remontées dans une interface y sont déclarées abstraites.", "The file changed; open the dialog again": "Le fichier a changé ; rouvrez la boîte de dialogue", - "Replace preview": "Aperçu du remplacement" + "Replace preview": "Aperçu du remplacement", + "Select files in the Project view, Commit tool window, or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet, la fenêtre Commit, ou ouvrez un fichier dans l'éditeur" } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 386e28941..97675b7e8 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -4425,7 +4425,6 @@ "Edit the deployment servers and options": "배포 서버 및 옵션 편집", "Configuration…": "구성…", "No deployment server configured": "구성된 배포 서버가 없습니다", - "Select files in the Project view or open a file in the editor": "프로젝트 뷰에서 파일을 선택하거나 편집기에서 파일을 여세요", "Upload to": "업로드 대상", "Download from": "다운로드 위치", "Sync with Deployed to": "배포된 항목과 동기화", @@ -6248,5 +6247,6 @@ "Empty: where the service mounts the project.": "비워 두면 서비스가 프로젝트를 마운트하는 위치를 사용합니다.", "The project is mounted here; paths and the working directory are mapped into it.": "프로젝트가 여기에 마운트되며, 경로와 작업 디렉터리가 이 위치로 매핑됩니다.", "Published ports": "게시된 포트", - "Run as the image's user, not the project folder's owner (Linux)": "프로젝트 폴더 소유자가 아닌 이미지의 사용자로 실행(Linux)" + "Run as the image's user, not the project folder's owner (Linux)": "프로젝트 폴더 소유자가 아닌 이미지의 사용자로 실행(Linux)", + "Select files in the Project view, Commit tool window, or open a file in the editor": "프로젝트 뷰나 커밋 도구 창에서 파일을 선택하거나 편집기에서 파일을 여세요" } diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 86239faee..761694715 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -4316,7 +4316,6 @@ "Edit the deployment servers and options": "Edytuj serwery wdrażania i opcje", "Configuration…": "Konfiguracja…", "No deployment server configured": "Brak skonfigurowanego serwera wdrażania", - "Select files in the Project view or open a file in the editor": "Wybierz pliki w widoku Projektu lub otwórz plik w edytorze", "Upload to": "Prześlij do", "Download from": "Pobierz z", "Sync with Deployed to": "Synchronizuj z wdrożeniem na", @@ -5943,5 +5942,6 @@ "Back to Changed Files": "Powrót do zmienionych plików", "Default (the module's JDK)": "Domyślnie (zestaw JDK modułu)", "Use classpath of module": "Użyj ścieżki klas modułu", - "Find by main class": "Znajdź według klasy głównej" + "Find by main class": "Znajdź według klasy głównej", + "Select files in the Project view, Commit tool window, or open a file in the editor": "Wybierz pliki w widoku Projektu, oknie Commit lub otwórz plik w edytorze" } diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 514acfa57..2046f7789 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -4329,7 +4329,6 @@ "Edit the deployment servers and options": "Editar os servidores e opções de implantação", "Configuration…": "Configuração…", "No deployment server configured": "Nenhum servidor de implantação configurado", - "Select files in the Project view or open a file in the editor": "Selecione arquivos na visualização do projeto ou abra um arquivo no editor", "Upload to": "Fazer upload para", "Download from": "Fazer download de", "Sync with Deployed to": "Sincronizar com implantado em", @@ -5957,5 +5956,6 @@ "Back to Changed Files": "Voltar para Arquivos alterados", "Default (the module's JDK)": "Padrão (JDK do módulo)", "Use classpath of module": "Usar classpath do módulo", - "Find by main class": "Localizar por classe principal" + "Find by main class": "Localizar por classe principal", + "Select files in the Project view, Commit tool window, or open a file in the editor": "Selecione arquivos na visualização do projeto, na janela Commit, ou abra um arquivo no editor" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 6ab004d77..7e63b5c57 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5219,7 +5219,8 @@ "Edit the deployment servers and options": "编辑部署服务器和选项", "Configuration…": "配置…", "No deployment server configured": "未配置部署服务器", - "Select files in the Project view or open a file in the editor": "请在项目视图中选择文件,或在编辑器中打开文件", + "Select files in the Project view, Commit tool window, or open a file in the editor": "请在项目视图或提交工具窗口中选择文件,或在编辑器中打开文件", + "Upload to": "上传到", "Download from": "下载自", "Sync with Deployed to": "与已部署的同步", diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index d408fd14e..e4f1a2d85 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -1464,6 +1464,20 @@ export function provideProjectViewSelection(get: () => string[]): () => void { /** Selected project view paths (absolute); empty without a project view. */ export const projectViewSelection = (): string[] => projectSelection?.() ?? []; +// Commit / Local Changes selection while that tool window has focus. Provided by +// features/vcs so Deployment (and similar) shortcuts see multi-file picks there. +let changesSelection: (() => string[]) | undefined; + +export function provideChangesViewSelection(get: () => string[]): () => void { + changesSelection = get; + return () => { + if (changesSelection === get) changesSelection = undefined; + }; +} + +/** Selected change-tree paths (absolute) while Commit/Local Changes is focused. */ +export const changesViewSelection = (): string[] => changesSelection?.() ?? []; + /** The project view node the user last selected; `dir` decides the icon and popup of the last crumb. */ export interface ProjectViewLead { path: string; From 121d7edc15c4a17c045572417608e377eef14fa5 Mon Sep 17 00:00:00 2001 From: Aditya Aggarwal Date: Fri, 20 Nov 2026 00:14:16 +0530 Subject: [PATCH 09/15] feat(spring): find Feign clients for a controller endpoint (#4584) A Spring controller endpoint gets Find Feign Clients (gutter menu, editor context menu, Find Action; Java and Kotlin): it matches the HTTP method and literal route across the trusted workspace and uses the controller module's spring.application.name to leave out clients of other services. One known match opens directly; otherwise a chooser lists the interface methods, with unresolved service names and explicit URLs marked Possible match. Co-authored-by: aditya-786 <42476079+aditya-786@users.noreply.github.com> --- docs/en/guide/http-client.mdx | 4 +- docs/zh/guide/http-client.mdx | 4 +- e2e/feignNavigation.spec.ts | 116 +++++++- src/features/http-client/index.ts | 14 +- src/features/http-client/spring/editor.ts | 30 ++- src/features/http-client/spring/feign.ts | 33 +-- .../spring/feignNavigation.test.ts | 134 +++++++++- .../http-client/spring/feignNavigation.ts | 248 ++++++++++++------ src/features/http-client/spring/routeIndex.ts | 19 +- src/platform/locales/text/en.json | 5 + src/platform/locales/text/zh.json | 5 + 11 files changed, 489 insertions(+), 123 deletions(-) diff --git a/docs/en/guide/http-client.mdx b/docs/en/guide/http-client.mdx index e4f7e2410..c9d581120 100644 --- a/docs/en/guide/http-client.mdx +++ b/docs/en/guide/http-client.mdx @@ -135,7 +135,9 @@ In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint** The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent. -This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes. +To see which Feign interfaces declare a request to a Spring endpoint, open the endpoint’s gutter menu and choose **Find Feign Clients**. You can also invoke the action from the editor menu or Find Action with the caret in the controller method. A single service match opens directly. When several clients match, the chooser shows each interface method and its source path. Clients whose service cannot be established appear below known matches as **Possible match**, even when only one is found. A client known to target another service is excluded. + +Navigation reads local source and module configuration, including unsaved editor changes. Custom source sets, composed or aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns, and runtime service discovery are outside its scope. ## Not supported diff --git a/docs/zh/guide/http-client.mdx b/docs/zh/guide/http-client.mdx index 560f4e4f0..e05e8eb5b 100644 --- a/docs/zh/guide/http-client.mdx +++ b/docs/zh/guide/http-client.mdx @@ -135,7 +135,9 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping` 内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。 -这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。 +要查看哪些 Feign 接口声明了对 Spring 端点的请求,请打开端点的装订线菜单并选择**查找 Feign 客户端**。光标位于控制器方法中时,也可以从编辑器菜单或查找操作中执行。只有一个服务匹配时会直接打开该声明。多个结果会列出各接口方法及其源码路径。无法确认目标服务的客户端排在已知匹配之后,并标为**可能匹配**,即便只有一个候选也会显示选择器。明确指向其他服务的客户端会被排除。 + +导航读取本地源码和模块配置,包括未保存的修改。暂不支持自定义源码目录、组合或别名注解、继承映射、动态映射路径、`@RequestLine`、Ant/正则路径模式和运行时服务发现。 ## 暂不支持 diff --git a/e2e/feignNavigation.spec.ts b/e2e/feignNavigation.spec.ts index 4629d2700..2c6ec5e03 100644 --- a/e2e/feignNavigation.spec.ts +++ b/e2e/feignNavigation.spec.ts @@ -2,13 +2,10 @@ import { expect, stubDesktop, test } from "./fixtures"; test.use({ video: "on" }); -test("Feign navigation selects the named service and offers ambiguous source targets", async ({ - workbench: page, -}, testInfo) => { +test.beforeEach(async ({ workbench: page }) => { await stubDesktop(page); await page.evaluate(async () => { const backend = "/src/editor/core/backend.ts"; - const contributions = "/src/workbench/contributions.ts"; const { docBackend } = await import(backend); const files: Map = docBackend().files; const root = "/dev/acme-api"; @@ -37,7 +34,9 @@ class UserController { files.set(`${root}/${service}/src/main/resources/application.properties`, `spring.application.name=${service}\n`); } window.__ipc.handlers.spring_route_sources = () => - [...files].filter(([p]) => p.endsWith("UserController.java")).map(([path, text]) => ({ path, text })); + [...files] + .filter(([path, text]) => /\.(java|kt)$/.test(path) && text.includes("Mapping")) + .map(([path, text]) => ({ path, text })); window.__ipc.handlers.fs_read_text = ({ path }) => { if (!files.has(String(path))) throw { kind: "notFound", message: "No fixture file" }; return files.get(String(path)); @@ -60,7 +59,21 @@ class UserController { hidden: false, })); window.__ipc.handlers.lsp_goto = () => []; - await (await import(contributions)).editorService().openFile(`${root}/client/src/main/java/UserClient.java`); + window.__ipc.handlers.fs_probe = ({ path }) => ({ + size: files.get(String(path))?.length ?? 0, + binary: false, + tooLarge: false, + }); + window.__ipc.handlers.find_files = () => []; + }); +}); + +test("Feign navigation selects the named service and offers ambiguous source targets", async ({ + workbench: page, +}, testInfo) => { + await page.evaluate(async () => { + const contributions = "/src/workbench/contributions.ts"; + await (await import(contributions)).editorService().openFile("/dev/acme-api/client/src/main/java/UserClient.java"); }); await expect(page.locator(".cm-content").last()).toContainText("@FeignClient"); await page.screenshot({ path: testInfo.outputPath("feign-source.png"), animations: "disabled" }); @@ -111,3 +124,94 @@ class UserController { await declarations.getByRole("option").filter({ hasText: "admin/" }).click(); await expect(page.locator(".cm-content").last()).toContainText('return "admin"'); }); + +test("a Spring endpoint lists Feign clients by module and flags unresolved services", async ({ + workbench: page, +}, testInfo) => { + await page.evaluate(async () => { + const backend = "/src/editor/core/backend.ts"; + const contributions = "/src/workbench/contributions.ts"; + const files: Map = (await import(backend)).docBackend().files; + const root = "/dev/acme-api"; + const original = `${root}/client/src/main/java/UserClient.java`; + const template = files.get(original)!; + files.delete(original); + for (const [module, type, service] of [ + ["orders", "OrderUsers", "users"], + ["admin-ui", "AdminUsers", "admin"], + ["gateway", "GatewayUsers", "${SERVICE}"], + ] as const) { + files.set( + `${root}/${module}/src/main/java/${type}.java`, + template.replace("UserClient", type).replace('"users"', `"${service}"`), + ); + } + files.set( + `${root}/billing/src/main/kotlin/BillingUsers.kt`, + `package shop +import org.springframework.cloud.openfeign.FeignClient +import org.springframework.web.bind.annotation.GetMapping + +@FeignClient("users") +interface BillingUsers { + @GetMapping("/users/{userId}") + fun find(): String +}`, + ); + await (await import(contributions)).editorService().openFile(`${root}/users/src/main/java/UserController.java`); + }); + + await page.locator('[data-icon-source="spring"][title="GET /users/{id}"]').click(); + await expect(page.getByRole("menuitem", { name: "Generate Request in HTTP Client" })).toBeVisible(); + await page.screenshot({ path: testInfo.outputPath("controller-menu.png"), animations: "disabled" }); + await page.getByRole("menuitem", { name: "Find Feign Clients" }).click({ timeout: 5_000 }); + const picker = page.getByRole("dialog", { name: "Feign Clients" }); + const rows = picker.getByRole("option"); + await expect(rows).toHaveCount(3); + await expect(rows.nth(0)).toContainText("BillingUsers.find"); + await expect(rows.nth(0)).toContainText("billing"); + await expect(rows.nth(1)).toContainText("OrderUsers.find"); + await expect(rows.nth(1)).toContainText("orders"); + await expect(rows.nth(2)).toContainText("GatewayUsers.find"); + await expect(rows.nth(2)).toContainText("Possible match"); + await page.screenshot({ path: testInfo.outputPath("feign-clients.png"), animations: "disabled" }); + await rows.nth(0).click(); + await expect(page.locator(".cm-content").last()).toContainText("interface BillingUsers"); +}); + +test("one possible client requires a choice and a changed workspace invalidates that choice", async ({ + workbench: page, +}) => { + await page.evaluate(async () => { + const backend = "/src/editor/core/backend.ts"; + const api = "/src/editor/api.ts"; + const actions = "/src/platform/actions.ts"; + const contributions = "/src/workbench/contributions.ts"; + const root = "/dev/acme-api"; + const files: Map = (await import(backend)).docBackend().files; + files.set(`${root}/users/src/main/resources/application.properties`, "spring.application.name=${SERVICE}"); + await (await import(contributions)).editorService().openFile(`${root}/users/src/main/java/UserController.java`); + const view = (await import(api)).activeEditor().view; + view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("return") } }); + await (await import(actions)).executeAction("http.findFeignClients"); + }); + const picker = page.getByRole("dialog", { name: "Feign Clients" }); + const candidate = picker.getByRole("option"); + await expect(candidate).toHaveCount(1); + await expect(candidate).toContainText("Possible match"); + await page.evaluate(async () => { + const backend = "/src/editor/core/backend.ts"; + const ipc = "/src/platform/ipc.ts"; + const path = "/dev/acme-api/users/src/main/resources/application.properties"; + (await import(backend)).docBackend().files.set(path, "spring.application.name=users"); + (await import(ipc)).emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] }); + }); + await candidate.click(); + await expect(picker).not.toBeVisible(); + await expect(page.locator(".cm-content").last()).toContainText("class UserController"); + await page.evaluate(async () => { + const actions = "/src/platform/actions.ts"; + await (await import(actions)).executeAction("http.findFeignClients"); + }); + await expect(page.locator(".cm-content").last()).toContainText("interface UserClient"); +}); diff --git a/src/features/http-client/index.ts b/src/features/http-client/index.ts index 16bad0f26..2b038705a 100644 --- a/src/features/http-client/index.ts +++ b/src/features/http-client/index.ts @@ -37,8 +37,9 @@ import { registerSpringEndpointProvider } from "./spring/routeIndex"; import { feignEditorExtension, feignMenuItems, + FIND_FEIGN_CLIENTS, GO_TO_FEIGN_ENDPOINT, - goToFeignEndpoint, + navigateFeign, registerFeignNavigation, } from "./spring/feignNavigation"; @@ -184,7 +185,16 @@ export function activate(): () => void { icon: "arrow-right", keywords: ["spring", "feign", "microservice", "endpoint"], when: SPRING_WHEN, - run: ({ arg }) => goToFeignEndpoint(arg), + run: ({ arg }) => navigateFeign("endpoint", arg), + }, + { + id: FIND_FEIGN_CLIENTS, + title: "Find Feign Clients", + category: "Navigate", + icon: "search", + keywords: ["spring", "feign", "client", "endpoint", "caller"], + when: SPRING_WHEN, + run: ({ arg }) => navigateFeign("clients", arg), }, { id: OPEN_ENDPOINT, diff --git a/src/features/http-client/spring/editor.ts b/src/features/http-client/spring/editor.ts index 7f2a63694..9b73bcf31 100644 --- a/src/features/http-client/spring/editor.ts +++ b/src/features/http-client/spring/editor.ts @@ -21,6 +21,7 @@ import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui"; import { notifications, type MenuGroupContext } from "@/workbench/contributions"; import { constantPool } from "./constants"; import { springAt, springControllers, type Controller, type Endpoint } from "./endpoints"; +import { findClientItems } from "./feignNavigation"; import { bodyLookup, findHost, renderRequest, skeleton, type SourceReader } from "./request"; import { parseSource } from "./source"; import styles from "../HttpClient.module.css"; @@ -83,17 +84,15 @@ export async function generateRequests(sourcePath: string, text: string, targets } } -function endpointItems(sourcePath: string, text: string, e: Endpoint): MenuItem[] { +function generateRequestItem(sourcePath: string, text: string, e: Endpoint): MenuItem { const generate = (path?: string) => void generateRequests(sourcePath, text, [{ endpoint: e, path }]); - return [ - e.paths.length > 1 - ? { - label: "Generate Request in HTTP Client", - icon: "file-http", - submenu: e.paths.map((p) => ({ label: `${e.httpMethod} ${p}`, verbatim: true, run: () => generate(p) })), - } - : { label: "Generate Request in HTTP Client", icon: "file-http", run: () => generate() }, - ]; + return e.paths.length > 1 + ? { + label: "Generate Request in HTTP Client", + icon: "file-http", + submenu: e.paths.map((p) => ({ label: `${e.httpMethod} ${p}`, verbatim: true, run: () => generate(p) })), + } + : { label: "Generate Request in HTTP Client", icon: "file-http", run: () => generate() }; } function controllerItems(sourcePath: string, text: string, c: Controller): MenuItem[] { @@ -120,8 +119,9 @@ export function springMenuItems(sourcePath: string, text: string, offset: number if (endpoint) items.push( endpoint.paths.length > 1 - ? endpointItems(sourcePath, text, endpoint)[0]! + ? generateRequestItem(sourcePath, text, endpoint) : { kind: "action", action: GENERATE_REQUEST, icon: "file-http" }, + ...findClientItems(sourcePath, text, endpoint.offset), ); if (controller?.endpoints.length) items.push({ kind: "action", action: GENERATE_CONTROLLER_REQUESTS, icon: "file-http" }); @@ -163,6 +163,7 @@ export async function generateAtCaret(scope: "endpoint" | "controller"): Promise interface Mark { pos: number; + offset: number; /** Endpoint key or the controller's name. */ key: string; title: string; @@ -188,6 +189,7 @@ function computeMarks(state: EditorState): Mark[] { if (c.endpoints.length) marks.push({ pos: lineStart(c.offset), + offset: c.offset, key: `class:${c.name}`, title: "Generate Requests for Controller", items: (path, text) => controllerItems(path, text, c), @@ -195,9 +197,10 @@ function computeMarks(state: EditorState): Mark[] { for (const e of c.endpoints) marks.push({ pos: lineStart(e.offset), + offset: e.offset, key: `${e.httpMethod} ${e.paths.join(",")}`, title: `${e.httpMethod} ${e.paths[0] ?? "/"}`, - items: (path, text) => endpointItems(path, text, e), + items: (path, text) => [generateRequestItem(path, text, e), ...findClientItems(path, text, e.offset)], }); } // One icon per line (the first wins). @@ -243,7 +246,8 @@ export function springEditorExtension(ctx: EditorDocContext): Extension { const found = computeMarks(this.view.state); const cur = this.view.state.field(marksField); const same = - cur.length === found.length && cur.every((m, i) => m.pos === found[i]!.pos && m.key === found[i]!.key); + cur.length === found.length && + cur.every((m, i) => m.pos === found[i]!.pos && m.offset === found[i]!.offset && m.key === found[i]!.key); if (!same) this.view.dispatch({ effects: setMarks.of(found) }); // Paths built from other classes' constants: load those classes, then mark again. if (found.length) { diff --git a/src/features/http-client/spring/feign.ts b/src/features/http-client/spring/feign.ts index dc4ec937f..17a6fd39a 100644 --- a/src/features/http-client/spring/feign.ts +++ b/src/features/http-client/spring/feign.ts @@ -1,7 +1,7 @@ /** Source-only Feign relationships. Request generation's default GET is not a * server constraint: unconstrained controller mappings accept every method. */ import { joinPaths } from "./endpoints"; -import { allClasses, parseSource, type Annotation, type Expr, type SourceFile, type Tok } from "./source"; +import { allClasses, parseSource, type Annotation, type Expr, type Method, type SourceFile, type Tok } from "./source"; const WEB = "org.springframework.web.bind.annotation"; const FEIGN = "org.springframework.cloud.openfeign.FeignClient"; @@ -19,19 +19,27 @@ export interface HttpShape { paths: string[]; methods: string[]; } -export interface FeignMethod extends HttpShape { +export interface MappedMethod extends HttpShape { name: string; + /** Whole declaration, including its annotations. */ from: number; to: number; nameFrom: number; + nameTo: number; +} +export interface FeignMethod extends MappedMethod { /** Literal URL spans, excluding quotes, for modifier-click navigation. */ links: { from: number; to: number }[]; service: string | null; } -export interface ControllerMethod extends HttpShape { - name: string; - from: number; - to: number; +function declaration(owner: string, method: Method) { + return { + name: `${owner}.${method.name}`, + from: method.start, + to: method.end, + nameFrom: method.nameStart, + nameTo: method.nameStart + method.name.length, + }; } function owned(a: Annotation, file: SourceFile, qualified: string): boolean { @@ -156,10 +164,7 @@ export function feignMethods(text: string): FeignMethod[] { verbs = methods(annotation, file); if (!urls || !verbs) continue; result.push({ - name: `${cls.name}.${method.name}`, - from: method.start, - to: method.end, - nameFrom: method.nameStart, + ...declaration(cls.name, method), paths: combine([prefix], urls.values), methods: verbs.map((v) => (v === "*" ? "GET" : v)), links: urls.links, @@ -170,10 +175,10 @@ export function feignMethods(text: string): FeignMethod[] { return result; } -export function controllerMethods(text: string, file?: SourceFile): ControllerMethod[] { +export function controllerMethods(text: string, file?: SourceFile): MappedMethod[] { if (text.length > MAX_NAVIGATION_SOURCE || !text.includes("Controller")) return []; file ??= parseSource(text); - const result: ControllerMethod[] = []; + const result: MappedMethod[] = []; for (const cls of allClasses(file)) { if ( !cls.annotations.some( @@ -199,9 +204,7 @@ export function controllerMethods(text: string, file?: SourceFile): ControllerMe verbs = methods(annotation, file); if (!own || !verbs) continue; result.push({ - name: `${cls.name}.${method.name}`, - from: method.nameStart, - to: method.nameStart + method.name.length, + ...declaration(cls.name, method), paths: combine(base.values, own.values), methods: verbs.includes("*") ? classMethods diff --git a/src/features/http-client/spring/feignNavigation.test.ts b/src/features/http-client/spring/feignNavigation.test.ts index 27f47e104..f1630bcd1 100644 --- a/src/features/http-client/spring/feignNavigation.test.ts +++ b/src/features/http-client/spring/feignNavigation.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { _emitEditorEvent } from "@/editor/api"; import { commands, emitLocalIdeEvent, type ProjectInfo } from "@/platform/ipc"; import { useProject } from "@/platform/project"; -import { feignMethods } from "./feign"; -import { feignTargets, registerFeignNavigation } from "./feignNavigation"; +import { controllerMethods, feignMethods } from "./feign"; +import { feignClients, feignTargets, registerFeignNavigation } from "./feignNavigation"; const root = "/p"; const clientPath = "/p/client/src/main/java/Client.java"; @@ -169,3 +169,133 @@ describe("core service-aware Feign navigation", () => { expect(vi.mocked(commands.fsReadText).mock.calls.every(([path]) => path.endsWith(".java"))).toBe(true); }); }); + +describe("finding Feign declarations from a controller", () => { + const clients = (controller = server, source = users) => feignClients(source, controllerMethods(controller)[0]!); + const config = "/p/users/src/main/resources/application.properties"; + + it("orders service matches first, excludes other services and returns each declaration at its UTF-16 identifier", async () => { + const unknown = "/p/a/src/main/java/Dynamic.java"; + const direct = "/p/b/src/main/java/Direct.java"; + const source = client.replace( + '@GetMapping("/users/{id}")', + '@GetMapping({"/users/{key}", "/users/{id}"}) /* 🛒 */', + ); + files.set(clientPath, source); + files.set(unknown, client.replace('name="users"', 'name="${service}"')); + files.set(direct, client.replace('name="users"', 'name="elsewhere",url="https://example.org"')); + files.set("/p/z/src/main/java/Other.java", client.replace('name="users"', 'name="admin"')); + files.set("/p/admin/src/main/java/OtherVerb.java", client.replaceAll("GetMapping", "PostMapping")); + files.set("/p/admin/src/main/java/OtherPath.java", client.replace("/users/{id}", "/users/all/active")); + await resolve(); // Both lookups share the same inventory. + const results = await clients(); + expect(results.map((t) => [t.path, !!t.possible])).toEqual([ + [clientPath, false], + [unknown, true], + [direct, true], + ]); + const col = source.split("\n")[2]!.indexOf("find()"); + expect(results[0]).toMatchObject({ + name: "Client.find", + range: { start: { line: 2, col }, end: { line: 2, col: col + 4 } }, + }); + expect(commands.springRouteSources).toHaveBeenCalledTimes(1); + }); + + it("keeps the roles of client and server for HEAD and unconstrained mappings", async () => { + files.set( + clientPath, + client + .replace( + "import org.springframework.web.bind.annotation.GetMapping", + "import org.springframework.web.bind.annotation.*", + ) + .replace('@GetMapping("/users/{id}")', '@RequestMapping(path="/users/{id}", method=RequestMethod.HEAD)'), + ); + const post = "/p/client/src/main/java/Post.java"; + files.set(post, client.replaceAll("GetMapping", "PostMapping")); + expect((await clients()).map((t) => t.path)).toEqual([clientPath]); + expect((await clients(server.replace("GetMapping", "RequestMapping"))).map((t) => t.path)).toEqual([ + clientPath, + post, + ]); + expect(await clients(server.replace("GetMapping", "PutMapping"))).toEqual([]); + }); + + it("rechecks edited and deleted declarations and the controller's current service without rescanning on typing", async () => { + const edit = (path: string) => + _emitEditorEvent({ type: "docChanged", doc: 9, path, baseVersion: 1, version: 2, changes: [] }); + files.set(clientPath, client); + expect((await clients()).map((t) => t.name)).toEqual(["Client.find"]); + files.set(clientPath, client.replace('name="users"', 'name="admin"')); + expect(await clients()).toEqual([]); // Revalidate even when the source event has not arrived yet. + const added = "/p/orders/src/main/kotlin/New.kt"; + files.set( + added, + `import org.springframework.cloud.openfeign.FeignClient +import org.springframework.web.bind.annotation.GetMapping +@FeignClient("users") +interface New { @GetMapping("/users/{key}") fun lookup(): String }`, + ); + edit(added); // Newly edited, without a visible editor or an entry in the disk index. + expect((await clients()).map((t) => t.name)).toEqual(["New.lookup"]); + files.set(config, "spring.application.name=admin\n"); + edit(config); + edit(clientPath); + expect((await clients()).map((t) => t.name)).toEqual(["Client.find"]); + files.delete(clientPath); + expect(await clients()).toEqual([]); + expect(commands.springRouteSources).toHaveBeenCalledTimes(1); + }); + + it("marks every match as possible if the controller's owning module has no unique identity", async () => { + files.set(clientPath, client); + files.set("/p/src/main/resources/application.properties", "spring.application.name=users\n"); + files.set("/p/users/src/main/resources/application-live.yml", "spring.application.name: alternate\n"); + files.set("/outside/src/main/java/Other.java", client); + expect((await clients()).map((t) => [t.path, t.possible])).toEqual([[clientPath, true]]); + expect(vi.mocked(commands.fsReadText).mock.calls.every(([path]) => path.startsWith("/p/"))).toBe(true); + }); + + it("finds a Java client for a Kotlin endpoint across linked projects and ignores unattached siblings", async () => { + const kotlin = `import org.springframework.web.bind.annotation.* +@RestController class Users { @GetMapping("/users/{user}") fun find(): String = "" }`; + const source = "/p/users/src/main/kotlin/Users.kt"; + useProject.setState({ + project: { + ...project("/workspace"), + workspace: { + version: 1, + name: "Services", + projects: ["/p/users", "/p/client"], + }, + }, + }); + files.set(source, kotlin); + files.set(clientPath, client); + files.set("/p/unattached/src/main/java/Other.java", client); + expect((await clients(kotlin, source)).map((t) => [t.path, !!t.possible])).toEqual([[clientPath, false]]); + expect(commands.fsReadText).not.toHaveBeenCalledWith("/p/unattached/src/main/java/Other.java"); + }); + + it("skips untrusted and outside sources, and cancels a pending lookup on workspace switch", async () => { + useProject.setState({ project: { ...project(), trusted: false } }); + expect(await clients()).toEqual([]); + useProject.setState({ project: project() }); + expect(await clients(server, "/elsewhere/Users.java")).toEqual([]); + expect(commands.springRouteSources).not.toHaveBeenCalled(); + expect(commands.fsReadDir).not.toHaveBeenCalled(); + let finish!: (value: Awaited>) => void; + vi.mocked(commands.springRouteSources).mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const pending = clients(); + useProject.setState({ project: project("/elsewhere") }); + finish({ status: "ok", data: [{ path: clientPath, text: client }] }); + expect(await pending).toEqual([]); + expect(commands.fsReadText).not.toHaveBeenCalledWith(clientPath); + }); +}); diff --git a/src/features/http-client/spring/feignNavigation.ts b/src/features/http-client/spring/feignNavigation.ts index 09adfd344..6b9249d57 100644 --- a/src/features/http-client/spring/feignNavigation.ts +++ b/src/features/http-client/spring/feignNavigation.ts @@ -10,21 +10,31 @@ import { } from "@/editor/api"; import { docOf } from "@/editor/lsp/lsp"; import { locationItems, navigateTo } from "@/editor/lsp/navigation"; -import { caretAnchor, openPopup } from "@/editor/lsp/popupStore"; +import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore"; import { invalidateNavigationProviders, registerNavigationProvider } from "@/editor/navigationProviders"; import { executeAction } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import { call, commands, onIdeEvent, type Location, type ProjectInfo } from "@/platform/ipc"; import { isSameOrInside } from "@/platform/paths"; -import { projectFolder, useProject } from "@/platform/project"; +import { projectFolder, relativePath, useProject } from "@/platform/project"; import { gutterIconMarkup, type MenuItem } from "@/ui"; import { notifications, type MenuGroupContext } from "@/workbench/contributions"; -import { callsEndpoint, controllerMethods, feignMethods, MAX_NAVIGATION_SOURCE, type FeignMethod } from "./feign"; -import { clearRouteIndex, controllerIndex, isRouteSource, type ControllerTarget } from "./routeIndex"; +import { + callsEndpoint, + controllerMethods, + feignMethods, + MAX_NAVIGATION_SOURCE, + type FeignMethod, + type HttpShape, + type MappedMethod, +} from "./feign"; +import { clearRouteIndex, controllerIndex, feignClientIndex, isRouteSource } from "./routeIndex"; import { isServiceConfiguration, loadServiceName, sourceModule } from "./serviceIdentity"; import styles from "../HttpClient.module.css"; export const GO_TO_FEIGN_ENDPOINT = "http.goToFeignEndpoint"; +export const FIND_FEIGN_CLIENTS = "http.findFeignClients"; +const TARGET_LIMIT = 256; const serviceNames = new Map>(); const changedSources = new Set(); let epoch = 0; @@ -60,78 +70,115 @@ function named(module: string): Promise { return pending; } -function location( - path: string, - text: string, - method: ReturnType[number], -): Location & { name: string } { - const doc = Text.of(text.split("\n")); - const from = doc.lineAt(method.from), - to = doc.lineAt(method.to); +interface FeignLocation extends Location { + name: string; + possible?: boolean; +} + +function location(path: string, doc: Text, method: MappedMethod): FeignLocation { + const from = doc.lineAt(method.nameFrom); return { path, name: method.name, range: { - start: { line: from.number - 1, col: method.from - from.from }, - end: { line: to.number - 1, col: method.to - to.from }, + start: { line: from.number - 1, col: method.nameFrom - from.from }, + end: { line: from.number - 1, col: method.nameTo - from.from }, }, }; } -/** The index supplies candidates; current source/configuration supplies the navigation target. */ -export async function feignTargets(source: string, client: FeignMethod): Promise<(Location & { name: string })[]> { +function lookupScope(source: string) { const project = useProject.getState().project; - if (!project?.trusted || !inside(project, source)) return []; + if (!project?.trusted || !inside(project, source)) return null; const key = projectKey(project), started = epoch; - const stale = () => started !== epoch || key !== projectKey(useProject.getState().project); - const indexed = await controllerIndex(project.root); - if (stale()) return []; - const overlays = new Set( - [...new Set([...changedSources, ...[...useEditorRegistry.getState().editors].map((e) => e.ctx.path)])] - .filter((path) => isRouteSource(path) && inside(project, path)) - .slice(0, 256), - ); - const currentText = new Map(); - const candidates: ControllerTarget[] = indexed.filter((target) => !overlays.has(target.path)); - // Visible and recently edited source files include unsaved/new controllers - // that the filesystem inventory has not seen yet. Never keep their full text. - for (const path of overlays) { + return { project, stale: () => started !== epoch || key !== projectKey(useProject.getState().project) }; +} + +function controllerService(project: ProjectInfo, path: string): Promise { + const module = sourceModule(path); + const folder = projectFolder(project, path); + return module && folder && isSameOrInside(module, folder.root) ? named(module) : Promise.resolve(null); +} + +/** The disk index narrows the search. Open and recently edited files may contain new + * mappings, and the current source supplies the identifier range we actually open. */ +async function* currentMappings( + scope: NonNullable>, + indexedPaths: string[], + parse: (text: string) => T[], + matches: (method: T) => boolean, +) { + const paths = new Set([...new Set(indexedPaths)].slice(0, TARGET_LIMIT)); + const overlays = new Set([...changedSources, ...[...useEditorRegistry.getState().editors].map((e) => e.ctx.path)]); + for (const path of [...overlays].filter((p) => isRouteSource(p) && inside(scope.project, p)).slice(0, TARGET_LIMIT)) + paths.add(path); + for (const path of [...paths].sort()) { + if (scope.stale()) return; const text = await read(path).catch(() => null); - if (text === null || text.length > MAX_NAVIGATION_SOURCE || stale()) continue; - currentText.set(path, text); - candidates.push(...controllerMethods(text).map((method) => ({ ...method, path }))); - } - const paths = [ - ...new Set(candidates.filter((target) => callsEndpoint(client, target)).map((target) => target.path)), - ].sort(); - const result: (Location & { name: string })[] = []; - for (const path of paths.slice(0, 256)) { - if (stale()) return []; - const module = sourceModule(path); - const folder = projectFolder(project, path); - if (client.service && module && folder && isSameOrInside(module, folder.root)) { - const name = await named(module); - if (name && name !== client.service) continue; - } - const text = currentText.get(path) ?? (await read(path).catch(() => null)); + if (scope.stale()) return; if (text === null || text.length > MAX_NAVIGATION_SOURCE) continue; - for (const method of controllerMethods(text).filter((method) => callsEndpoint(client, method))) { - const target = location(path, text, method); - if ( - !result.some( - (r) => - r.path === path && - r.range.start.line === target.range.start.line && - r.range.start.col === target.range.start.col, - ) - ) - result.push(target); - if (result.length === 256) break; - } - if (result.length === 256) break; + const methods = parse(text).filter(matches); + if (methods.length) yield { path, doc: Text.of(text.split("\n")), methods }; } - return stale() ? [] : result; +} + +export async function feignTargets(source: string, client: FeignMethod): Promise { + const scope = lookupScope(source); + if (!scope) return []; + const indexed = await controllerIndex(scope.project.root); + if (scope.stale()) return []; + const matches = (method: HttpShape) => callsEndpoint(client, method); + const paths = indexed + .filter(matches) + .map((entry) => entry.path) + .sort(); + const result: FeignLocation[] = []; + for await (const { path, doc, methods } of currentMappings(scope, paths, controllerMethods, matches)) { + const service = client.service && (await controllerService(scope.project, path)); + if (service && service !== client.service) continue; + for (const method of methods) { + result.push(location(path, doc, method)); + if (result.length === TARGET_LIMIT) break; + } + if (result.length === TARGET_LIMIT) break; + } + return scope.stale() ? [] : result; +} + +export async function feignClients(source: string, controller: MappedMethod): Promise { + const scope = lookupScope(source); + if (!scope) return []; + const [indexed, service] = await Promise.all([ + feignClientIndex(scope.project.root), + controllerService(scope.project, source), + ]); + if (scope.stale()) return []; + const matches = (client: HttpShape & { service: string | null }) => + (!service || !client.service || client.service === service) && callsEndpoint(client, controller); + const candidates = indexed.filter(matches); + // Keep named clients ahead of ambiguous ones when the candidate limit is reached. + const paths = [ + ...candidates + .filter((entry) => service && entry.service) + .map((entry) => entry.path) + .sort(), + ...candidates + .filter((entry) => !service || !entry.service) + .map((entry) => entry.path) + .sort(), + ]; + const confirmed: FeignLocation[] = [], + possible: FeignLocation[] = []; + for await (const { path, doc, methods } of currentMappings(scope, paths, feignMethods, matches)) { + for (const method of methods) { + if (service && method.service) confirmed.push(location(path, doc, method)); + else if (possible.length < TARGET_LIMIT) possible.push({ ...location(path, doc, method), possible: true }); + if (confirmed.length === TARGET_LIMIT) break; + } + if (confirmed.length === TARGET_LIMIT) break; + } + return scope.stale() ? [] : [...confirmed, ...possible].slice(0, TARGET_LIMIT); } export function registerFeignNavigation(): () => void { @@ -183,44 +230,87 @@ export function registerFeignNavigation(): () => void { }; } -export async function goToFeignEndpoint(arg?: unknown): Promise { +function clientItem(target: FeignLocation): ListPopupItem { + const project = useProject.getState().project; + const folder = projectFolder(project, target.path); + const path = folder ? relativePath(folder.root, target.path) : target.path; + const display = project?.workspace && folder ? `${folder.name}/${path}` : path; + const { line, col } = target.range.start; + return { + id: `${target.path}:${line}:${col}`, + label: target.name, + detail: `${display}:${line + 1}`, + preview: target.possible ? tx("Possible match") : undefined, + symbol: "method", + location: { path: target.path, line }, + run: () => navigateTo(target), + }; +} + +export async function navigateFeign(direction: "endpoint" | "clients", arg?: unknown): Promise { const requested = arg as { path?: unknown; offset?: unknown } | undefined; const editor = typeof requested?.path === "string" ? editorsFor(requested.path)[0] : activeEditor(); if (!editor || editor.ctx.virtual || !["java", "kotlin"].includes(editor.ctx.language)) return; + const scope = lookupScope(editor.ctx.path); + if (!scope) return; const view = editor.view, - before = view.state.doc, - started = epoch; + before = view.state.doc; const offset = typeof requested?.offset === "number" ? requested.offset : view.state.selection.main.head; - const client = feignMethods(before.toString()).find((c) => c.from <= offset && offset <= c.to); - if (!client) return; + const atCaret = (m: MappedMethod) => m.from <= offset && offset <= m.to; const stale = () => - view.state.doc !== before || started !== epoch || !editorsFor(editor.ctx.path).some((e) => e.view === view); + view.state.doc !== before || scope.stale() || !editorsFor(editor.ctx.path).some((e) => e.view === view); try { - const targets = await feignTargets(editor.ctx.path, client); + let targets: FeignLocation[]; + if (direction === "clients") { + const controller = controllerMethods(before.toString()).find(atCaret); + if (!controller) { + notifications().notify({ + level: "info", + title: tx("No Spring request mapping at the caret"), + key: "feign-navigation", + }); + return; + } + targets = await feignClients(editor.ctx.path, controller); + } else { + const client = feignMethods(before.toString()).find(atCaret); + if (!client) return; + targets = await feignTargets(editor.ctx.path, client); + } if (stale()) return; if (!targets.length) { - notifications().notify({ level: "info", title: tx("No matching Feign endpoint found"), key: "feign-navigation" }); - } else if (targets.length === 1) await navigateTo(targets[0]!); + notifications().notify({ + level: "info", + title: direction === "clients" ? tx("No matching Feign clients found") : tx("No matching Feign endpoint found"), + key: "feign-navigation", + }); + } else if (targets.length === 1 && !targets[0]!.possible) await navigateTo(targets[0]!); else { - const items = await locationItems(targets); + const items = direction === "clients" ? targets.map(clientItem) : await locationItems(targets); if (stale()) return; openPopup({ kind: "list", - title: tx("Choose Feign Endpoint"), + title: direction === "clients" ? tx("Feign Clients") : tx("Choose Feign Endpoint"), anchor: caretAnchor(view, Math.min(offset, before.length)), items: items.map((item) => ({ ...item, run: () => (stale() ? undefined : item.run()) })), }); } } catch (error) { - notifications().notify({ - level: "error", - title: tx("Cannot navigate to Feign endpoint"), - body: String(error), - key: "feign-navigation", - }); + if (!stale()) + notifications().notify({ + level: "error", + title: direction === "clients" ? tx("Cannot find Feign clients") : tx("Cannot navigate to Feign endpoint"), + body: String(error), + key: "feign-navigation", + }); } } +export function findClientItems(path: string, text: string, offset: number): MenuItem[] { + if (!lookupScope(path) || !controllerMethods(text).some((method) => method.nameFrom === offset)) return []; + return [{ kind: "action", action: FIND_FEIGN_CLIENTS, icon: "search", arg: { path, offset } }]; +} + export function feignMenuItems(context: MenuGroupContext): MenuItem[] { const editor = activeEditor(); if (!editor || editor.ctx.path !== context.paths[0]) return []; diff --git a/src/features/http-client/spring/routeIndex.ts b/src/features/http-client/spring/routeIndex.ts index 1a728dc14..423975447 100644 --- a/src/features/http-client/spring/routeIndex.ts +++ b/src/features/http-client/spring/routeIndex.ts @@ -5,15 +5,19 @@ import { projectFolder, relativePath, useProject } from "@/platform/project"; import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions"; import { constantPool, resetConstantPool } from "./constants"; import { controllersOf } from "./endpoints"; -import { controllerMethods, type ControllerMethod } from "./feign"; +import { controllerMethods, feignMethods, type HttpShape } from "./feign"; import { parseSource } from "./source"; -export interface ControllerTarget extends ControllerMethod { +interface ControllerTarget extends HttpShape { path: string; } +interface ClientSource extends ControllerTarget { + service: string | null; +} interface RouteIndex { routes: EndpointEntry[]; controllers: ControllerTarget[]; + clients: ClientSource[]; } export function registerSpringEndpointProvider(): () => void { @@ -51,8 +55,12 @@ export function controllerIndex(root: string | null): Promise result.controllers); } +export function feignClientIndex(root: string): Promise { + return index(root).then((result) => result.clients); +} + function index(root: string | null): Promise { - if (!root) return Promise.resolve({ routes: [], controllers: [] }); + if (!root) return Promise.resolve({ routes: [], controllers: [], clients: [] }); const current = useProject.getState().project; const project = current?.root === root ? current : null; const key = JSON.stringify([root, project?.workspace?.projects ?? null]); @@ -67,6 +75,7 @@ function index(root: string | null): Promise { async function scan(root: string, project: ProjectInfo | null): Promise { const sources = await call(commands.springRouteSources()); + const clients: ClientSource[] = []; const routes: EndpointEntry[] = []; const controllers: ControllerTarget[] = []; const parsed = []; @@ -76,6 +85,8 @@ async function scan(root: string, project: ProjectInfo | null): Promise Date: Fri, 20 Nov 2026 02:47:51 +0800 Subject: [PATCH 10/15] test: fix main's spacing-scale and model-refresh failures (#4591) pnpm test failed on main twice: the HTTP Client's redirect list from #4519 used gap: 2px instead of --space-0-5, and the agent model-refresh test's IPC mock lacked vcsRemotes, which the session's origin lookup reads since #4554. --- src/features/agents/modelRefresh.test.tsx | 1 + src/features/http-client/HttpClient.module.css | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/features/agents/modelRefresh.test.tsx b/src/features/agents/modelRefresh.test.tsx index d4e79693b..abc61b9a0 100644 --- a/src/features/agents/modelRefresh.test.tsx +++ b/src/features/agents/modelRefresh.test.tsx @@ -54,6 +54,7 @@ vi.mock("@/platform/ipc", async (original) => ({ agentCommands: async () => ok([]), vcsBranchInfo: async () => ok({ head: "main" }), vcsConfigGet: async () => ok(null), + vcsRemotes: async () => ok([]), vcsBranches: async () => ok([]), agentCreate: (request: NewAgentTask) => backend.create(request), agentEntries: async () => ok([{ type: "user", text: "Earlier message", attachments: [] }] satisfies AgentEntry[]), diff --git a/src/features/http-client/HttpClient.module.css b/src/features/http-client/HttpClient.module.css index 8a4e813c6..babaf0683 100644 --- a/src/features/http-client/HttpClient.module.css +++ b/src/features/http-client/HttpClient.module.css @@ -135,7 +135,7 @@ .redirects { display: flex; flex-direction: column; - gap: 2px; + gap: var(--space-0-5); padding: 2px 8px; border-bottom: 1px solid var(--border); font-family: var(--font-mono); From 5859cf9f5bceb0af3865e418fbe7be4290a3318f Mon Sep 17 00:00:00 2001 From: lleviathe <95321986+lleviathe@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:49:08 +0400 Subject: [PATCH 11/15] feat(mcp): show background projects in the status bar (#4590) A Background Projects status bar item shows how many projects the MCP server holds open without a window, only while there are any (and never in a remote window). Its popup lists each project with its badge, state and path, opens one in its own window or unloads it, and offers Unload All and MCP Server Settings. The Settings page's Open now list uses the same rows. Co-authored-by: lleviathe <95321986+lleviathe@users.noreply.github.com> --- docs/en/guide/mcp.mdx | 2 + docs/zh/guide/mcp.mdx | 2 + src/features/mcp/BackgroundStatus.module.css | 119 +++++++++++++++ src/features/mcp/BackgroundStatus.test.tsx | 139 ++++++++++++++++++ src/features/mcp/BackgroundStatus.tsx | 112 ++++++++++++++ src/features/mcp/index.ts | 12 +- src/features/mcp/reporters.test.ts | 7 +- .../settings/pages/McpServer.module.css | 35 +++-- src/features/settings/pages/mcpServer.tsx | 13 +- src/platform/locales/text/en.json | 7 + src/platform/locales/text/zh.json | 7 + src/platform/mcpBackground.ts | 5 + src/ui/icons.tsx | 1 + src/ui/openidea/general/layers.svg | 4 + src/workbench/ProjectBadge.module.css | 14 ++ src/workbench/ProjectBadge.tsx | 15 ++ 16 files changed, 473 insertions(+), 21 deletions(-) create mode 100644 src/features/mcp/BackgroundStatus.module.css create mode 100644 src/features/mcp/BackgroundStatus.test.tsx create mode 100644 src/features/mcp/BackgroundStatus.tsx create mode 100644 src/ui/openidea/general/layers.svg create mode 100644 src/workbench/ProjectBadge.module.css create mode 100644 src/workbench/ProjectBadge.tsx diff --git a/docs/en/guide/mcp.mdx b/docs/en/guide/mcp.mdx index 5a7f8662d..60a578010 100644 --- a/docs/en/guide/mcp.mdx +++ b/docs/en/guide/mcp.mdx @@ -155,6 +155,8 @@ When a project loads and unloads: **Open now** lists the loaded projects, each with what it is doing (answering a request, kept open by a run, or how long it has been idle and when it unloads) and an **Unload** button. Unloading does not wait for **Apply**. The project loads again on the next tool call that names it, if the setting still serves it. +While any project is loaded, the **Background Projects** item in the status bar (a layers icon and the count) opens the same list. Each row has the **Open in New Window** and **Unload** icon buttons, and below the list are **Unload All** and **MCP Server Settings…**. + What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools. A background project has no window, so some tools differ: diff --git a/docs/zh/guide/mcp.mdx b/docs/zh/guide/mcp.mdx index 8f03803ab..ce60b2927 100644 --- a/docs/zh/guide/mcp.mdx +++ b/docs/zh/guide/mcp.mdx @@ -154,6 +154,8 @@ stdio 配置大致如下(路径以你机器上的为准): **当前已打开** 列出已加载的项目,每个项目显示它正在做什么(正在处理请求、因某个运行保持打开,或已空闲多久以及何时卸载),并带有 **卸载** 按钮。卸载不必等到 **应用**。如果设置仍然提供该项目,下一次指向它的工具调用会再次加载它。 +只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。 + 信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。 后台项目没有窗口,所以有些工具不同: diff --git a/src/features/mcp/BackgroundStatus.module.css b/src/features/mcp/BackgroundStatus.module.css new file mode 100644 index 000000000..2ed9b4396 --- /dev/null +++ b/src/features/mcp/BackgroundStatus.module.css @@ -0,0 +1,119 @@ +/* Mirrors the title bar's project popup: two-line project rows, then action rows. */ +.panel { + display: flex; + flex-direction: column; + width: 400px; + padding: var(--space-1-5) 0; + font-family: var(--font-ui); + font-size: var(--fs-ui); + color: var(--fg); + outline: none; +} +.header { + padding: var(--space-1) var(--space-4); + color: var(--fg-muted); + font-size: var(--fs-small); + font-weight: 600; +} +.projects { + display: flex; + flex-direction: column; + max-height: 320px; + margin: 0; + padding: 0; + overflow-y: auto; + list-style: none; +} +.project { + position: relative; + display: flex; + align-items: center; + gap: var(--space-3); + min-width: 0; + margin: 0 var(--space-1-5); + padding: var(--space-1-5) var(--space-2); + border-radius: var(--radius-selection); +} +.project:hover, +.project:focus-within { + background: var(--bg-tree-selected); +} +.text { + display: flex; + flex: 1; + flex-direction: column; + gap: var(--space-0-5); + min-width: 0; +} +.top { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-3); + min-width: 0; +} +.name, +.path, +.state { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.name { + color: var(--fg-strong); +} +.path, +.state { + color: var(--fg-subtle); + font-size: var(--fs-small); +} +.state { + flex: none; + max-width: 60%; +} +/* The row's actions take the place of its state while the row is hovered or focused. */ +.actions { + position: absolute; + top: 50%; + right: var(--space-2); + display: flex; + gap: var(--space-0-5); + transform: translateY(-50%); + opacity: 0; +} +.project:hover .actions, +.project:focus-within .actions { + opacity: 1; +} +.project:hover .state, +.project:focus-within .state { + visibility: hidden; +} +.project:hover .path, +.project:focus-within .path { + padding-right: 52px; +} +.separator { + height: 1px; + margin: var(--space-1-5) var(--space-3); + background: var(--border); +} +.action { + display: flex; + align-items: center; + min-height: var(--h-list-row); + margin: 0 var(--space-1-5); + padding: 0 var(--space-2); + border: 0; + border-radius: var(--radius-selection); + background: none; + color: var(--fg-strong); + font: inherit; + text-align: left; + cursor: default; +} +.action:hover, +.action:focus-visible { + background: var(--bg-tree-selected); + outline: none; +} diff --git a/src/features/mcp/BackgroundStatus.test.tsx b/src/features/mcp/BackgroundStatus.test.tsx new file mode 100644 index 000000000..b0ba288c0 --- /dev/null +++ b/src/features/mcp/BackgroundStatus.test.tsx @@ -0,0 +1,139 @@ +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { McpBackgroundProject } from "@/bindings"; + +const mocks = vi.hoisted(() => ({ + list: vi.fn(), + unload: vi.fn(), + execute: vi.fn(async (_id: string, _arg?: unknown) => {}), +})); +vi.mock("@/platform/actions", async (original) => ({ + ...(await original()), + executeAction: mocks.execute, +})); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + isTauri: () => true, + commands: { ...real.commands, mcpBackgroundProjects: mocks.list, mcpUnloadBackgroundProject: mocks.unload }, + }; +}); + +const { emitLocalIdeEvent } = await import("@/platform/ipc"); +const { useRemote } = await import("@/platform/remote"); +const { BackgroundStatus } = await import("./BackgroundStatus"); + +const ok = (data: T) => ({ status: "ok" as const, data }); +const project = (root: string, patch: Partial = {}): McpBackgroundProject => ({ + root, + idleSeconds: 0, + ...patch, +}); +const inventory = project("/projects/inventory"); +const billing = project("/projects/billing", { keptOpenBy: { kind: "request" } }); + +async function show(projects: McpBackgroundProject[]) { + mocks.list.mockResolvedValue(ok(projects)); + render(); + await act(async () => {}); +} +const openPopup = async () => { + fireEvent.click(screen.getByRole("button", { name: /Background Projects/ })); + await act(async () => {}); + return screen.getByRole("dialog", { name: "Background Projects" }); +}; + +beforeEach(() => { + mocks.list.mockReset(); + mocks.unload.mockReset().mockResolvedValue(ok(null)); + mocks.execute.mockClear(); +}); +afterEach(() => { + cleanup(); + useRemote.setState({ session: null }); +}); + +describe("background projects in the status bar", () => { + it("renders nothing while no project is loaded", async () => { + await show([]); + expect(screen.queryByRole("button")).toBeNull(); + }); + + it("shows how many projects are loaded", async () => { + await show([inventory, billing]); + expect(screen.getByRole("button", { name: /Background Projects/ })).toHaveTextContent("2"); + }); + + it("lists each project with its name, path and state", async () => { + await show([inventory, billing]); + const popup = await openPopup(); + expect(within(popup).getByText("inventory")).toBeInTheDocument(); + expect(within(popup).getByText("/projects/billing")).toBeInTheDocument(); + expect(within(popup).getByText("Answering a request")).toBeInTheDocument(); + expect(within(popup).getByText("Last request just now")).toBeInTheDocument(); + }); + + it("opens with the focus on the list, so no row's state gives way to its actions", async () => { + await show([inventory]); + const popup = await openPopup(); + expect(popup.contains(document.activeElement)).toBe(true); + expect(document.activeElement).not.toBeInstanceOf(HTMLButtonElement); + }); + + it("stays hidden in a remote window, whose server serves no background projects", async () => { + useRemote.setState({ + session: { root: "/srv/app" } as NonNullable["session"]>, + }); + await show([inventory]); + expect(screen.queryByRole("button")).toBeNull(); + }); + + it("names a project at the file system root by its path", async () => { + await show([project("/")]); + const popup = await openPopup(); + expect(within(popup).getAllByText("/").length).toBe(2); + }); + + it("opens a project in its own window from its row", async () => { + await show([inventory, billing]); + const popup = await openPopup(); + fireEvent.click(within(popup).getByRole("button", { name: "Open /projects/billing in a new window" })); + expect(mocks.execute).toHaveBeenCalledWith("file.openInNewWindow", "/projects/billing"); + }); + + it("unloads the project of the row", async () => { + await show([inventory, billing]); + const popup = await openPopup(); + fireEvent.click(within(popup).getByRole("button", { name: "Unload /projects/inventory" })); + expect(mocks.unload).toHaveBeenCalledTimes(1); + expect(mocks.unload).toHaveBeenCalledWith("/projects/inventory"); + }); + + it("unloads every listed project once with Unload All", async () => { + await show([inventory, billing]); + const popup = await openPopup(); + fireEvent.click(within(popup).getByRole("button", { name: "Unload All" })); + expect(mocks.unload.mock.calls.map((c) => c[0])).toEqual(["/projects/inventory", "/projects/billing"]); + }); + + it("closes the popup before it opens the MCP server settings", async () => { + await show([inventory]); + const popup = await openPopup(); + mocks.execute.mockImplementationOnce(async () => { + expect(popup.isConnected).toBe(false); + }); + fireEvent.click(within(popup).getByRole("button", { name: "MCP Server Settings…" })); + expect(mocks.execute).toHaveBeenCalledWith("file.settings", "agents.mcpServer"); + expect(screen.queryByRole("dialog", { name: "Background Projects" })).toBeNull(); + }); + + it("closes the popup and hides the item when the last project unloads", async () => { + await show([inventory]); + await openPopup(); + mocks.list.mockResolvedValue(ok([])); + await act(async () => emitLocalIdeEvent({ type: "mcpBackgroundProjectsChanged" })); + expect(screen.queryByRole("dialog", { name: "Background Projects" })).toBeNull(); + expect(screen.queryByRole("button")).toBeNull(); + }); +}); diff --git a/src/features/mcp/BackgroundStatus.tsx b/src/features/mcp/BackgroundStatus.tsx new file mode 100644 index 000000000..f4033c3a1 --- /dev/null +++ b/src/features/mcp/BackgroundStatus.tsx @@ -0,0 +1,112 @@ +import { useRef, useState } from "react"; +import { flushSync } from "react-dom"; +import { BarButton, Icon, IconButton, Popup, T } from "@/ui"; +import { executeAction } from "@/platform/actions"; +import { useTx } from "@/platform/i18n"; +import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground"; +import { basename } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; +import { ProjectBadge } from "@/workbench/ProjectBadge"; +import styles from "./BackgroundStatus.module.css"; + +/** Status bar item for the projects the MCP server holds open without a window. */ +export function BackgroundStatus() { + const t = useTx(); + const loaded = useBackgroundProjects(); + // A remote window's commands reach its server, which serves none: the desktop's list stays out of it. + const remote = useRemote((s) => s.session !== null); + const projects = remote ? [] : loaded; + const [open, setOpen] = useState(false); + const ref = useRef(null); + const count = projects.length; + + // Reset during render, so the popup does not reappear with the next project that loads. + if (count === 0 && open) setOpen(false); + + if (count === 0) return null; + return ( + <> + setOpen((o) => !o)} + > + + {count} + + setOpen(false)} + aria-label={t("Background Projects")} + > + {/* The focus starts on the list: on a row it would swap that row's state for its actions. */} +
+
+ Served without a window +
+
    + {projects.map((project) => { + const path = project.root; + const name = basename(path) || path; + return ( +
  • + +
    + + + {name} + + {backgroundProjectState(project)} + + + {path} + +
    + + void executeAction("file.openInNewWindow", path)} + /> + unloadBackgroundProject(path)} + /> + +
  • + ); + })} +
+
+ + +
+ + + ); +} diff --git a/src/features/mcp/index.ts b/src/features/mcp/index.ts index 7453c1d05..c40ed3ee4 100644 --- a/src/features/mcp/index.ts +++ b/src/features/mcp/index.ts @@ -4,12 +4,21 @@ import { commands, call, onIdeEvent, ideEventsReady } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { useRemote } from "@/platform/remote"; -import { registerOverlay } from "@/workbench/contributions"; +import { registerOverlay, registerStatusItem } from "@/workbench/contributions"; +import { BackgroundStatus } from "./BackgroundStatus"; import { McpConfirmHost } from "./ConfirmDialog"; import { denyAll, dropConfirm, handleMcpRequest } from "./requests"; export function activate(): () => void { const offOverlay = registerOverlay({ id: "mcp.confirm", component: McpConfirmHost }); + const offStatus = registerStatusItem({ + id: "mcp.background", + align: "right", + priority: 4, + title: "Background Projects", + component: BackgroundStatus, + lightEdit: true, + }); const offRequests = onIdeEvent("mcpRequest", (e) => void handleMcpRequest(e.id, e.request)); const offClosed = onIdeEvent("mcpRequestClosed", (e) => dropConfirm(e.id)); const ready = () => { @@ -104,6 +113,7 @@ export function activate(): () => void { disposed = true; unload(); offOverlay(); + offStatus(); offRequests(); offClosed(); window.removeEventListener("beforeunload", unload); diff --git a/src/features/mcp/reporters.test.ts b/src/features/mcp/reporters.test.ts index 20df822c9..4c44e65a2 100644 --- a/src/features/mcp/reporters.test.ts +++ b/src/features/mcp/reporters.test.ts @@ -73,8 +73,13 @@ vi.mock("@/platform/ipc", () => ({ mcpSetFocusedEditor: state.reportFocused, }, })); -vi.mock("@/workbench/contributions", () => ({ registerOverlay: () => () => {}, editorService: vi.fn() })); +vi.mock("@/workbench/contributions", () => ({ + registerOverlay: () => () => {}, + registerStatusItem: () => () => {}, + editorService: vi.fn(), +})); vi.mock("./ConfirmDialog", () => ({ McpConfirmHost: () => null })); +vi.mock("./BackgroundStatus", () => ({ BackgroundStatus: () => null })); const { activate } = await import("./index"); describe("MCP editor reports", () => { diff --git a/src/features/settings/pages/McpServer.module.css b/src/features/settings/pages/McpServer.module.css index a8e6f3ea6..374c61e41 100644 --- a/src/features/settings/pages/McpServer.module.css +++ b/src/features/settings/pages/McpServer.module.css @@ -12,43 +12,52 @@ align-items: center; gap: var(--space-2); } -.path { - flex: 1; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-family: var(--font-mono); - font-size: var(--fs-small); -} +/* Framed like the Folders list above it; rows as in the status bar's Background Projects popup. */ .projects { display: flex; flex-direction: column; - gap: var(--space-2); width: 100%; + max-width: 480px; min-width: 0; margin: 0; padding: 0; + border-radius: var(--radius-small); + box-shadow: inset 0 0 0 1px var(--border-strong); list-style: none; } .project { display: flex; align-items: center; - gap: var(--space-2); + gap: var(--space-3); min-width: 0; + padding: var(--space-2) var(--space-3); +} +.project + .project { + border-top: 1px solid var(--border); } .projectText { display: flex; flex: 1; flex-direction: column; + gap: var(--space-0-5); min-width: 0; } -.projectName { +.projectName, +.projectPath, +.projectState { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - font-weight: 600; } +.projectName { + color: var(--fg-strong); +} +.projectPath, +.projectState { + color: var(--fg-subtle); + font-size: var(--fs-small); +} + .unload { flex: none; } diff --git a/src/features/settings/pages/mcpServer.tsx b/src/features/settings/pages/mcpServer.tsx index 667ffde46..57e4f8923 100644 --- a/src/features/settings/pages/mcpServer.tsx +++ b/src/features/settings/pages/mcpServer.tsx @@ -1,10 +1,11 @@ /** Built-in MCP server status and client configurations. */ import { useEffect, useState } from "react"; import { commands, call, isTauri, onIdeEvent, type McpServerStatus } from "@/platform/ipc"; -import { backgroundProjectState, useBackgroundProjects } from "@/platform/mcpBackground"; +import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground"; import { basename, useProject } from "@/platform/project"; import { WORKFLOW_LIMITS } from "@/platform/workflowSettings"; import { useTx } from "@/platform/i18n"; +import { ProjectBadge } from "@/workbench/ProjectBadge"; import { useRemote } from "@/platform/remote"; import { Button, Input, T, copyText } from "@/ui"; import { GlobListEditor, Row, SettingNumber, SettingSelect } from "../components/Form"; @@ -233,7 +234,6 @@ function BackgroundOpenNow() { const projects = remote ? [] : loaded; const [mode] = useSetting("mcpServer.backgroundProjects"); const [enabled] = useSetting("mcpServer.enabled"); - const unload = (root: string) => void call(commands.mcpUnloadBackgroundProject(root)).catch(() => undefined); return ( {projects.map((project) => { - const name = basename(project.root); + const name = basename(project.root) || project.root; return (
  • +
    {name} - + {project.root} - {backgroundProjectState(project)} + {backgroundProjectState(project)}
    diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index f3c60fd8a..70d196419 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1739,6 +1739,13 @@ "Unload {path}": "Unload {path}", "Background projects are off": "Background projects are off", "A remote host serves only the project open in its window": "A remote host serves only the project open in its window", + "Served without a window": "Served without a window", + "Background Projects": "Background Projects", + "Background Projects: {count}": "Background Projects: {count}", + "Projects the MCP server holds open without a window": "Projects the MCP server holds open without a window", + "Open {path} in a new window": "Open {path} in a new window", + "Unload All": "Unload All", + "MCP Server Settings…": "MCP Server Settings…", "The MCP server is off": "The MCP server is off", "Archived ({count})": "Archived ({count})", "Insert": "Insert", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 58abb9a0f..fd3dbdb31 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8142,6 +8142,13 @@ "Unload {path}": "卸载 {path}", "Background projects are off": "后台项目已关闭", "A remote host serves only the project open in its window": "远程主机只为其窗口中打开的项目提供服务", + "Served without a window": "无窗口提供服务", + "Background Projects": "后台项目", + "Background Projects: {count}": "后台项目:{count}", + "Projects the MCP server holds open without a window": "MCP 服务器在没有窗口的情况下保持打开的项目", + "Open {path} in a new window": "在新窗口中打开 {path}", + "Unload All": "全部卸载", + "MCP Server Settings…": "MCP 服务器设置…", "The MCP server is off": "MCP 服务器已关闭", "Archived ({count})": "归档({count})", "Insert": "插入", diff --git a/src/platform/mcpBackground.ts b/src/platform/mcpBackground.ts index 7f3f6ca44..902f6a6d7 100644 --- a/src/platform/mcpBackground.ts +++ b/src/platform/mcpBackground.ts @@ -23,6 +23,11 @@ export function backgroundProjectState(project: McpBackgroundProject): string { return tx`Idle ${n} min, unloads in ${m} min`; } +/** Unloads one background project at once; one that is not loaded is already unloaded. */ +export function unloadBackgroundProject(root: string): void { + void call(commands.mcpUnloadBackgroundProject(root)).catch(() => undefined); +} + /** * The background projects, current: fetched on mount and when the backend reports a change, and every 30 s * while any is loaded, every 3 s while one answers a request (the end of a request and an idle project's diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index 1a202869b..d46d6eff0 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -312,6 +312,7 @@ const ICONS = { "page-first": "openidea/general/pageFirst", "page-last": "openidea/general/pageLast", sliders: "openidea/general/sliders", + layers: "openidea/general/layers", "graphql-variables": "openidea/general/graphqlVariables", layout: "general/layout", split: "general/splitVertically", diff --git a/src/ui/openidea/general/layers.svg b/src/ui/openidea/general/layers.svg new file mode 100644 index 000000000..103fcc627 --- /dev/null +++ b/src/ui/openidea/general/layers.svg @@ -0,0 +1,4 @@ + + + + diff --git a/src/workbench/ProjectBadge.module.css b/src/workbench/ProjectBadge.module.css new file mode 100644 index 000000000..882f72992 --- /dev/null +++ b/src/workbench/ProjectBadge.module.css @@ -0,0 +1,14 @@ +.badge { + display: flex; + flex: none; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border-radius: var(--radius-selection); + background: linear-gradient(135deg, var(--project-color), var(--project-color-end)); + color: var(--fg-button-primary); + font-size: var(--fs-tiny); + font-weight: 600; + letter-spacing: 0.02em; +} diff --git a/src/workbench/ProjectBadge.tsx b/src/workbench/ProjectBadge.tsx new file mode 100644 index 000000000..2396c8726 --- /dev/null +++ b/src/workbench/ProjectBadge.tsx @@ -0,0 +1,15 @@ +import { useSyncExternalStore } from "react"; +import clsx from "clsx"; +import { projectInitials } from "./projectColor"; +import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "./tabColors"; +import styles from "./ProjectBadge.module.css"; + +/** Square project avatar for a two-line row: the title bar widget's colour and initials. */ +export function ProjectBadge({ name, path, className }: { name: string; path: string; className?: string }) { + useSyncExternalStore(subscribeTabColors, tabColorsVersion); + return ( + + {projectInitials(name)} + + ); +} From 121e1fa5359ed86cebc1b7d725ee5386ea4b5344 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 02:51:47 +0800 Subject: [PATCH 12/15] fix(completion): fit the lookup to the editor and its font (#4566) The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size. --- e2e/codeInsight.spec.ts | 82 ++++++++++++++++++++++++++++++++++++ src/editor/lsp/completion.ts | 53 ++++++++++++++--------- src/editor/lsp/theme.ts | 53 ++++++++++++----------- 3 files changed, 143 insertions(+), 45 deletions(-) diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index b222fd919..cf711098c 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -65,6 +65,7 @@ test("completion lists the server's items and inserts the chosen one", async ({ const popup = page.locator(".cm-tooltip-autocomplete"); await expect(popup.getByText("total", { exact: true })).toBeVisible(); await expect(popup.getByText("toDto", { exact: true })).toBeVisible(); + expect((await popup.boundingBox())!.width).toBeLessThan(360); const field = popup.locator("li").filter({ has: page.locator(".cm-completionLabel", { hasText: /^total$/ }) }); await expect(field.locator(".cm-completionDetail")).toHaveCount(0); await expect(field.locator(".cm-lsp-type")).toHaveText("BigDecimal"); @@ -83,6 +84,17 @@ test("completion lists the server's items and inserts the chosen one", async ({ const label = await method.locator(".cm-completionLabel").boundingBox(); // Subpixel rounding differs per platform/font; a mis-set inset is a whole icon column off. expect(Math.abs(label!.x - wordStart)).toBeLessThanOrEqual(2); + const zoomedSize = await editor.locator(".cm-content").evaluate(async (content) => { + const viewModule = "/node_modules/.vite/deps/@codemirror_view.js"; + const prefsModule = "/src/editor/core/cm/prefs.ts"; + const { EditorView } = await import(/* @vite-ignore */ viewModule); + const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule); + const fontSize = Number.parseFloat(getComputedStyle(content).fontSize); + stepFontZoom(EditorView.findFromDOM(content as HTMLElement)!, 6); + return `${fontSize + 6}px`; + }); + await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize); + await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize); await page.keyboard.type("toD"); await expect(popup.getByText("total", { exact: true })).toBeHidden(); // Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top. @@ -98,6 +110,76 @@ test("completion lists the server's items and inserts the chosen one", async ({ expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0); }); +test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => { + const editor = await openSample(page); + const label = "transformOrder" + "AcrossParticipatingRegions".repeat(5); + await page.evaluate((label) => { + const item: CompletionItem = { + label, + labelDetail: "(order: Order, options: TransformationOptions)", + labelDescription: "Promise", + detail: `${label}(order: Order, options: TransformationOptions): Promise`, + kind: "method", + documentation: { kind: "markdown", value: "Transforms the order." }, + sortText: null, + filterText: null, + preselect: true, + deprecated: false, + insertText: `${label}()`, + isSnippet: false, + replaceRange: null, + replaceRangeTab: null, + additionalEdits: [], + commitCharacters: [], + command: null, + data: null, + server: 1, + }; + window.__ipc.handlers.lsp_completion = () => ({ isIncomplete: false, items: [item] }); + }, label); + await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click(); + await page.keyboard.press("End"); + await page.keyboard.press("Enter"); + await page.keyboard.type("order."); + await page.keyboard.press("Control+Space"); + + const popup = page.locator(".cm-tooltip-autocomplete"); + const option = popup.getByRole("option").filter({ + has: page.locator(".cm-completionLabel", { hasText: label }), + }); + await expect(option.locator(".cm-completionLabel")).toHaveText(label); + await page.setViewportSize({ width: 580, height: 900 }); + const bounds = (await editor.boundingBox())!; + await expect + .poll(async () => { + const box = (await popup.boundingBox())!; + return Math.max(bounds.x - box.x, box.x + box.width - (bounds.x + bounds.width)); + }) + .toBeLessThanOrEqual(2); + const geometry = await option.evaluate((row) => { + const label = row.querySelector(".cm-completionLabel")!; + const type = row.querySelector(".cm-lsp-type")!; + return { + nameTruncated: label.scrollWidth > label.clientWidth, + nameWidth: label.clientWidth, + typeWidth: type.clientWidth, + typeOverflow: type.getBoundingClientRect().right - row.getBoundingClientRect().right, + }; + }); + expect(geometry.nameTruncated).toBe(true); + expect(geometry.nameWidth).toBeGreaterThan(40); + expect(geometry.typeWidth).toBeGreaterThan(16); + expect(geometry.typeOverflow).toBeLessThanOrEqual(1); + + await page.keyboard.press("F1"); + await expect(popup.locator(".cm-completionInfo")).toContainText( + `${label}(order: Order, options: TransformationOptions)`, + ); + await page.keyboard.press("Enter"); + await expect(popup).toBeHidden(); + await expect(editor.locator(".cm-activeLine")).toContainText(`order.${label}()`); +}); + test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => { const editor = await openSample(page); await page.evaluate(async () => { diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index 4d0bc6ae4..6e8e9570b 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -25,7 +25,7 @@ import { type CompletionSource, } from "@codemirror/autocomplete"; import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state"; -import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view"; +import { EditorView, ViewPlugin, getTooltip, keymap, showTooltip, type Rect, type ViewUpdate } from "@codemirror/view"; import { call, commands, @@ -59,6 +59,8 @@ import { showHint } from "./hint"; import { inplaceRenameActive } from "./inplaceRename"; import { languageSemantics } from "./semantic"; import { remoteChange } from "@/editor/api"; +import { tooltipBounds } from "@/editor/core/cm/setup"; +import { completionLabelOffset } from "./theme"; interface RequestContext { doc: number; @@ -983,36 +985,45 @@ function sortToggle(view: EditorView): HTMLElement { return button; } -/** IDEA's advertiser bar under the list (one tip: "Press ↵ to insert, ⇥ to replace") and its Sort by Name toggle. */ -const completionFooter = ViewPlugin.fromClass( +const completionPopup = ViewPlugin.fromClass( class { constructor(private view: EditorView) {} update(u: ViewUpdate) { if (completionStatus(u.state) !== "active") return; this.view.requestMeasure({ - read: () => null, - write: () => { - const scope = this.view.dom.ownerDocument; - const tooltips = [ - ...this.view.dom.querySelectorAll(".cm-tooltip-autocomplete"), - ...scope.querySelectorAll(".cm-tooltip-autocomplete"), - ]; - for (const t of tooltips) { - let footer = t.querySelector(":scope > .cm-lsp-completion-footer"); - if (footer) { - // CodeMirror rebuilds the option list by appending a fresh
      , - // which would leave an existing footer above the list. - const list = t.querySelector(":scope > ul"); - if (list && list.nextElementSibling !== footer) list.after(footer); - continue; - } + key: this, + read: () => { + const { left, right } = tooltipBounds(this.view); + return { + width: `${Math.max(0, Math.floor(right - left))}px`, + fontSize: getComputedStyle(this.view.contentDOM).fontSize, + }; + }, + write: ({ width, fontSize }) => { + const popup = this.view.state + .facet(showTooltip) + .map((tooltip) => tooltip && getTooltip(this.view, tooltip)) + .find((tooltip) => tooltip?.dom.classList.contains("cm-lsp-completion")); + if (!popup) return; + // Apply the label alignment inside CodeMirror's viewport clamp. + popup.offset = { x: -completionLabelOffset, y: 0 }; + const t = popup.dom; + if (t.style.getPropertyValue("--cm-completion-max-width") !== width) + t.style.setProperty("--cm-completion-max-width", width); + // The body-level tooltip does not inherit the editor's temporary font zoom. + if (t.style.getPropertyValue("--openidea-editor-font-size") !== fontSize) + t.style.setProperty("--openidea-editor-font-size", fontSize); + let footer = t.querySelector(":scope > .cm-lsp-completion-footer"); + if (!footer) { footer = document.createElement("div"); footer.className = "cm-lsp-completion-footer"; const tip = document.createElement("span"); tip.textContent = tx("Press ↵ to insert, ⇥ to replace"); footer.append(tip, sortToggle(this.view)); - t.appendChild(footer); } + // CodeMirror appends a fresh list when the candidates change. + const list = t.querySelector(":scope > ul"); + if (list && list.nextElementSibling !== footer) list.after(footer); }, }); } @@ -1067,7 +1078,7 @@ export function completionExtension() { tooltipClass: () => "cm-lsp-completion", positionInfo: positionCompletionInfo, }), - completionFooter, + completionPopup, lookupTracker, serverInsertAt, caretAfterServerInsert, diff --git a/src/editor/lsp/theme.ts b/src/editor/lsp/theme.ts index 5cd4270d0..846df3f7a 100644 --- a/src/editor/lsp/theme.ts +++ b/src/editor/lsp/theme.ts @@ -10,19 +10,17 @@ const tooltipSurface = { color: "var(--fg)", }; -/** - * Row metrics that put a label one icon column right of the popup's left edge. They live on the - * popup as custom properties so every rule consuming them — including the popup's negative - * offset below — changes together. The remaining 1px is tooltipSurface's border, shared with - * the hover and signature tooltips. - */ +const completionInsets = { edge: 4, padding: 6, icon: 16, gap: 6 }; +export const completionLabelOffset = + 1 + completionInsets.edge + completionInsets.padding + completionInsets.icon + completionInsets.gap; + const completionRowMetrics = { // Rows grow with the editor font size (lookup text uses the editor font, as typed text does). "--cm-completion-row": "max(var(--h-list-row), calc(var(--openidea-editor-font-size, var(--fs-code)) * 1.7))", - "--cm-completion-edge": "4px", - "--cm-completion-inset": "6px", - "--cm-completion-icon": "16px", - "--cm-completion-gap": "6px", + "--cm-completion-edge": `${completionInsets.edge}px`, + "--cm-completion-inset": `${completionInsets.padding}px`, + "--cm-completion-icon": `${completionInsets.icon}px`, + "--cm-completion-gap": `${completionInsets.gap}px`, }; const markdown = { @@ -103,22 +101,19 @@ export const lspTheme = EditorView.theme({ fontFamily: "var(--openidea-editor-font, var(--font-mono))", fontWeight: "var(--fw-code, 400)", fontSize: "var(--openidea-editor-font-size, var(--fs-code))", - // CodeMirror anchors the popup at the completed word's start. Pull it left by one row's - // leading inset so the labels, not the icon column, sit on the text. CodeMirror's horizontal - // clamp measures the border box (margins excluded), so this offset sits outside its math: - // near the right edge it leaves that much extra space, and a word starting within one inset - // of the viewport's left edge would let the popup clip there. The normal editor layout - // (gutter + project sidebar) keeps the word well clear of that edge. - marginLeft: - "calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))", + display: "flex", + flexDirection: "column", + width: "max-content", + maxWidth: "min(720px, var(--cm-completion-max-width, 100vw))", // No overflow clipping: CodeMirror nests the documentation pane in this box and // positions it outside it (see `positionCompletionInfo`). The footer rounds itself. }, ".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": { fontFamily: "var(--openidea-editor-font, var(--font-mono))", fontWeight: "var(--fw-code, 400)", - minWidth: "420px", - maxWidth: "min(720px, 80vw)", + minWidth: "0", + maxWidth: "100%", + height: "auto", maxHeight: "calc(var(--cm-completion-row) * 11 + 8px)", padding: "4px 0", }, @@ -153,9 +148,15 @@ export const lspTheme = EditorView.theme({ alignItems: "center", justifyContent: "center", }, - ".cm-lsp-completion .cm-completionLabel": { flex: "none", overflow: "hidden", textOverflow: "ellipsis" }, + ".cm-lsp-completion .cm-completionLabel": { + flex: "0 1 auto", + minWidth: "0", + overflow: "hidden", + textOverflow: "ellipsis", + }, ".cm-lsp-completion .cm-completionDetail": { flex: "0 1 auto", + minWidth: "0", marginLeft: "0", fontStyle: "normal", color: "var(--fg-subtle)", @@ -172,7 +173,8 @@ export const lspTheme = EditorView.theme({ marginLeft: "calc(-1 * var(--cm-completion-gap))", }, ".cm-lsp-completion .cm-lsp-type": { - flex: "1 0 auto", + flex: "0 1 auto", + minWidth: "0", maxWidth: "60%", marginLeft: "auto", paddingLeft: "16px", @@ -188,18 +190,21 @@ export const lspTheme = EditorView.theme({ }, ".cm-lsp-completion-footer": { display: "flex", + flex: "none", + flexWrap: "wrap", alignItems: "center", padding: "5px 12px", backgroundColor: "var(--bg-popup-inline, var(--bg-elev))", color: "var(--fg-subtle)", fontFamily: "var(--font-ui)", fontSize: "var(--fs-small)", - whiteSpace: "nowrap", - gap: "12px", + gap: "var(--space-1) var(--space-3)", justifyContent: "space-between", borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)", }, ".cm-lsp-completion-sort": { + flex: "none", + maxWidth: "100%", padding: "0", border: "none", background: "none", From fd8f0eb99cfbaa9b760a0e5a4398b8e2680fa10f Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 02:52:46 +0800 Subject: [PATCH 13/15] fix(editor): make quick documentation fit narrow windows (#4568) Quick Documentation used a fixed 600px cap and kept its caret anchor after the window shrank, so short documents looked cramped and the actions could end up off screen. The popup now sizes to a 300-500px content width, keeps its actions together in the lower-right corner while the document scrolls, and clamps the anchor to the current viewport. --- e2e/quickDocumentationLayout.spec.ts | 73 ++++++++++++++++++++++++++++ src/editor/lsp/Popups.module.css | 19 +++++++- src/editor/lsp/Popups.tsx | 15 +++++- 3 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 e2e/quickDocumentationLayout.spec.ts diff --git a/e2e/quickDocumentationLayout.spec.ts b/e2e/quickDocumentationLayout.spec.ts new file mode 100644 index 000000000..19d33315b --- /dev/null +++ b/e2e/quickDocumentationLayout.spec.ts @@ -0,0 +1,73 @@ +import type { Page } from "@playwright/test"; +import { expect, openFromTree, stubDesktop, test } from "./fixtures"; + +async function quickDocumentation(page: Page, markdown: string) { + const editor = await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate((value) => { + window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null }); + }, markdown); + const line = editor.locator(".cm-line", { hasText: "return order.toDto()" }); + await line.click(); + await page.keyboard.press("End"); + await page.keyboard.press("ArrowLeft"); + await page.keyboard.press("ArrowLeft"); + await page.keyboard.press("ArrowLeft"); + await page.keyboard.press("F1"); + const popup = page.getByRole("dialog", { name: "Documentation", exact: true }); + await expect(popup.locator(".cm-lsp-markdown")).toBeVisible(); + return popup; +} + +test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => { + const popup = await quickDocumentation(page, "Returns the total."); + const back = popup.getByRole("button", { name: "Back", exact: true }); + const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" }); + await expect(dock).toBeVisible(); + const bounds = (await popup.boundingBox())!; + expect(bounds.width).toBeGreaterThanOrEqual(298); + expect(bounds.width).toBeLessThan(320); + const backBounds = (await back.boundingBox())!; + const dockBounds = (await dock.boundingBox())!; + expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2); + expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16); + await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px"); + await page.keyboard.press("Escape"); + await expect(popup).toBeHidden(); +}); + +test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => { + const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult"; + const markdown = [ + `\`\`\`kotlin\n${signature}\n\`\`\``, + ...Array.from({ length: 22 }, (_, i) => { + return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`; + }), + "End of pricing documentation.", + ].join("\n\n"); + const popup = await quickDocumentation(page, markdown); + const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" }); + await expect(dock).toBeVisible(); + expect((await popup.boundingBox())!.width).toBeLessThan(508); + await page.setViewportSize({ width: 430, height: 500 }); + await expect + .poll(async () => { + const box = (await popup.boundingBox())!; + return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500); + }) + .toBeLessThanOrEqual(1); + const body = popup.locator(".cm-lsp-markdown").locator(".."); + const last = popup.getByText("End of pricing documentation."); + const dockBefore = (await dock.boundingBox())!; + await expect(body.locator("pre")).toContainText(signature); + const scroll = await body.evaluate((node) => { + node.scrollTop = node.scrollHeight; + return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth }; + }); + expect(scroll.top).toBeGreaterThan(0); + expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1); + const lastBounds = (await last.boundingBox())!; + expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1); + expect(await dock.boundingBox()).toEqual(dockBefore); + await expect(dock).toBeInViewport(); +}); diff --git a/src/editor/lsp/Popups.module.css b/src/editor/lsp/Popups.module.css index e6eefb4d8..707f1921f 100644 --- a/src/editor/lsp/Popups.module.css +++ b/src/editor/lsp/Popups.module.css @@ -238,6 +238,10 @@ flex-direction: column; overflow: hidden; } +.docPopup:not([data-resized]) { + width: max-content; + min-width: min(300px, 90vw); +} .docScope { display: contents; } @@ -246,21 +250,32 @@ } .docPopup .docFrame { flex: 1 1 auto; + min-width: 0; min-height: 0; display: flex; flex-direction: column; } .docPopup:not([data-resized]) .docFrame { - max-width: min(600px, 90vw); - max-height: 420px; + max-width: min(500px, 90vw); + max-height: 500px; } .docPopup .docBody { flex: 1 1 auto; min-height: 0; overflow: auto; + overscroll-behavior: contain; + padding: var(--space-2) var(--space-4) var(--space-1); } .docPopup .docToolbar { + position: static; flex: none; + align-self: flex-end; + margin: 0 var(--space-2) var(--space-1); + padding: 0; + border: 0; +} +.docPopup .docToolbar .spacer { + display: none; } .docWindowFrame { height: 100%; diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx index 7a36b0aa8..fa8cb8a21 100644 --- a/src/editor/lsp/Popups.tsx +++ b/src/editor/lsp/Popups.tsx @@ -356,6 +356,19 @@ function DocPopup({ popup }: { popup: Extract }) { const focusSeq = useLspPopup((s) => s.focusSeq); const scope = useRef(null); const opened = useRef(focusSeq); + // The captured caret can end up outside the viewport while the popup is open. + const anchor = useMemo( + () => ({ + getBoundingClientRect: () => + new DOMRect( + Math.max(0, Math.min(popup.anchor.x, window.innerWidth)), + Math.max(0, Math.min(popup.anchor.y, window.innerHeight)), + 0, + 0, + ), + }), + [popup.anchor], + ); useEffect(() => { if (focusSeq !== opened.current) scope.current?.querySelector("[data-lsp-doc]")?.focus({ preventScroll: true }); @@ -364,7 +377,7 @@ function DocPopup({ popup }: { popup: Extract }) { return ( Date: Fri, 20 Nov 2026 02:53:44 +0800 Subject: [PATCH 14/15] fix(run): keep configuration names visible in narrow sidebars (#4573) A long run target could take the whole row in the Run/Debug Configurations sidebar, leaving the configuration name at zero width and forcing horizontal scrolling. Target labels now truncate in wide panes, narrow panes (container query) hide the muted target and scope, and the row tooltip carries the full name, target, scope and command. Type headings are semibold. --- e2e/runConfigLayout.spec.ts | 28 +++++++++++++++++++++++--- src/features/run/EditConfigsDialog.tsx | 15 +++++++++----- src/features/run/Run.module.css | 18 +++++++++++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/e2e/runConfigLayout.spec.ts b/e2e/runConfigLayout.spec.ts index 9c7ff7f70..fe6af50c8 100644 --- a/e2e/runConfigLayout.spec.ts +++ b/e2e/runConfigLayout.spec.ts @@ -1,8 +1,8 @@ import type { Page } from "@playwright/test"; import { expect, test } from "./fixtures"; -async function openConfigurations(page: Page) { - await page.evaluate(async () => { +async function openConfigurations(page: Page, target?: string) { + await page.evaluate(async (target) => { const path = "/src/features/run/store.ts"; const { useRun } = await import(/* @vite-ignore */ path); const base = { @@ -21,6 +21,7 @@ async function openConfigurations(page: Page) { ...base, id: "layout:app", name: "Payments development server", + target, beforeLaunch: [{ kind: "run", target: "layout:prepare" }], }, { ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" }, @@ -29,10 +30,31 @@ async function openConfigurations(page: Page) { loaded: true, editorOpen: true, }); - }); + }, target); await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible(); } +test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => { + const target = "payments-development-shared-staging-runner-west"; + await openConfigurations(page, target); + const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true }); + const tree = dialog.getByRole("tree", { name: "Run configurations", exact: true }); + const row = tree.getByRole("treeitem", { name: /^Payments development server/ }); + const name = row.getByText("Payments development server", { exact: true }); + const badge = row.getByText(`@ ${target}`, { exact: true }); + await expect(badge).toBeVisible(); + + for (const width of [1100, 520]) { + await page.setViewportSize({ width, height: 820 }); + await expect.poll(async () => (await name.boundingBox())!.width).toBeGreaterThan(width === 1100 ? 80 : 50); + await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + } + + await expect(badge).toBeHidden(); + await expect(row).toHaveAttribute("title", new RegExp(`Payments development server @ ${target}`)); + await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server"); +}); + test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({ workbench: page, }) => { diff --git a/src/features/run/EditConfigsDialog.tsx b/src/features/run/EditConfigsDialog.tsx index 6af849e4b..ea9b1d065 100644 --- a/src/features/run/EditConfigsDialog.tsx +++ b/src/features/run/EditConfigsDialog.tsx @@ -511,6 +511,7 @@ function EditConfigsDialog() { aria-expanded={!collapsed.has(r.key)} className={styles.editItem} style={{ paddingLeft: 6 }} + title={tx(r.label)} onClick={() => toggle(r.key)} onDragOver={(e) => e.preventDefault()} onDrop={(e) => onDrop(e, r.kind, null)} @@ -534,6 +535,7 @@ function EditConfigsDialog() { aria-expanded={!collapsed.has(r.key)} className={clsx(styles.editItem, sel && styles.editItemSelected)} style={{ paddingLeft: 22 }} + title={r.name} onClick={() => setSelection({ type: "folder", kind: r.kind, name: r.name })} onDoubleClick={() => toggle(r.key)} onDragOver={(e) => e.preventDefault()} @@ -547,6 +549,9 @@ function EditConfigsDialog() { } const c = r.config; const isTomcat = c.kind === "tomcat"; + const name = c.name || tx("Unnamed"); + const target = c.target ? targetName(c, runTargets) : null; + const scope = !c.detected && !isTomcat ? (c.local ? "local" : "user") : null; const tomcatNoArtifact = isTomcat && ((c.params?.deployment ?? "artifact") === "artifact" @@ -561,7 +566,9 @@ function EditConfigsDialog() { className={clsx(styles.editItem, current?.id === c.id && styles.editItemSelected)} style={{ paddingLeft: r.depth === 2 ? 50 : 34 }} onClick={() => setSelection({ type: "config", id: c.id })} - title={commandLine(c)} + title={[name + (target ? ` @ ${target}` : "") + (scope ? ` (${scope})` : ""), commandLine(c)] + .filter(Boolean) + .join("\n")} draggable onDragStart={(e) => { dragged.current = c.id; @@ -579,11 +586,9 @@ function EditConfigsDialog() { )} {c.name || Unnamed} - {c.target && @ {targetName(c, runTargets)}} + {target && @ {target}} {errorsById[c.id] && } - {!c.detected && !isTomcat && ( - {c.local ? "local" : "user"} - )} + {scope && {scope}} ); })} diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index 7a25c9a1a..b330f6e3e 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -553,6 +553,7 @@ flex: 1; } .editSidebar { + container: run-config-navigation / inline-size; min-height: 0; display: flex; flex-direction: column; @@ -596,6 +597,22 @@ background: var(--bg-selected-strong); color: var(--fg-strong); } +.editTarget { + flex: 0 1 auto; + min-width: 0; + max-width: 25%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.editItem .failed { + flex: none; +} +@container run-config-navigation (max-width: 220px) { + .editItem .chooserMuted { + display: none; + } +} .editForm { flex: 1; min-width: 0; @@ -701,6 +718,7 @@ } .editGroupName { color: var(--fg-strong); + font-weight: 600; } .editEmpty { flex: 1; From 5c2e7ff92af744ade504a78d750a8ac9b0092895 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 02:54:44 +0800 Subject: [PATCH 15/15] fix(editor): fit intention previews beside or below the list (#4578) The intention preview had a fixed 420px width beside the list, which pushed the action list away from the caret or got clipped in narrow windows. The preview now opens to the right when there is room, to the left when that keeps the list by the caret, and below the list in narrow windows. Preview code follows the editor's font settings and theme and wraps long lines. --- e2e/codeInsight.spec.ts | 79 ++++++++++++++++++++++++++++++++ src/editor/lsp/Popups.module.css | 44 +++++++++++++++--- src/editor/lsp/Popups.tsx | 66 ++++++++++++++++++++------ src/editor/lsp/intentions.ts | 1 + src/editor/lsp/popupStore.ts | 1 + 5 files changed, 171 insertions(+), 20 deletions(-) diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index cf711098c..d355298ad 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -498,6 +498,85 @@ test("indexed single-file rename previews all anchors and applies only after con expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] }); }); +test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1600, height: 900 }); + const editor = await openSample(page); + await page.evaluate(async () => { + const path = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ path); + const { settings } = useProject.getState(); + useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize: 16 } } }); + }); + await expect(editor.locator(".cm-content")).toHaveCSS("font-size", "16px"); + const replacement = "com.acme.orders." + "SharedDevelopmentOrderModel".repeat(6); + await page.evaluate( + ({ file, replacement, edit }) => { + window.__ipc.handlers.lsp_code_actions = () => [ + { + title: "Replace Order with the fully qualified shared development order model", + kind: "quickfix", + isPreferred: true, + disabledReason: null, + edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: replacement }] }] }, + command: null, + data: null, + server: 1, + }, + ...Array.from({ length: 11 }, (_, i) => ({ + title: `Create alternative Order model ${i + 1}`, + kind: "quickfix", + isPreferred: false, + disabledReason: null, + edit: null, + command: null, + data: null, + server: 1, + })), + ]; + window.__ipc.handlers.lsp_execute_code_action = () => []; + }, + { file: FILE, replacement, edit: range(20, 19, 24) }, + ); + await caretAt(editor, page, "val order: Order", "Order "); + await page.keyboard.press("Alt+Enter"); + const popup = page.getByRole("dialog", { name: "Intentions", exact: true }); + const options = popup.getByRole("listbox", { name: "Intentions" }); + const preview = popup.locator('[aria-label="Preview"]'); + await expect(preview.locator("pre")).toContainText(replacement); + const wide = (await options.boundingBox())!; + const widePreview = (await preview.boundingBox())!; + expect(widePreview.x).toBeGreaterThanOrEqual(wide.x + wide.width - 1); + + await page.setViewportSize({ width: 1050, height: 900 }); + await expect + .poll(async () => { + const list = (await options.boundingBox())!; + const code = (await preview.boundingBox())!; + return code.x + code.width - list.x; + }) + .toBeLessThanOrEqual(1); + + await page.setViewportSize({ width: 520, height: 540 }); + await expect + .poll(async () => { + const menu = (await popup.boundingBox())!; + const list = (await options.boundingBox())!; + const code = (await preview.boundingBox())!; + return { + popupFits: menu.x >= 0 && menu.y >= 0 && menu.x + menu.width <= 521 && menu.y + menu.height <= 541, + previewBelow: code.y >= list.y + list.height - 1, + previewFits: code.x >= menu.x && code.x + code.width <= menu.x + menu.width + 1, + }; + }) + .toEqual({ popupFits: true, previewBelow: true, previewFits: true }); + expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await expect(preview.locator("pre")).toHaveCSS("font-size", "16px"); + await expect(options).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(popup).toBeHidden(); + await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1); +}); + test("diagnostics underline the range and ⌥⏎ applies the preferred quick fix", async ({ workbench: page }) => { const editor = await openSample(page); await page.evaluate( diff --git a/src/editor/lsp/Popups.module.css b/src/editor/lsp/Popups.module.css index 707f1921f..a3215c0bf 100644 --- a/src/editor/lsp/Popups.module.css +++ b/src/editor/lsp/Popups.module.css @@ -30,8 +30,7 @@ } .withPreview { flex-direction: row; - width: auto; - max-width: min(1160px, 94vw); + min-width: 0; } .listMain { display: flex; @@ -39,6 +38,11 @@ min-width: 0; flex: none; } +.withPreview .listMain { + flex: 1 1 320px; + min-width: 300px; + min-height: 0; +} .mnemonic { width: 10px; flex: none; @@ -48,14 +52,39 @@ text-align: right; } .previewPanel { - width: 420px; - flex: none; + flex: 0 1 var(--list-preview-width); + min-width: 300px; min-height: 60px; - max-height: 340px; + max-height: 300px; overflow: auto; border-left: 1px solid var(--border-popup); background: var(--bg-popup-inline, var(--bg-elev)); } +.previewLeft { + flex-direction: row-reverse; +} +.previewLeft .previewPanel { + border-left: 0; + border-right: 1px solid var(--border-popup); +} +.previewBelow { + flex-direction: column; +} +.previewBelow .listMain { + flex: 0 1 auto; + min-width: 0; +} +.previewBelow .previewPanel { + flex: 0 1 auto; + min-width: 0; + min-height: 0; + max-height: min(300px, 40vh); + border-left: 0; + border-top: 1px solid var(--border-popup); +} +.previewBelow .previewPanel[aria-busy] { + height: 60px; +} .previewText { padding: 8px 10px; font-size: var(--fs-small); @@ -66,12 +95,13 @@ padding: 6px 0; font-family: var(--openidea-editor-font, var(--font-mono)); font-weight: var(--fw-code); - font-size: var(--fs-small); + font-size: var(--openidea-editor-font-size, var(--fs-code)); color: var(--fg-editor); } .diffLine { padding: 0 10px; - white-space: pre; + white-space: pre-wrap; + overflow-wrap: anywhere; min-height: 1.4em; } .diff-added { diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx index fa8cb8a21..2fe99609d 100644 --- a/src/editor/lsp/Popups.tsx +++ b/src/editor/lsp/Popups.tsx @@ -1,5 +1,5 @@ /** React popups for LSP editor features, rendered as a workbench overlay. */ -import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; +import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react"; import clsx from "clsx"; import { Checkbox, @@ -49,11 +49,17 @@ function ItemIcon({ item }: { item: ListPopupItem }) { return ; } -function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading" }) { +function ListPreviewPanel({ + preview, + themeClasses, +}: { + preview: ListPreview | null | "loading"; + themeClasses?: string; +}) { if (preview === "loading") return
      ; if (!preview) return null; return ( -
      +
      {preview.kind === "text" ? (
      {preview.text}
      ) : ( @@ -70,6 +76,9 @@ function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading" ); } +const LIST_PREVIEW_WIDTH = 420; +const MIN_SIDE_BY_SIDE_WIDTH = 660; + function ListPopup({ popup }: { popup: Extract }) { const [query, setQuery] = useState(""); const filtered = useMemo(() => { @@ -91,6 +100,13 @@ function ListPopup({ popup }: { popup: Extract }) { const [preview, setPreview] = useState<{ id: string; data: ListPreview | null } | null>(null); const fetchPreview = popup.preview; + const [viewportWidth, setViewportWidth] = useState(() => window.innerWidth); + useEffect(() => { + if (!fetchPreview) return; + const resize = () => setViewportWidth(window.innerWidth); + window.addEventListener("resize", resize); + return () => window.removeEventListener("resize", resize); + }, [fetchPreview]); useEffect(() => { if (!fetchPreview || !activeItem || activeItem.disabled) return; const ctrl = new AbortController(); @@ -164,22 +180,46 @@ function ListPopup({ popup }: { popup: Extract }) { ? ("loading" as const) : null : null; + const hasPreview = shownPreview !== null; + const previewBelow = hasPreview && viewportWidth <= MIN_SIDE_BY_SIDE_WIDTH; + const previewLeft = + hasPreview && + !previewBelow && + popup.anchor.x + width + LIST_PREVIEW_WIDTH > viewportWidth - 6 && + popup.anchor.x >= LIST_PREVIEW_WIDTH + 6; + const anchor = useMemo(() => { + if (!fetchPreview) return popup.anchor; + const x = popup.anchor.x - (previewLeft ? LIST_PREVIEW_WIDTH : 0); + return { + getBoundingClientRect: () => + new DOMRect( + Math.max(0, Math.min(x, window.innerWidth)), + Math.max(0, Math.min(popup.anchor.y, window.innerHeight)), + 0, + 0, + ), + }; + }, [fetchPreview, popup.anchor, previewLeft]); + const popupSize = { + width: hasPreview ? width + LIST_PREVIEW_WIDTH : width, + "--list-preview-width": `${LIST_PREVIEW_WIDTH}px`, + } as CSSProperties; const indexOf = (item: ListPopupItem) => popup.items.indexOf(item); return ( -
      +
      {popup.title} {popup.busy && } @@ -260,7 +300,7 @@ function ListPopup({ popup }: { popup: Extract }) { />
      - {popup.preview && } + {popup.preview && } {sub?.item.submenu && ( { dismissed = true; }, diff --git a/src/editor/lsp/popupStore.ts b/src/editor/lsp/popupStore.ts index 93ea33c08..2402517c0 100644 --- a/src/editor/lsp/popupStore.ts +++ b/src/editor/lsp/popupStore.ts @@ -104,6 +104,7 @@ export type LspPopup = pin?: { label: string; run: () => void }; /** Side panel for the selected row, fetched lazily; `signal` aborts when the selection moves. */ preview?: (item: ListPopupItem, signal: AbortSignal) => Promise; + themeClasses?: string; /** Runs when the popup goes away (closed, replaced or a row ran). */ onClose?: () => void; }