From 9943d71d0277f56e7a6257076ad9b7ca26355910 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 18:40:25 +0900 Subject: [PATCH 01/66] fix(editor): show no diagnostics in library sources (#6946) Language servers publish errors for files they generate or read outside the project (sourcekit-lsp parse errors in its .swiftinterface). Library sources open read-only, so their diagnostics are dropped from the editor and the Problems view. Closes #6943 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/editor/lsp/diagnostics.test.ts | 16 +++++++++++++++- src/editor/lsp/diagnostics.ts | 5 ++++- src/features/code-insight/problemsStore.test.ts | 13 +++++++++++++ src/features/code-insight/problemsStore.ts | 3 +++ 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/editor/lsp/diagnostics.test.ts b/src/editor/lsp/diagnostics.test.ts index ea82fca10..4f444c1f9 100644 --- a/src/editor/lsp/diagnostics.test.ts +++ b/src/editor/lsp/diagnostics.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { EditorState, Text } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { viewShown, type EditorDocContext } from "@/editor/api"; +import { setLibraryRoots, viewShown, type EditorDocContext } from "@/editor/api"; import { lspDoc } from "./lsp"; import type { Diagnostic } from "@/bindings"; import { @@ -60,6 +60,20 @@ describe("editor diagnostics store", () => { expect(calls).toBe(3); off(); }); + it("keeps no diagnostics for library sources", () => { + const dispose = setLibraryRoots("test", ["/sdk"]); + const stop = installDiagnosticsEvents(); + emitLocalIdeEvent({ + type: "diagnostics", + path: "/sdk/Swift.String.swiftinterface", + source: "sk", + items: [d(0, 0, 1)], + }); + setFileDiagnostics("/sdk/Swift.String.swiftinterface", "local", [d(1, 0, 1)]); + expect(diagnosticsFor("/sdk/Swift.String.swiftinterface")).toEqual([]); + stop(); + dispose(); + }); }); describe("toLintDiagnostics", () => { diff --git a/src/editor/lsp/diagnostics.ts b/src/editor/lsp/diagnostics.ts index f11e53065..acf69f370 100644 --- a/src/editor/lsp/diagnostics.ts +++ b/src/editor/lsp/diagnostics.ts @@ -12,7 +12,7 @@ import type { Diagnostic, Severity } from "@/bindings"; import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { publishLocalDiagnostics } from "@/platform/localDiagnostics"; -import { intentionsChanged, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api"; +import { intentionsChanged, isLibraryPath, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api"; import { rangeToOffsets } from "./positions"; import { lspDoc } from "./lsp"; import { showHint } from "./hint"; @@ -54,6 +54,9 @@ export function setFileDiagnostics(path: string, source: string, items: Diagnost } function storeDiagnostics(path: string, source: string, items: Diagnostic[], published = false) { + // A library source opens read-only: errors a server reports in it (an SDK interface it + // generated, a dependency's code) are not the user's to fix. + if (isLibraryPath(path)) items = []; let sources = byPath.get(path); if (!items.length) { if (!sources?.delete(source) && !published) return; diff --git a/src/features/code-insight/problemsStore.test.ts b/src/features/code-insight/problemsStore.test.ts index 8bd0440c5..e145e9f8a 100644 --- a/src/features/code-insight/problemsStore.test.ts +++ b/src/features/code-insight/problemsStore.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it } from "vitest"; import type { Diagnostic } from "@/bindings"; +import { setLibraryRoots } from "@/editor/api"; import { useProject } from "@/platform/project"; import { applyDiagnosticsEvent, @@ -300,3 +301,15 @@ describe("incremental bookkeeping", () => { } }); }); + +describe("library sources", () => { + beforeEach(() => clearProblems()); + + it("are not the project's problems", () => { + const dispose = setLibraryRoots("test", ["/sdk"]); + applyDiagnosticsEvent("/sdk/Foundation.swiftinterface", "sk", [d(1)]); + applyDiagnosticsEvent("/p/main.swift", "sk", [d(2)]); + expect([...useProblems.getState().map.keys()]).toEqual(["/p/main.swift"]); + dispose(); + }); +}); diff --git a/src/features/code-insight/problemsStore.ts b/src/features/code-insight/problemsStore.ts index 23c00e712..369e3c64e 100644 --- a/src/features/code-insight/problemsStore.ts +++ b/src/features/code-insight/problemsStore.ts @@ -5,6 +5,7 @@ */ import { create } from "zustand"; import type { Diagnostic, Severity } from "@/bindings"; +import { isLibraryPath } from "@/editor/api"; import { onIdeEvent } from "@/platform/ipc"; import { onLocalDiagnostics } from "@/platform/localDiagnostics"; import { @@ -256,6 +257,8 @@ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items } export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) { + // Library sources (an SDK interface, a dependency's code) are not the project's problems. + if (isLibraryPath(path)) items = []; useProblems.setState((s) => { // The file's sources map is replaced, not changed, so this is the list before the event. const before = mergedSources(s.map.get(path)); From 695424beb2c52dbf17e7fccf885dd266a09a919a Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 18:40:41 +0900 Subject: [PATCH 02/66] fix(editor): reopen restored library source tabs read-only (#6950) The library-source mark lived only in memory, so a tab restored after a reload opened the same file editable. The editor session now saves the mark and restores it before the documents open. Closes #6947 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/editor/api.ts | 5 +++++ src/editor/core/controller.ts | 15 +++++++++++++-- src/editor/core/model/session.test.ts | 12 ++++++++++++ src/editor/core/model/session.ts | 20 +++++++++++++++++++- 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/editor/api.ts b/src/editor/api.ts index 037549468..327c248f9 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -918,6 +918,11 @@ function outsideProject(path: string): boolean { /** Files outside the project that code navigation opened: library sources, shown read-only. */ const navigatedLibraryFiles = new Set(); +/** Marks `path` as a library source again, for a tab restored from a saved session. */ +export function markLibraryFile(path: string): void { + navigatedLibraryFiles.add(path); +} + /** * Opens a code location a language server or the index answered (a declaration, an * implementation, a documentation link) and selects `selection`. A file outside the project is a diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 5a61b0609..58143168b 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -21,6 +21,8 @@ import { _provideOpenEditorPaths, _setActiveEditor, focusedCellEditor, + isLibraryPath, + markLibraryFile, shownLine, type NavigationLocation, } from "@/editor/api"; @@ -114,7 +116,14 @@ import { import { EditorSlot, type SlotHost } from "./model/slot"; import { NavigationHistory } from "./model/navHistory"; import { EditHistory } from "./model/editHistory"; -import { loadSession, restoreTabsState, serializeSession, storeSession, type FileViewState } from "./model/session"; +import { + loadSession, + restoreTabsState, + serializeSession, + sessionLibraryFiles, + storeSession, + type FileViewState, +} from "./model/session"; import { docBackend, type DocBackend } from "./backend"; import { isClassFile } from "@/platform/classFiles"; import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs"; @@ -663,7 +672,7 @@ export class EditorController implements SlotHost { const kinds = useContributions.getState().editorKinds; storeSession( root, - serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable), + serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable, isLibraryPath), ); } @@ -700,6 +709,8 @@ export class EditorController implements SlotHost { if (this.forgottenSessions.delete(root)) return; const session = loadSession(root); if (!session) return; + // Before the documents open: a library source opens read-only. + for (const path of sessionLibraryFiles(session)) markLibraryFile(path); const state = restoreTabsState(session, fileKey); const kinds = useContributions.getState().editorKinds; for (const pane of Object.values(state.panes)) diff --git a/src/editor/core/model/session.test.ts b/src/editor/core/model/session.test.ts index 3e0be06c5..8553cc87a 100644 --- a/src/editor/core/model/session.test.ts +++ b/src/editor/core/model/session.test.ts @@ -14,6 +14,7 @@ import { parseSession, restoreTabsState, serializeSession, + sessionLibraryFiles, slashPath, storeSession, type EditorSession, @@ -59,6 +60,17 @@ describe("editor session", () => { expect(r.layout).toMatchObject({ kind: "split", dir: "column" }); }); + it("remembers which file tabs are library sources", () => { + let s = initialTabsState(); + s = open(s, "/p/main.swift"); + s = open(s, "/tmp/sk/Swift.String.swiftinterface"); + const library = (path: string) => path.endsWith(".swiftinterface"); + const session = serializeSession(s, {}, undefined, library)!; + const parsed = parseSession(JSON.parse(JSON.stringify(session)))!; + expect(sessionLibraryFiles(parsed)).toEqual(["/tmp/sk/Swift.String.swiftinterface"]); + expect(sessionLibraryFiles(parseSession(JSON.parse(JSON.stringify(serializeSession(s, {})!)))!)).toEqual([]); + }); + it("saves tabs of restorable editor kinds with their input", () => { let s = initialTabsState(); s = open(s, "/p/a.ts"); diff --git a/src/editor/core/model/session.ts b/src/editor/core/model/session.ts index ee0e142cf..47ea943dc 100644 --- a/src/editor/core/model/session.ts +++ b/src/editor/core/model/session.ts @@ -18,6 +18,8 @@ export interface SessionTab { input?: EditorInput; pinned?: boolean; preview?: boolean; + /** A library source (read-only), e.g. an SDK interface code navigation opened outside the project. */ + library?: boolean; } export type SessionLayout = @@ -43,11 +45,15 @@ const STORAGE_PREFIX = "openidea.editorSession.v1:"; const isFileTab = (t: Tab) => t.input.kind === "file" && !!t.input.path; -/** `restorable`: whether a non-file tab is saved (its kind asked for it). */ +/** + * `restorable`: whether a non-file tab is saved (its kind asked for it). `library`: whether a + * file tab shows a library source, so it opens read-only again. + */ export function serializeSession( s: TabsState, files: Record, restorable: (input: EditorInput) => boolean = () => false, + library: (path: string) => boolean = () => false, ): EditorSession | null { const saved = (t: Tab) => isFileTab(t) || (t.input.kind !== "file" && restorable(t.input)); const walk = (n: LayoutNode): SessionLayout | null => { @@ -66,6 +72,7 @@ export function serializeSession( ...(isFileTab(t) ? { path: t.input.path! } : { input: { ...t.input } }), ...(t.pinned ? { pinned: true } : {}), ...(t.preview ? { preview: true } : {}), + ...(isFileTab(t) && library(t.input.path!) ? { library: true } : {}), })), active, }; @@ -151,6 +158,17 @@ export function parseSession(raw: unknown): EditorSession | null { }; } +/** Paths of the file tabs saved as library sources. */ +export function sessionLibraryFiles(session: EditorSession): string[] { + const out: string[] = []; + const walk = (l: SessionLayout) => + l.kind === "pane" + ? l.tabs.forEach((t) => t.library === true && t.path && out.push(t.path)) + : l.children.forEach(walk); + walk(session.layout); + return out; +} + let seq = 0; const id = (p: string) => `${p}r${++seq}`; From edd67464397a1d96a924b61245eea831851051f4 Mon Sep 17 00:00:00 2001 From: Waiting-Night <53596273+wangyuewen-china@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:40:54 +0800 Subject: [PATCH 03/66] fix(editor): stop type hierarchy searches from library gutter markers (#6951) Library gutter markers asked jdtls for inheritors of every visible class, which on a JDK interface ran a full type hierarchy search and timed out. Library sources keep super-method markers but ask for no inheritors; Go to Implementation still answers. Co-authored-by: wangyuewen-china <53596273+wangyuewen-china@users.noreply.github.com> --- src/editor/navigation/implementationGutter.ts | 11 +++++++---- src/editor/navigation/lineMarkers.test.ts | 16 ++++++++++------ 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/editor/navigation/implementationGutter.ts b/src/editor/navigation/implementationGutter.ts index 84b4bca35..5116d6de4 100644 --- a/src/editor/navigation/implementationGutter.ts +++ b/src/editor/navigation/implementationGutter.ts @@ -13,7 +13,8 @@ * The cache outlives the editor view (switching tabs remounts it) until other * files change, a language server settles or its classpath changes: on some servers (jdtls) every * implementation search walks the whole workspace, so asking again is costly. - * Library sources ask no inheritors from the server (`isLibrarySource`). + * Library sources ask no inheritors from the server (`isLibrarySource`); explicit + * Go to Implementation still answers. */ import { RangeSet, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state"; import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view"; @@ -826,11 +827,13 @@ class MarkersPlugin { } /** - * In a library every method's overriders would be searched for across the whole project, - * one search per visible method: only its classes and interfaces get ↓ markers. + * Library symbols are referenced everywhere, so an inheritor search walks the whole + * project and its dependencies (jdtls builds a full type hierarchy). A JDK interface + * such as `java.util.function.Function` then keeps the status bar at "Creating type + * hierarchy" and times out. Keep super-method markers, but ask for no inheritors. */ export function libraryCandidates(candidates: readonly MarkerCandidate[]): MarkerCandidate[] { - return candidates.map((c) => (c.method && c.inheritable ? { ...c, inheritable: false } : c)); + return candidates.map((c) => ({ ...c, inheritable: false, implicit: false })); } /** LSP access for one pass: this document's outline as known, others' opened on demand, each asked once. */ diff --git a/src/editor/navigation/lineMarkers.test.ts b/src/editor/navigation/lineMarkers.test.ts index e11ee7d07..a04c75768 100644 --- a/src/editor/navigation/lineMarkers.test.ts +++ b/src/editor/navigation/lineMarkers.test.ts @@ -517,18 +517,22 @@ describe("library sources", () => { [`${SHAPE_PATH}:1`]: [loc("/p/Circle.java", 2, 18), loc("/p/Square.java", 1, 18)], }; - it("ask for the inheritors of types only, not one project-wide search per method", async () => { + it("ask for no inheritors: a library type's search walks the whole project and its dependencies", async () => { const { deps, calls } = server(shapeImpls, {}); const candidates = libraryCandidates(markerCandidates(SHAPE_OUTLINE, lines(SHAPE))); const cache = emptyCache(); await fillMarkers(SHAPE_PATH, candidates, ALL, deps(SHAPE_PATH), cache); - expect(calls.implementations).toEqual([[{ line: 0, col: 17 }]]); - expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.tooltip])).toEqual([ - [0, "implemented", "Is implemented by Circle, Square"], - ]); + expect(calls.implementations).toEqual([]); + expect(calls.subtypes).toBe(0); + expect(cachedMarkers(candidates, ALL, cache)).toEqual([]); }); - it("still ask the server for inheritors and subtypes", async () => { + it("also drops Go's implicit interface queries", () => { + const candidates = libraryCandidates(markerCandidates(GO_OUTLINE, lines(GO), { implicitInterfaces: true })); + expect(candidates.some((c) => c.inheritable || c.implicit)).toBe(false); + }); + + it("keeps super-method queries available without enabling inheritor searches", async () => { const off = setLibraryRoots("test", ["/venv/site-packages"]); try { const library = { From 08249ca5fdd7094e18eafd451c42e81b85574e24 Mon Sep 17 00:00:00 2001 From: Jimmy Song <44343516+zhiai007@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:41:09 +0800 Subject: [PATCH 04/66] fix(viewers): reload preview images when files change on disk (#6952) Preview image data URLs were cached by path forever. The cache now drops entries on fsChanged and open Markdown and reStructuredText previews reload the affected images. Co-authored-by: zhiai007 <44343516+zhiai007@users.noreply.github.com> --- .../viewers/markdown/MarkdownEditor.tsx | 43 ++- src/features/viewers/previewImages.test.tsx | 306 ++++++++++++++++++ src/features/viewers/previewImages.ts | 95 +++++- src/features/viewers/rst/RstEditor.tsx | 30 +- 4 files changed, 445 insertions(+), 29 deletions(-) create mode 100644 src/features/viewers/previewImages.test.tsx diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index 12f75cb62..4bea6bb43 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -85,7 +85,7 @@ import { wheelZoomStep } from "@/platform/wheelZoom"; import { iconNode } from "@/ui/iconNode"; import { isMarkdownPath } from "../fileKinds"; import { attachPanZoom } from "../panZoom"; -import { imageUrl } from "../previewImages"; +import { createPreviewImageLoader } from "../previewImages"; /** * Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved @@ -480,7 +480,18 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s let live = true; const size = (img: HTMLImageElement, intrinsic?: { w: number; h: number } | null) => applyImageZoomWidth(img, intrinsic, img.closest(`.${IMAGE_ZOOM}`) ?? img); + const resetImageSize = (img: HTMLImageElement) => { + const box = img.closest(`.${IMAGE_ZOOM}`) ?? img; + delete img.dataset.naturalWidth; + delete box.dataset.naturalWidth; + box.style.removeProperty("--image-width"); + }; const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => { + const changed = img.getAttribute("src") !== url; + if (changed && img.hasAttribute("src")) { + resetImageSize(img); + size(img); + } const svgSize = svgDataUrlSize(url); if (svgSize && size(img, svgSize) && asyncLoad) { setDiagramsDrawn((n) => n + 1); @@ -495,11 +506,31 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s setDiagramsDrawn((n) => n + 1); } }; - if (img.getAttribute("src") !== url) img.src = url; - if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) { + if (changed) img.src = url; + // Only trust synchronous naturalWidth when `src` did not change: right after assigning a new `src`, + // browsers still report the previous image's `complete` / `naturalWidth` until the new decode finishes. + if ( + !changed && + !img.hasAttribute("data-natural-width") && + img.complete && + img.naturalWidth > 0 && + img.naturalHeight > 0 + ) { size(img, { w: img.naturalWidth, h: img.naturalHeight }); } }; + const images = createPreviewImageLoader( + (img, url) => { + img.classList.remove(styles.blocked!); + bindImageUrl(img, url, true); + }, + (img) => { + resetImageSize(img); + img.removeAttribute("src"); + img.classList.add(styles.blocked!); + setDiagramsDrawn((n) => n + 1); + }, + ); const imgs = [...root.querySelectorAll("img[data-src]")]; imgs.forEach((img) => { attachImagePanZoom(img); @@ -515,10 +546,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s img.title = "Remote images are not loaded"; return; } - imageUrl(target.path).then( - (url) => live && bindImageUrl(img, url, true), - () => live && img.classList.add(styles.blocked!), - ); + images.load(img, target.path); }); root.querySelectorAll("pre > code").forEach((code) => { const pre = code.parentElement!; @@ -531,6 +559,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s }); return () => { live = false; + images.dispose(); for (const img of imgs) img.onload = null; }; }, [html, path]); diff --git a/src/features/viewers/previewImages.test.tsx b/src/features/viewers/previewImages.test.tsx new file mode 100644 index 000000000..2d6d31bb7 --- /dev/null +++ b/src/features/viewers/previewImages.test.tsx @@ -0,0 +1,306 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; +import { Text } from "@codemirror/state"; +import * as ipc from "@/platform/ipc"; +import { emitLocalIdeEvent } from "@/platform/ipc"; +import { useLiveMarkdown } from "./markdown/live"; +import { MarkdownEditor } from "./markdown/MarkdownEditor"; +import { useMarkdownModes } from "./markdown/modes"; +import { imageUrl } from "./previewImages"; +import { useLiveRst } from "./rst/live"; +import { RstEditor } from "./rst/RstEditor"; +import { rstModes } from "./rst/RstLayoutActions"; + +const svgUrl = (width: number, height: number) => + `data:image/svg+xml;base64,${btoa(``)}`; + +const liveDoc = (lines: string[]) => ({ + text: Text.of(lines), + topLine: 0, + sourceAtEnd: false, + scrollSeq: 0, + fontZoom: 0, + previewTop: 0, + caretLine: 0, + caretSeq: 0, +}); + +describe("preview image disk refresh", () => { + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + }); + + beforeEach(() => { + localStorage.clear(); + useMarkdownModes.setState({ byTab: {}, fallback: "split" }); + rstModes.useModes.setState({ byTab: {}, fallback: "split" }); + useLiveMarkdown.setState({}, true); + useLiveRst.setState({}, true); + }); + + it("evicts cached image URLs on file and parent-directory fsChanged without dropping unrelated paths", async () => { + let version = 1; + const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => ({ + status: "ok", + data: `data:image/png;base64,${path}:v${version}`, + })); + + const a1 = await imageUrl("/p/cache/a.png"); + const b1 = await imageUrl("/p/cache/b.png"); + const dirImg1 = await imageUrl("/p/cache/assets/diagram.png"); + expect(await imageUrl("/p/cache/a.png")).toBe(a1); + expect(fsReadImage).toHaveBeenCalledTimes(3); + + version = 2; + emitLocalIdeEvent({ + type: "fsChanged", + created: [], + modified: ["/p/cache/a.png"], + removed: [], + }); + + expect(await imageUrl("/p/cache/a.png")).toBe("data:image/png;base64,/p/cache/a.png:v2"); + expect(await imageUrl("/p/cache/b.png")).toBe(b1); + expect(fsReadImage).toHaveBeenCalledTimes(4); + + version = 3; + emitLocalIdeEvent({ + type: "fsChanged", + created: ["/p/cache/assets"], + modified: [], + removed: [], + }); + + expect(await imageUrl("/p/cache/assets/diagram.png")).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v3"); + expect(dirImg1).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v1"); + expect(await imageUrl("/p/cache/b.png")).toBe(b1); + }); + + it("keeps a newer reload when an earlier in-flight read rejects or resolves late", async () => { + const imgPath = "/p/md-race/shot.png"; + const mdPath = "/p/md-race/README.md"; + const resolvers: Array<{ resolve: (v: { status: "ok"; data: string }) => void; reject: (e: Error) => void }> = []; + + vi.spyOn(ipc.commands, "fsReadImage").mockImplementation( + () => + new Promise((resolve, reject) => { + resolvers.push({ resolve, reject }); + }), + ); + + useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" }); + useLiveMarkdown.setState({ [mdPath]: liveDoc(["![Shot](./shot.png)"]) }); + + render( + +
+ , + ); + + await waitFor(() => expect(resolvers).toHaveLength(1)); + + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] }); + }); + await waitFor(() => expect(resolvers).toHaveLength(2)); + + act(() => { + resolvers[1]!.resolve({ status: "ok", data: "data:image/png;base64,FRESH" }); + }); + + const preview = screen.getByRole("document", { name: "Markdown preview" }); + await waitFor(() => { + expect(preview.querySelector('img[alt="Shot"]')?.getAttribute("src")).toBe( + "data:image/png;base64,FRESH", + ); + }); + + act(() => { + resolvers[0]!.reject(new Error("stale read failed")); + }); + await act(async () => {}); + + expect(preview.querySelector('img[alt="Shot"]')?.getAttribute("src")).toBe( + "data:image/png;base64,FRESH", + ); + expect(await imageUrl(imgPath)).toBe("data:image/png;base64,FRESH"); + }); + + it("reloads Markdown preview images on fsChanged, updates dimensions, and recovers after removal", async () => { + const imgPath = "/p/md-reload/diagram.svg"; + const mdPath = "/p/md-reload/README.md"; + let current: string | null = svgUrl(320, 180); + + vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => { + if (path === imgPath && current !== null) return { status: "ok", data: current }; + return { status: "error", error: { kind: "notFound", message: path } } as never; + }); + + useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" }); + useLiveMarkdown.setState({ [mdPath]: liveDoc(["![Diagram](./diagram.svg)"]) }); + + render( + +
+ , + ); + + const preview = screen.getByRole("document", { name: "Markdown preview" }); + await waitFor(() => { + const img = preview.querySelector('img[alt="Diagram"]'); + expect(img?.getAttribute("src")).toBe(svgUrl(320, 180)); + }); + + const img = preview.querySelector('img[alt="Diagram"]')!; + const box = img.closest(".image-zoom") ?? img; + expect(box.style.getPropertyValue("--image-width")).toBe("320px"); + + current = svgUrl(640, 240); + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] }); + }); + + await waitFor(() => { + expect(img.getAttribute("src")).toBe(svgUrl(640, 240)); + expect(box.style.getPropertyValue("--image-width")).toBe("640px"); + }); + + current = null; + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] }); + }); + + await waitFor(() => { + expect(img.getAttribute("src")).toBeNull(); + expect(img.hasAttribute("data-natural-width")).toBe(false); + expect(box.style.getPropertyValue("--image-width")).toBe(""); + }); + + current = svgUrl(480, 200); + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] }); + }); + + await waitFor(() => { + expect(img.getAttribute("src")).toBe(svgUrl(480, 200)); + expect(box.style.getPropertyValue("--image-width")).toBe("480px"); + }); + }); + + it("updates raster image width on reload even when old naturalWidth is still reported synchronously", async () => { + const imgPath = "/p/md-raster/shot.png"; + const mdPath = "/p/md-raster/README.md"; + let current = "data:image/png;base64,V1"; + + vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => { + if (path === imgPath) return { status: "ok", data: current }; + return { status: "error", error: { kind: "notFound", message: path } } as never; + }); + + useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" }); + useLiveMarkdown.setState({ [mdPath]: liveDoc(["![Shot](./shot.png)"]) }); + + render( + +
+ , + ); + + const preview = screen.getByRole("document", { name: "Markdown preview" }); + await waitFor(() => { + expect(preview.querySelector('img[alt="Shot"]')?.getAttribute("src")).toBe( + "data:image/png;base64,V1", + ); + }); + + const img = preview.querySelector('img[alt="Shot"]')!; + const box = img.closest(".image-zoom") ?? img; + let naturalWidth = 960; + let naturalHeight = 600; + Object.defineProperty(img, "complete", { get: () => true, configurable: true }); + Object.defineProperty(img, "naturalWidth", { get: () => naturalWidth, configurable: true }); + Object.defineProperty(img, "naturalHeight", { get: () => naturalHeight, configurable: true }); + act(() => { + img.dispatchEvent(new Event("load")); + }); + expect(box.style.getPropertyValue("--image-width")).toBe("960px"); + + // Simulate HTML spec: right after `img.src = newUrl`, `complete` is still true and `naturalWidth` is still 960 + // until the new image decodes and fires `load`. + current = "data:image/png;base64,V2"; + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] }); + }); + + await waitFor(() => { + expect(img.getAttribute("src")).toBe("data:image/png;base64,V2"); + }); + expect(img.hasAttribute("data-natural-width")).toBe(false); + + naturalWidth = 420; + naturalHeight = 280; + act(() => { + img.dispatchEvent(new Event("load")); + }); + expect(box.style.getPropertyValue("--image-width")).toBe("420px"); + }); + + it("reloads reStructuredText preview images when modified on disk", async () => { + const rstPath = "/p/rst-reload/index.rst"; + const imgPath = "/p/rst-reload/chart.png"; + let current: string | null = "data:image/png;base64,OLD"; + + vi.spyOn(ipc.commands, "rstPreview").mockResolvedValue({ + status: "ok", + data: '
Chart
', + }); + vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => { + if (path === imgPath && current !== null) return { status: "ok", data: current }; + return { status: "error", error: { kind: "notFound", message: path } } as never; + }); + + useLiveRst.setState({ [rstPath]: "Title\n=====\n" }); + render( + +
+ , + ); + + const preview = document.querySelector('[aria-label="reStructuredText preview"]')!; + await waitFor(() => { + expect(preview.querySelector('img[alt="Chart"]')?.getAttribute("src")).toBe( + "data:image/png;base64,OLD", + ); + }); + + current = "data:image/png;base64,NEW"; + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] }); + }); + + await waitFor(() => { + expect(preview.querySelector('img[alt="Chart"]')?.getAttribute("src")).toBe( + "data:image/png;base64,NEW", + ); + }); + + current = null; + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] }); + }); + await waitFor(() => { + expect(preview.querySelector('img[alt="Chart"]')?.getAttribute("src")).toBeNull(); + }); + + current = "data:image/png;base64,RESTORED"; + act(() => { + emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] }); + }); + await waitFor(() => { + expect(preview.querySelector('img[alt="Chart"]')?.getAttribute("src")).toBe( + "data:image/png;base64,RESTORED", + ); + }); + }); +}); diff --git a/src/features/viewers/previewImages.ts b/src/features/viewers/previewImages.ts index 6e7594ef0..72c05d826 100644 --- a/src/features/viewers/previewImages.ts +++ b/src/features/viewers/previewImages.ts @@ -1,16 +1,97 @@ -import { call, commands } from "@/platform/ipc"; +import { call, commands, onIdeEvent } from "@/platform/ipc"; +import { isSameOrInside } from "@/platform/paths"; /** Loaded local images by absolute path (data URLs), shared by all previews. */ const imageCache = new Map>(); const IMAGE_CACHE_LIMIT = 64; +type ImageChangeListener = (changed: readonly string[]) => void; +const listeners = new Set(); +let offFs: (() => void) | null = null; + +function matchesChanged(path: string, changed: readonly string[]): boolean { + return changed.some((entry) => isSameOrInside(path, entry)); +} + +function ensureWatching(): void { + offFs ??= onIdeEvent("fsChanged", (e) => { + const changed = [...e.created, ...e.modified, ...e.removed]; + if (!changed.length) return; + for (const cached of [...imageCache.keys()]) { + if (matchesChanged(cached, changed)) imageCache.delete(cached); + } + for (const listener of [...listeners]) listener(changed); + }); +} + export function imageUrl(path: string): Promise { - let p = imageCache.get(path); - if (!p) { - p = call(commands.fsReadImage(path)); - p.catch(() => imageCache.delete(path)); + ensureWatching(); + let pending = imageCache.get(path); + if (!pending) { + const request = call(commands.fsReadImage(path)); + request.catch(() => { + if (imageCache.get(path) === request) imageCache.delete(path); + }); if (imageCache.size >= IMAGE_CACHE_LIMIT) imageCache.delete(imageCache.keys().next().value!); - imageCache.set(path, p); + imageCache.set(path, request); + pending = request; } - return p; + return pending; +} + +/** Loads local preview images and reloads them whenever their disk paths change. */ +export function createPreviewImageLoader( + onLoad: (img: HTMLImageElement, url: string) => void, + onError: (img: HTMLImageElement) => void, +) { + let active = true; + const groups = new Map(); + let off: (() => void) | null = null; + + const apply = ( + path: string, + group: { imgs: HTMLImageElement[]; gen: number }, + targets: readonly HTMLImageElement[], + ) => { + const gen = group.gen; + imageUrl(path).then( + (url) => { + if (!active || group.gen !== gen) return; + for (const img of targets) onLoad(img, url); + }, + () => { + if (!active || group.gen !== gen) return; + for (const img of targets) onError(img); + }, + ); + }; + + return { + load(img: HTMLImageElement, path: string) { + let group = groups.get(path); + if (!group) { + group = { imgs: [], gen: 0 }; + groups.set(path, group); + if (!off) { + ensureWatching(); + const onChanged: ImageChangeListener = (changed) => { + for (const [watchedPath, watchedGroup] of groups) { + if (!matchesChanged(watchedPath, changed)) continue; + watchedGroup.gen++; + apply(watchedPath, watchedGroup, watchedGroup.imgs); + } + }; + listeners.add(onChanged); + off = () => listeners.delete(onChanged); + } + } + group.imgs.push(img); + apply(path, group, [img]); + }, + dispose() { + active = false; + off?.(); + groups.clear(); + }, + }; } diff --git a/src/features/viewers/rst/RstEditor.tsx b/src/features/viewers/rst/RstEditor.tsx index de6815bbb..c39fd2dcc 100644 --- a/src/features/viewers/rst/RstEditor.tsx +++ b/src/features/viewers/rst/RstEditor.tsx @@ -13,7 +13,7 @@ import { maybeEditorService } from "@/workbench/contributions"; import { EmptyState, FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui"; import { modeOf } from "../layoutModes"; import { ANCHOR_PREFIX, resolveLink, sanitizePreviewHtml } from "../markdown/render"; -import { imageUrl } from "../previewImages"; +import { createPreviewImageLoader } from "../previewImages"; import { useLiveRst } from "./live"; import { RstLayoutActions, rstModes } from "./RstLayoutActions"; import styles from "../markdown/Markdown.module.css"; @@ -25,10 +25,20 @@ const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 }; type Rendered = { html: string } | { error: string }; /** Puts docutils' `html` into `root`: sanitized, local images loaded, code highlighted. */ -function fill(root: HTMLElement, html: string, path: string, isLive: () => boolean) { +function fill(root: HTMLElement, html: string, path: string) { const template = document.createElement("template"); template.innerHTML = sanitizePreviewHtml(html); root.replaceChildren(template.content); + const images = createPreviewImageLoader( + (img, url) => { + img.classList.remove(styles.blocked!); + if (img.getAttribute("src") !== url) img.src = url; + }, + (img) => { + img.removeAttribute("src"); + img.classList.add(styles.blocked!); + }, + ); root.querySelectorAll("img[data-src]").forEach((img) => { const src = img.dataset.src ?? ""; if (/^data:image\//i.test(src)) { @@ -41,19 +51,13 @@ function fill(root: HTMLElement, html: string, path: string, isLive: () => boole img.title = tx("Remote images are not loaded"); return; } - imageUrl(target.path).then( - (url) => { - if (isLive()) img.src = url; - }, - () => { - if (isLive()) img.classList.add(styles.blocked!); - }, - ); + images.load(img, target.path); }); root.querySelectorAll("pre.code > code").forEach((code) => { const lang = [...code.parentElement!.classList].find((c) => c !== "code" && c !== "literal-block") ?? null; void highlightInto(code, code.textContent ?? "", lang); }); + return () => images.dispose(); } function RstPreview({ path }: { path: string }) { @@ -84,11 +88,7 @@ function RstPreview({ path }: { path: string }) { useLayoutEffect(() => { const root = ref.current; if (!root || html === null) return; - let live = true; - fill(root, html, path, () => live); - return () => { - live = false; - }; + return fill(root, html, path); }, [html, path]); const scrollTo = (id: string) => From 4c71299745d6d090a0fda410c7c95fea92e6d367 Mon Sep 17 00:00:00 2001 From: sonnartliao <59303729+sonnartliao@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:41:27 +0800 Subject: [PATCH 05/66] fix(editor): resolve C declarations without include metadata (#6959) Without a compilation database clangd leaves nested includes unresolved or answers with the call site itself. For C-family files an empty or self-only answer falls back to syntax and the project index (including identifiers in macro bodies), Go to Implementation from a header finds the source definition, and member access is never guessed by bare name. Co-authored-by: sonnartliao <59303729+sonnartliao@users.noreply.github.com> --- src/editor/lsp/navigation.ts | 106 +++++++++- .../lsp/navigationImplementation.test.ts | 106 +++++++++- src/editor/lsp/syntaxFallback.test.ts | 200 ++++++++++++++++++ src/editor/lsp/syntaxFallback.ts | 45 +++- src/platform/locales/text/es.json | 1 + src/platform/locales/text/fr.json | 1 + src/platform/locales/text/ko.json | 1 + src/platform/locales/text/pl.json | 1 + src/platform/locales/text/pt.json | 1 + src/platform/locales/text/ru.json | 1 + src/platform/locales/text/tr.json | 1 + src/platform/locales/text/zh-TW.json | 1 + src/platform/locales/text/zh.json | 1 + 13 files changed, 446 insertions(+), 20 deletions(-) diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index f9ac17f50..70bfa1299 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -66,6 +66,8 @@ import { isDeclarationName, isSelfTarget, localHighlights, + projectIndexDefinitions, + usageRole, type DeclarationTarget, } from "./syntaxFallback"; import { showHint, showPendingHint } from "./hint"; @@ -112,6 +114,27 @@ export async function navigateTo(loc: Location) { await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col }); } +const CLANGD_LANGUAGES = new Set(["c", "cpp", "objective-c", "objective-cpp"]); +const CLANGD_SYNTAX_NOTE = "Based on syntax and the project index"; +const C_HEADER = /\.(?:h|hh|hpp|hxx|h\+\+)$/i; + +/** `pki_check_bin` for `.../pki_check_bin.h`: the stem a source counterpart shares. */ +function fileStem(path: string): string { + const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1); + const dot = name.lastIndexOf("."); + return (dot > 0 ? name.slice(0, dot) : name).toLowerCase(); +} + +/** + * `pki_check_bin.c` for `pki_check_bin.h`, or every source when no stem matches: the same + * declaration can be implemented in another component (a kernel tree holds many copies). + */ +function counterpartSources(header: string, sources: readonly DeclarationTarget[]): readonly DeclarationTarget[] { + const stem = fileStem(header); + const own = sources.filter((l) => fileStem(l.path) === stem); + return own.length ? own : sources; +} + const NOT_FOUND: Record = { definition: "Cannot find declaration to go to", declaration: "Cannot find declaration to go to", @@ -373,6 +396,18 @@ async function onDeclarationName(view: EditorView, offset: number): Promise { + const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null); + return usageRole(at) === "call"; +} + +/** A C-family member must come from its receiver's type, not a project-wide bare-name lookup. */ +async function onMemberName(doc: EditorDocContext, pos: Pos): Promise { + const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null); + return at?.node.kind === "field_identifier" || at?.node.kind === "property_identifier"; +} + /** * Go to Implementation targets for Python from the IDE's inheritance graph: its servers * declare no type hierarchy and analyse one root, so the graph also knows the attached @@ -400,7 +435,20 @@ async function implementationFallbackTargets( pos: Pos, ): Promise { const declaration = await requestNavigation(view, offset, "definition").catch(() => []); - return declaration.filter((l) => !isSelfTarget([l], path, pos)); + const targets = declaration.filter((l) => !isSelfTarget([l], path, pos)); + if (targets.length) return targets; + const doc = docOf(view); + if (!doc || !CLANGD_LANGUAGES.has(doc.language)) return targets; + // Without a compilation database clangd only sees this header. Look the name up in the + // project index for a source definition; never offer another header declaration. + const name = nameAt(view, offset) ?? (offset > 0 ? nameAt(view, offset - 1) : null); + if (!name) return targets; + const indexed = await projectIndexDefinitions(path, name, "call").catch(() => []); + const sources = indexed.filter((l) => !isSelfTarget([l], path, pos) && !C_HEADER.test(l.path)); + if (!sources.length) return targets; + // The caret's own header names the source that implements it: its stem picks that source + // among same-name definitions elsewhere instead of turning the jump into a chooser. + return C_HEADER.test(path) ? counterpartSources(path, sources) : sources; } /** Whether `line` (0-based) of `text` is an import statement. */ @@ -495,6 +543,7 @@ async function gotoResolved( const pos = offsetToPos(view.state.doc, offset); let locs: DeclarationTarget[]; let fromSyntax = false; + let syntaxNote = SYNTAX_NOTE; const declaration = kind === "definition" || kind === "declaration"; // A segment of an import path names a file — possibly in a dependency project, which // neither the single-root server nor the name index resolves. @@ -580,6 +629,35 @@ async function gotoResolved( const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos); if (superseded()) return; locs = dedupeLocations(declarationTargets); + if (declarationTargets.some((target) => target.name && target.kind)) { + fromSyntax = true; + syntaxNote = CLANGD_SYNTAX_NOTE; + } + } + // Without a compilation database clangd may not resolve nested #include files. Its empty + // answer is not authoritative for these languages; the project index still has the local + // declarations. An implicit C declaration can also point at the call itself: replace that + // pseudo target only when syntax and the index provide a real target elsewhere. + if (declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language)) { + const selfTargets = locs.length > 0 && locs.every((l) => isSelfTarget([l], doc.path, pos)); + if (!locs.length || (selfTargets && (await onCallName(doc, pos)))) { + const fallback = await gotoFallback(view, doc, pos, false); + if (fallback?.length) { + if (!locs.length) { + locs = fallback; + fromSyntax = true; + syntaxNote = CLANGD_SYNTAX_NOTE; + } else { + const elsewhere = fallback.filter((l) => !isSelfTarget([l], doc.path, pos)); + if (elsewhere.length) { + locs = elsewhere; + fromSyntax = true; + syntaxNote = CLANGD_SYNTAX_NOTE; + } + } + } + } + if (superseded()) return; } if (!locs.length) { // The server has no definition here: a link (`href`, `#include`, Markdown) or a file path. @@ -600,8 +678,12 @@ async function gotoResolved( } // The server only resolves what it sees: answer from the project index, which also // covers attached dependency projects (an unresolved import into them). Never for a - // module path: a segment is not a symbol name. - if (declaration && !fromSyntax && !moduleName) { + // module path: a segment is not a symbol name. A C-family member needs its receiver's + // type, so a bare-name dependency lookup would be a guess here too. + const clangMember = + declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos)); + if (superseded()) return; + if (declaration && !fromSyntax && !moduleName && !clangMember) { const name = nameAt(view, offset); const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : []; if (targets.length) { @@ -687,7 +769,7 @@ async function gotoResolved( setTimeout(() => { if (superseded()) return; const target = activeEditor()?.view; - if (target) showHint(target, SYNTAX_NOTE, { timeout: 2500 }); + if (target) showHint(target, syntaxNote, { timeout: 2500 }); }, 150); return; } @@ -775,11 +857,16 @@ async function followReferenceAt( } /** Declaration targets from the structure service; null when it cannot answer for this file. */ -async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos): Promise { +async function gotoFallback( + view: EditorView, + doc: EditorDocContext, + pos: Pos, + allowMember = true, +): Promise { try { await whenSynced(view); const text = view.state.doc; - const fb = await declarationFallback(doc, text, pos); + const fb = await declarationFallback(doc, text, pos, undefined, allowMember); return fb.kind === "unsupported" ? null : fb.targets; } catch (e) { console.debug("[syntax] declaration fallback", e); @@ -936,11 +1023,14 @@ async function probeNavigation( navigable = !!(await gotoFallback(view, doc, pos))?.length; fromSyntax = true; } + if (!navigable && !fromSyntax && CLANGD_LANGUAGES.has(doc.language)) + navigable = !!(await gotoFallback(view, doc, pos, false))?.length; if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual) navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length; // The index answers across dependency roots too (unresolved imports), but a module path - // segment is a file rather than a name. - if (!navigable && !fromSyntax) { + // segment is a file rather than a name. Keep member probing consistent with the click path. + const clangMember = !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos)); + if (!navigable && !fromSyntax && !clangMember) { const moduleName = importModuleName(view, doc, offset); if (moduleName) navigable = !!(await moduleFile(doc, moduleName).catch(() => null)); else { diff --git a/src/editor/lsp/navigationImplementation.test.ts b/src/editor/lsp/navigationImplementation.test.ts index b195bd190..2caab3100 100644 --- a/src/editor/lsp/navigationImplementation.test.ts +++ b/src/editor/lsp/navigationImplementation.test.ts @@ -3,9 +3,11 @@ import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import type { commands, Location } from "@/platform/ipc"; -const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({ +const { lspGoto, lspGotoImplementation, findSymbols, navIndexDefinitions } = vi.hoisted(() => ({ lspGoto: vi.fn(), lspGotoImplementation: vi.fn(), + findSymbols: vi.fn(), + navIndexDefinitions: vi.fn(), })); vi.mock("@/platform/ipc", async (orig) => { const real = await orig(); @@ -17,7 +19,15 @@ vi.mock("@/platform/ipc", async (orig) => { return { ...real, isTauri: () => true, - commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance }, + commands: { + ...real.commands, + lspGoto, + lspGotoImplementation, + findSymbols, + navIndexDefinitions, + fsReadText, + navInheritance, + }, }; }); vi.mock("@tauri-apps/api/core", async (orig) => ({ @@ -60,6 +70,8 @@ beforeEach(() => { invalidateConfigurationNavigation(); lspGoto.mockResolvedValue(ok([])); lspGotoImplementation.mockResolvedValue(ok([])); + findSymbols.mockResolvedValue({ status: "ok", data: [] }); + navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] }); view = editor(TEXT, "go", "/p/store.go"); }); afterEach(() => { @@ -154,4 +166,94 @@ describe("Go to Implementation on a symbol nothing implements", () => { await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2); expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true }); }); + + it("finds a C source definition from the project index when clangd only returns the header", async () => { + const name = "verify_firmware"; + const text = `int ${name}(const char *signed_fw_path);\n`; + const col = text.indexOf(name); + const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } }; + const symbol = (path: string, line: number) => ({ + name, + kind: "function" as const, + container: null, + path, + relPath: path.slice(1), + range: { start: { line, col }, end: { line, col: col + name.length } }, + score: 1, + indices: [], + }); + view.destroy(); + view = editor(text, "c", "/p/pki_check_bin.h"); + lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }])); + findSymbols.mockResolvedValue({ + status: "ok", + data: [symbol("/p/pki_check_bin.h", 0), symbol("/p/pki_check_bin.c", 190)], + }); + await gotoTargets(view, "implementation", col + 2); + expect(findSymbols).toHaveBeenCalledWith(name, "all", 500); + expect(openFile).toHaveBeenCalledWith("/p/pki_check_bin.c", { selection: { line: 190, col }, focus: true }); + expect(navIndexDefinitions).not.toHaveBeenCalled(); + }); + + it("does not treat another header declaration as a C implementation", async () => { + const name = "verify_firmware"; + const text = `int ${name}(const char *signed_fw_path);\n`; + const col = text.indexOf(name); + const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } }; + view.destroy(); + view = editor(text, "c", "/p/pki_check_bin.h"); + lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }])); + findSymbols.mockResolvedValue({ + status: "ok", + data: [ + { + name, + kind: "function" as const, + container: null, + path: "/p/other.h", + relPath: "p/other.h", + range, + score: 1, + indices: [], + }, + ], + }); + await gotoTargets(view, "implementation", col + 2); + expect(openFile).not.toHaveBeenCalled(); + expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found"); + }); + + it("prefers the header's own source among same-name definitions elsewhere", async () => { + const name = "verify_firmware"; + const text = `int ${name}(const char *signed_fw_path);\n`; + const col = text.indexOf(name); + const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } }; + const symbol = (path: string, line: number) => ({ + name, + kind: "function" as const, + container: null, + path, + relPath: path.slice(1), + range: { start: { line, col }, end: { line, col: col + name.length } }, + score: 1, + indices: [], + }); + view.destroy(); + view = editor(text, "c", "/p/pki_check_bin.h"); + lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }])); + findSymbols.mockResolvedValue({ + status: "ok", + data: [ + symbol("/p/pki_check_bin.h", 0), + symbol("/p/pki_check_bin.c", 190), + symbol("/kernel/5.15/gvt/firmware.c", 149), + symbol("/kernel/5.4/gvt/firmware.c", 154), + ], + }); + await gotoTargets(view, "implementation", col + 2); + expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/pki_check_bin.c", { + selection: { line: 190, col }, + focus: true, + }); + }); }); diff --git a/src/editor/lsp/syntaxFallback.test.ts b/src/editor/lsp/syntaxFallback.test.ts index 5adba1959..d06e0436e 100644 --- a/src/editor/lsp/syntaxFallback.test.ts +++ b/src/editor/lsp/syntaxFallback.test.ts @@ -48,6 +48,8 @@ const { gotoTargets, navigationExtension, highlightUsages } = await import("./na const { registerNavigationProvider } = await import("@/editor/navigationProviders"); const { startRename, renameNamePart } = await import("./rename"); const { lspDoc } = await import("./lsp"); +const { usePlatform } = await import("@/platform/platformInfo"); +const { resetNavigationModifier } = await import("@/platform/navigationModifier"); const { invalidateConfigurationNavigation } = await import("./configurationNavigation"); const { useLspPopup, closePopup } = await import("./popupStore"); const { inplaceRenameExtension, inplaceSession } = await import("./inplaceRename"); @@ -211,6 +213,36 @@ describe("declarationFallback", () => { expect(res).toMatchObject({ kind: "targets", ambiguous: true }); }); + it("can reject a member reported by locals without querying the index", async () => { + cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "member" })); + const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 }, undefined, false); + expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false }); + expect(cmd.syntaxNodeAt).not.toHaveBeenCalled(); + expect(cmd.findSymbols).not.toHaveBeenCalled(); + }); + + it("can reject a C field node when locals are unavailable", async () => { + cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false })); + cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("field_identifier", r(1, 6, 9)), ancestors: [] })); + const res = await fb.declarationFallback( + { ...doc, language: "c-fields" }, + text, + { line: 1, col: 7 }, + undefined, + false, + ); + expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false }); + expect(cmd.findSymbols).not.toHaveBeenCalled(); + }); + + it("keeps a no-identifier answer empty outside macro replacement bodies", async () => { + cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" })); + cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] })); + const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 }); + expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false }); + expect(cmd.findSymbols).not.toHaveBeenCalled(); + }); + it("uses the node text for languages without locals, and gives up without a grammar", async () => { cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false })); cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] })); @@ -345,6 +377,174 @@ describe("navigation wiring", () => { expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to"); }); + function clangCall(language: string, name = "indirect_call") { + const text = `#include "direct.h"\nint main(void) { return ${name}(); }\n`; + const path = language === "cpp" || language === "objective-cpp" ? "/p/main.cpp" : "/p/main.c"; + const col = text.split("\n")[1]!.indexOf(name); + const range = r(1, col, col + name.length); + const at: NodeAt = { + node: node("identifier", range, "function"), + ancestors: [node("call_expression", r(1, 0, text.split("\n")[1]!.length))], + }; + cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name, range, reason: "topLevel" })); + cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)); + const view = editor(text, language, text.indexOf(name) + 2, path); + return { view, path, range, at, name }; + } + + it.each(["c", "cpp", "objective-c", "objective-cpp"])( + "uses the local project index when clangd cannot resolve a nested include in %s", + async (language) => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + const { view, name } = clangCall(language); + cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")])); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/p/include/indirect.h", { selection: { line: 3, col: 4 }, focus: true }); + expect(cmd.navIndexDefinitions).not.toHaveBeenCalled(); + }, + ); + + it("resolves a function name inside a C macro replacement body", async () => { + const name = "sys_util_read_content"; + const text = `#define jy_read_country(buf, len) ${name}(FACTORY_DIR "country_code", buf, len)\n`; + const col = text.indexOf(name); + cmd.lspGoto.mockReturnValueOnce(ok([])); + cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" })); + cmd.syntaxNodeAt.mockReturnValueOnce( + ok({ + node: node("preproc_arg", r(0, col, text.length - 1), "value"), + ancestors: [node("preproc_function_def", r(0, 0, text.length - 1))], + }), + ); + cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")])); + const view = editor(text, "c", col + 2, "/p/jy_lib.h"); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", { + selection: { line: 3, col: 4 }, + focus: true, + }); + expect(cmd.navIndexDefinitions).not.toHaveBeenCalled(); + }); + + it("underlines a nested-include call when the hover probe uses the same index fallback", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + const { view, name } = clangCall("c"); + cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")])); + const os = usePlatform.getState().os; + usePlatform.setState({ os: "macos" }); + resetNavigationModifier(); + const offset = view.state.doc.toString().indexOf(name) + 2; + vi.spyOn(view, "posAtCoords").mockReturnValue(offset); + try { + view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true })); + await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull()); + } finally { + resetNavigationModifier(); + usePlatform.setState({ os }); + } + }); + + it("replaces clangd's implicit-declaration self target with the indexed declaration", async () => { + const { view, path, range, at, name } = clangCall("c"); + cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }])); + cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)); + cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")])); + executeAction.mockClear(); + await gotoTargets(view, "definition"); + expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", { + selection: { line: 3, col: 4 }, + focus: true, + }); + expect(executeAction).not.toHaveBeenCalled(); + }); + + it("keeps a legitimate declaration self target instead of replacing it from the index", async () => { + const name = "indirect_call"; + const range = r(0, 4, 4 + name.length); + const path = "/p/main.c"; + cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }])); + cmd.syntaxNodeAt.mockReturnValueOnce( + ok({ + node: node("identifier", range, "declarator"), + ancestors: [node("function_declarator", r(0, 0, 4 + name.length + 8))], + }), + ); + const view = editor(`int ${name}(void) { return 0; }\n`, "c", 6, path); + executeAction.mockClear(); + await gotoTargets(view, "definition"); + expect(executeAction).toHaveBeenCalledWith("find.showUsages"); + expect(cmd.findSymbols).not.toHaveBeenCalled(); + expect(openFile).not.toHaveBeenCalled(); + }); + + it("keeps clangd's original self target when the local index has no better answer", async () => { + const { view, path, range, at } = clangCall("c"); + cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }])); + cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)); + executeAction.mockClear(); + await gotoTargets(view, "definition"); + expect(executeAction).toHaveBeenCalledWith("find.showUsages"); + expect(openFile).not.toHaveBeenCalled(); + }); + + it("does not guess a C member declaration from unrelated project symbols", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + const range = r(0, 3, 10); + const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] }; + cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "handler", range, reason: "member" })); + cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)).mockReturnValueOnce(ok(at)); + cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")])); + try { + const view = editor("s->handler();\n", "c", 5, "/p/main.c"); + await gotoTargets(view, "definition"); + expect(cmd.findSymbols).not.toHaveBeenCalled(); + expect(cmd.navIndexDefinitions).not.toHaveBeenCalled(); + expect(openFile).not.toHaveBeenCalled(); + } finally { + cmd.navIndexDefinitions.mockReturnValue(ok([])); + } + }); + + it("does not underline a C member from a bare-name dependency candidate", async () => { + const range = r(0, 3, 10); + const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] }; + cmd.lspGoto.mockReturnValue(ok([])); + cmd.syntaxLocals.mockReturnValue(ok({ status: "notLocal", name: "handler", range, reason: "member" })); + cmd.syntaxNodeAt.mockReturnValue(ok(at)); + cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")])); + const view = editor("s->handler();\n", "c", 5, "/p/main.c"); + const os = usePlatform.getState().os; + usePlatform.setState({ os: "macos" }); + resetNavigationModifier(); + vi.spyOn(view, "posAtCoords").mockReturnValue(5); + try { + view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true })); + await vi.waitFor(() => expect(cmd.syntaxNodeAt).toHaveBeenCalled()); + expect(view.dom.querySelector(".cm-lsp-link")).toBeNull(); + expect(cmd.navIndexDefinitions).not.toHaveBeenCalled(); + expect(openFile).not.toHaveBeenCalled(); + } finally { + resetNavigationModifier(); + usePlatform.setState({ os }); + cmd.lspGoto.mockReturnValue(unavailable()); + cmd.syntaxLocals.mockReturnValue(ok({ status: "noIdentifier" })); + cmd.syntaxNodeAt.mockReturnValue(ok(null)); + cmd.navIndexDefinitions.mockReturnValue(ok([])); + } + }); + + it("shows ambiguous nested-include declarations as syntax-based candidates", async () => { + cmd.lspGoto.mockReturnValueOnce(ok([])); + const { view, name } = clangCall("c"); + cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/a.c"), sym(name, "function", "/p/include/a.h")])); + await gotoTargets(view, "definition"); + const popup = useLspPopup.getState().popup; + expect(popup?.kind).toBe("list"); + if (popup?.kind !== "list") return; + expect(popup.title).toBe(`Choose Declaration of ${name} (2 found, based on syntax)`); + expect(openFile).not.toHaveBeenCalled(); + }); + it("answers from the index when the server cannot resolve an import into a dependency project", async () => { cmd.lspGoto.mockReturnValueOnce(ok([])); cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("ParallelDims", "class", "/deps/engine/model.py")])); diff --git a/src/editor/lsp/syntaxFallback.ts b/src/editor/lsp/syntaxFallback.ts index 431245417..5b0b00f88 100644 --- a/src/editor/lsp/syntaxFallback.ts +++ b/src/editor/lsp/syntaxFallback.ts @@ -154,6 +154,20 @@ export async function indexDefinitions(path: string, name: string): Promise { + const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT)); + const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(path, s.path)); + return rankTargets( + symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })), + path, + ); +} + /** * Go to Declaration without a language server: a certain local definition, * otherwise project index symbols with exactly that name (filtered by the @@ -164,32 +178,43 @@ export async function declarationFallback( text: Text, pos: Pos, signal?: AbortSignal, + allowMember = true, ): Promise { const support = await structure.support(doc.language); if (!support.tree) return { kind: "unsupported" }; let locals: Locals | null = null; if (support.locals) locals = await structure.locals(doc.doc, pos, { signal }); - if (locals?.status === "noIdentifier") return { kind: "targets", targets: [], ambiguous: false }; if (locals?.status === "local") return { kind: "targets", ...localTargets(doc.path, locals.symbol) }; + if (!allowMember && locals?.status === "notLocal" && locals.reason === "member") + return { kind: "targets", targets: [], ambiguous: false }; const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }, { signal }); - const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at); + if (locals?.status === "noIdentifier" && at?.node.kind !== "preproc_arg") + return { kind: "targets", targets: [], ambiguous: false }; + if (!allowMember && at?.node.kind === "field_identifier") return { kind: "targets", targets: [], ambiguous: false }; + const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at, pos); if (!name) return { kind: "targets", targets: [], ambiguous: false }; // A member (`obj.name`) can be any member of that name; only a plain name has a syntactic role. const role = locals?.status === "notLocal" && locals.reason === "member" ? "other" : usageRole(at); - const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT)); - const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(doc.path, s.path)); - const targets = rankTargets( - symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })), - doc.path, - ); + const targets = await projectIndexDefinitions(doc.path, name, role); return { kind: "targets", targets, ambiguous: targets.length > 1 }; } const IDENT = /^[\p{L}_$][\p{L}\p{N}_$]*$/u; +const IDENT_PART = /[\p{L}\p{N}_$]/u; -/** Name of a leaf identifier node (languages without `locals.scm`). */ -function identifierText(text: Text, at: NodeAt | null): string | null { +/** Name of a leaf identifier node, or the identifier at `pos` in a macro replacement body. */ +function identifierText(text: Text, at: NodeAt | null, pos: Pos): string | null { + if (at?.node.kind === "preproc_arg") { + if (pos.line >= text.lines) return null; + const line = text.line(pos.line + 1).text; + let from = Math.min(pos.col, line.length); + let to = from; + while (from > 0 && IDENT_PART.test(line[from - 1]!)) from--; + while (to < line.length && IDENT_PART.test(line[to]!)) to++; + const name = line.slice(from, to); + return IDENT.test(name) ? name : null; + } if (!at || !/identifier|^name$|^constant$|^word$/.test(at.node.kind)) return null; const { from, to } = rangeToOffsets(text, at.node.range); const name = text.sliceString(from, to); diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 7f316646f..dcd9ea7e4 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -299,6 +299,7 @@ "Base interpreter": "Intérprete base", "Base interpreter:": "Intérprete base:", "Based on syntax (language server not ready)": "Basado en sintaxis (el servidor de lenguaje no está listo)", + "Based on syntax and the project index": "Basado en sintaxis y el índice del proyecto", "Behavior": "Comportamiento", "Benchmark function": "Función de benchmark", "Binary response": "Respuesta binaria", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 7c46baa51..a7be02f2d 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -255,6 +255,7 @@ "Base interpreter": "Interpréteur de base", "Base interpreter:": "Interpréteur de base :", "Based on syntax (language server not ready)": "D'après la syntaxe (serveur de langage pas encore prêt)", + "Based on syntax and the project index": "D'après la syntaxe et l'index du projet", "Behavior": "Comportement", "Benchmark function": "Fonction de benchmark", "Binary response": "Réponse binaire", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 2716f866f..64c5cc9d0 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -335,6 +335,7 @@ "Base interpreter": "기본 인터프리터", "Base interpreter:": "기본 인터프리터:", "Based on syntax (language server not ready)": "구문 기반(언어 서버가 준비되지 않음)", + "Based on syntax and the project index": "구문 및 프로젝트 인덱스 기반", "Behavior": "동작", "Benchmark function": "벤치마크 함수", "Binary response": "바이너리 응답", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 053c2f0f4..947a7ae30 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -291,6 +291,7 @@ "Base interpreter": "Interpreter bazowy", "Base interpreter:": "Interpreter bazowy:", "Based on syntax (language server not ready)": "Na podstawie składni (serwer językowy nie jest gotowy)", + "Based on syntax and the project index": "Na podstawie składni i indeksu projektu", "Behavior": "Zachowanie", "Benchmark function": "Funkcja benchmarku", "Binary response": "Odpowiedź binarna", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 3ed42fc0d..36c71f171 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -291,6 +291,7 @@ "Base interpreter": "Interpretador base", "Base interpreter:": "Interpretador base:", "Based on syntax (language server not ready)": "Baseado na sintaxe (servidor de linguagem não pronto)", + "Based on syntax and the project index": "Baseado na sintaxe e no índice do projeto", "Behavior": "Comportamento", "Benchmark function": "Função de benchmark", "Binary response": "Resposta binária", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index c95ef28db..fe6ce8ffc 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -1248,6 +1248,7 @@ "Base interpreter": "Базовый интерпретатор", "Base interpreter:": "Базовый интерпретатор:", "Based on syntax (language server not ready)": "На основе синтаксиса (языковой сервер не готов)", + "Based on syntax and the project index": "На основе синтаксиса и индекса проекта", "Behavior": "Поведение", "Benchmark function": "Функция бенчмарка", "Binary response": "Двоичный ответ", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 23a3b459b..eae689952 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -3092,6 +3092,7 @@ "Base interpreter": "Temel yorumlayıcı", "Base interpreter:": "Temel yorumlayıcı:", "Based on syntax (language server not ready)": "Sözdizimine göre (dil sunucusu hazır değil)", + "Based on syntax and the project index": "Sözdizimine ve proje dizinine göre", "Behavior": "Davranış", "Benchmark function": "Performans testi fonksiyonu", "Binary response": "İkili yanıt", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 032c0baf8..96cb167cd 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -936,6 +936,7 @@ "Base interpreter": "基礎直譯器", "Base interpreter:": "基礎直譯器:", "Based on syntax (language server not ready)": "基於語法(語言伺服器尚未就緒)", + "Based on syntax and the project index": "基於語法和專案索引", "Behavior": "行為", "Benchmark function": "基準測試函式", "Binary response": "二進位制回應", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 90273ec92..c023750f0 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1395,6 +1395,7 @@ "Base interpreter": "基础解释器", "Base interpreter:": "基础解释器:", "Based on syntax (language server not ready)": "基于语法(语言服务器尚未就绪)", + "Based on syntax and the project index": "基于语法和项目索引", "Behavior": "行为", "Benchmark function": "基准测试函数", "Binary response": "二进制响应", From 83013262893ad9dcfb5213cad0b64a8135127d09 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:41:43 +0800 Subject: [PATCH 06/66] fix(ui): remeasure the custom scrollbar when its content grows without the scroller resizing (#6973) The custom scrollbar observed only the scroller, whose size does not change when its content grows (a Markdown preview reflowing after a width change). It now also observes the scroller children, re-observing them when they are replaced. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- src/ui/Scrollbar.test.tsx | 67 ++++++++++++++++++++++++++++++++++++++- src/ui/Scrollbar.tsx | 15 +++++++-- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/src/ui/Scrollbar.test.tsx b/src/ui/Scrollbar.test.tsx index 190399046..a500af2db 100644 --- a/src/ui/Scrollbar.test.tsx +++ b/src/ui/Scrollbar.test.tsx @@ -1,6 +1,6 @@ import { act, render } from "@testing-library/react"; import { useRef } from "react"; -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { Scrollbar } from "./Scrollbar"; function Harness({ onScroll }: { onScroll: (top: number) => void }) { @@ -13,7 +13,72 @@ function Harness({ onScroll }: { onScroll: (top: number) => void }) { ); } +/** A ResizeObserver the test fires by hand, for the elements it was told to observe. */ +function fakeResizeObserver() { + const observers = new Set<{ callback: () => void; targets: Set }>(); + vi.stubGlobal( + "ResizeObserver", + class { + entry: { callback: () => void; targets: Set }; + constructor(callback: () => void) { + this.entry = { callback, targets: new Set() }; + observers.add(this.entry); + } + observe(target: Element) { + this.entry.targets.add(target); + } + unobserve(target: Element) { + this.entry.targets.delete(target); + } + disconnect() { + this.entry.targets.clear(); + } + }, + ); + return (target: Element) => { + act(() => { + for (const o of observers) if (o.targets.has(target)) o.callback(); + }); + }; +} + describe("Scrollbar", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("measures again when the scroller's content grows without the scroller resizing", async () => { + const resize = fakeResizeObserver(); + const { getByTestId, container } = render( {}} />); + const scroller = getByTestId("scroller"); + const content = document.createElement("div"); + scroller.append(content); + await Promise.resolve(); + const size = { content: 100 }; + Object.defineProperties(scroller, { + clientHeight: { configurable: true, value: 100 }, + scrollHeight: { configurable: true, get: () => size.content }, + scrollTop: { configurable: true, value: 0 }, + }); + const track = container.querySelector("[aria-hidden]")!; + const thumb = track.firstElementChild as HTMLElement; + resize(scroller); + + // `contentHeight` stays the same, as in a Markdown preview reflowing at a late block width. + size.content = 200; + resize(content); + expect(thumb.style.height).toBe("50px"); + + const replaced = document.createElement("div"); + act(() => { + scroller.replaceChildren(replaced); + }); + await Promise.resolve(); + size.content = 400; + resize(replaced); + expect(thumb.style.height).toBe("32px"); + }); + it("notifies scroll listeners synchronously while the thumb is dragged", () => { const onScroll = vi.fn(); const { getByTestId, container } = render(); diff --git a/src/ui/Scrollbar.tsx b/src/ui/Scrollbar.tsx index 47159edc3..1f611653c 100644 --- a/src/ui/Scrollbar.tsx +++ b/src/ui/Scrollbar.tsx @@ -17,7 +17,8 @@ export const hideNativeHorizontalScrollbar = styles.hideNativeHorizontal; * native one scrolls asynchronously in WebKit and shows blank rows until the * page catches up. * - * Pass the scrollable content size to remeasure when content grows. The vertical + * Pass the scrollable content size to remeasure when content grows; content that grows without it is + * caught by observing the scroller's children. The vertical * scrollbar sets `data-scrollbar-shown` when needed. The horizontal overlay appears * on scroll and fades when idle. */ @@ -83,7 +84,16 @@ export function Scrollbar({ lastLeft = el.scrollLeft; sync(); }); - observer.observe(el); + // The scroller's size does not change when its content grows (a Markdown preview reflowing), + // so observe its children too, and again when they are replaced. + const observe = () => { + observer.disconnect(); + observer.observe(el); + for (const child of el.children) observer.observe(child); + }; + observe(); + const replaced = new MutationObserver(observe); + replaced.observe(el, { childList: true }); window.addEventListener("blur", endDrag); return () => { endDrag(); @@ -91,6 +101,7 @@ export function Scrollbar({ window.clearTimeout(hideTimer.current); el.removeEventListener("scroll", onScroll); observer.disconnect(); + replaced.disconnect(); }; }, [target, endDrag, horizontal, scheduleHide]); From acc48a48163ada4a467fdd68f859b7742dfae4da Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 18:42:00 +0900 Subject: [PATCH 07/66] fix(run): clear a selected test's output with Clear All (#6982) A selected test node shows the output captured on that node, which Clear All did not touch. Clear All now drops captured test output as well; statuses and the tree stay. Closes #6975 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/run/clearConsole.test.ts | 79 +++++++++++++++++++++++++++ src/features/run/store.ts | 7 ++- src/features/run/testing/results.ts | 6 ++ 3 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 src/features/run/clearConsole.test.ts diff --git a/src/features/run/clearConsole.test.ts b/src/features/run/clearConsole.test.ts new file mode 100644 index 000000000..2b582900c --- /dev/null +++ b/src/features/run/clearConsole.test.ts @@ -0,0 +1,79 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; + +const ipc = vi.hoisted(() => ({ + runStart: vi.fn(async (_config: RunConfig) => ({ status: "ok", data: 1 })), + runStop: vi.fn(async () => ({ status: "ok", data: null })), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } }; +}); +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal()), + Channel: class { + onmessage: ((m: unknown) => void) | null = null; + }, +})); + +import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions"; +import { nodeDuration, nodeOutput, nodeStatus } from "./testing"; +import { clearConsole, resetRuns, runtime, startRun } from "./store"; + +const SEP = "\u0000"; +const config: RunConfig = { + id: "junit:CartTest", + name: "CartTest", + kind: "shell", + command: "true", + args: [], + cwd: null, + env: {}, + detected: false, + isTest: true, + debugAdapter: null, +}; +const cls = ["CartTest"]; +const total = ["CartTest", "total"]; + +beforeEach(() => provideToolWindowService({ show: vi.fn(), hide: vi.fn() } as unknown as ToolWindowService)); +afterEach(() => resetRuns()); + +async function testRun() { + const session = (await startRun(config, undefined, undefined, { prepared: true }))!; + const rt = runtime(session.id)!; + rt.console.append({ kind: "stdout", text: "before all\nprinted by total\n" }); + rt.tests!.apply([ + { type: "output", path: cls, line: "before all" }, + { type: "output", path: total, line: "printed by total" }, + { type: "result", path: total, status: "failed", durationMs: 12 }, + ]); + return { id: session.id, rt, tests: rt.tests! }; +} + +it("Clear All empties the full console and every test node's output, keeping the results (#6975)", async () => { + const { id, rt, tests } = await testRun(); + const leaf = tests.get(total.join(SEP))!; + const group = tests.get(cls.join(SEP))!; + expect(nodeOutput(group)).toEqual(["before all", "printed by total"]); + + clearConsole(id); + + expect(rt.console.text()).toBe(""); + expect(nodeOutput(leaf)).toEqual([]); + expect(nodeOutput(group)).toEqual([]); + expect(nodeStatus(leaf)).toBe("failed"); + expect(nodeDuration(group)).toBe(12); + expect(tests.roots.map((r) => r.children.map((c) => c.name))).toEqual([["total"]]); +}); + +it("output printed after Clear All shows in the console and on its test", async () => { + const { id, rt, tests } = await testRun(); + clearConsole(id); + rt.console.append({ kind: "stdout", text: "after clear\n" }); + tests.apply([{ type: "output", path: total, line: "after clear" }]); + + expect(rt.console.text()).toBe("after clear"); + expect(nodeOutput(tests.get(total.join(SEP))!)).toEqual(["after clear"]); + expect(nodeOutput(tests.get(cls.join(SEP))!)).toEqual(["after clear"]); +}); diff --git a/src/features/run/store.ts b/src/features/run/store.ts index e46c5c3e4..e2f2497da 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -1940,8 +1940,11 @@ export async function closeStdin(sessionId: string): Promise { } export function clearConsole(sessionId: string) { - runtimes.get(sessionId)?.console.clear(); - runtimes.get(sessionId)?.terminal?.clear(); + const rt = runtimes.get(sessionId); + rt?.console.clear(); + rt?.terminal?.clear(); + // A selected test shows its own captured output, so that goes too (as in IDEA). + rt?.tests?.clearOutput(); bump(sessionId); } diff --git a/src/features/run/testing/results.ts b/src/features/run/testing/results.ts index b8d570a63..7bb34e29c 100644 --- a/src/features/run/testing/results.ts +++ b/src/features/run/testing/results.ts @@ -101,6 +101,12 @@ export class TestResults { this.version++; } + /** Console Clear All: drops every node's captured output; statuses, durations and the tree stay. */ + clearOutput() { + for (const n of this.byId.values()) n.output = []; + this.version++; + } + /** Finds a test by a suffix of its path (pytest failure headers name `Class.test`). */ findBySuffix(suffix: string[]): TestNode | undefined { let best: TestNode | undefined; From 37a8aae0182fa297c650ac2d7d7b4ae599a3a45e Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:42:16 +0800 Subject: [PATCH 08/66] fix(vcs): keep focused and unsaved all-in-one diff blocks mounted while the view has no height (#6983) With no height (a maximized tool window over the diff) the virtualizer rendered no range and unmounted the focused and unsaved blocks, saving an unsaved index edit. The view now reports at least 1 px and keeps the last measured block sizes while hidden. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- src/features/vcs/CombinedDiff.tsx | 19 ++++- .../__tests__/combinedDiffUnsaved.test.tsx | 76 +++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) diff --git a/src/features/vcs/CombinedDiff.tsx b/src/features/vcs/CombinedDiff.tsx index 134c5e77b..1f96481d6 100644 --- a/src/features/vcs/CombinedDiff.tsx +++ b/src/features/vcs/CombinedDiff.tsx @@ -15,7 +15,14 @@ import { type ReactNode, type Ref, } from "react"; -import { defaultRangeExtractor, elementScroll, useVirtualizer, type Range } from "@tanstack/react-virtual"; +import { + defaultRangeExtractor, + elementScroll, + measureElement, + observeElementRect, + useVirtualizer, + type Range, +} from "@tanstack/react-virtual"; import clsx from "clsx"; import { tx } from "@/platform/i18n"; import { relativeDir, useProject } from "@/platform/project"; @@ -278,6 +285,16 @@ export function CombinedDiffView({ estimateSize: () => ESTIMATE, overscan: 4, rangeExtractor, + // A view with no height (hidden behind a maximized tool window) makes the library render nothing, + // skipping `rangeExtractor`: report at least 1 px so the focused and unsaved blocks stay mounted. + observeElementRect: (instance, cb) => + observeElementRect(instance, (rect) => cb({ ...rect, height: Math.max(rect.height, 1) })), + // While the view is hidden its blocks are 0 px tall: recording that would collapse every block onto + // one offset and mount them all. Keep the last known size (or the estimate) instead. + measureElement: (node, entry, instance) => + measureElement(node, entry, instance) || + instance.itemSizeCache.get(keys[instance.indexFromElement(node)]!) || + ESTIMATE, // A correction for a block above moves the view by its delta from wherever it is now: a `scrollTo` // (the library's offset plus the delta) can drop wheel scrolling still in flight in WebKit. scrollToFn: (offset, options, instance) => { diff --git a/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx b/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx index 7a068e087..01553a8e0 100644 --- a/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx +++ b/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx @@ -144,6 +144,82 @@ describe("the all-in-one diff, staged edits", () => { expect(block(paths[0]!)).not.toBeNull(); }); + it("with autosave off, keeps them while the view has no height, as when a maximized tool window hides it", async () => { + let height = 600; + const observers: Array<(entries: unknown[]) => void> = []; + vi.stubGlobal( + "ResizeObserver", + class { + constructor(cb: (entries: unknown[]) => void) { + observers.push(cb); + } + observe() {} + unobserve() {} + disconnect() {} + }, + ); + const heightOf = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "clientHeight")!; + Object.defineProperty(HTMLElement.prototype, "clientHeight", { configurable: true, get: () => height }); + try { + await editAndScrollAway(false); + height = 0; + act(() => observers.forEach((cb) => cb([]))); + await act(() => new Promise((r) => setTimeout(r, 20))); + expect(savedStaged).toEqual([]); + expect(block(paths[0]!)).not.toBeNull(); + } finally { + Object.defineProperty(HTMLElement.prototype, "clientHeight", heightOf); + vi.unstubAllGlobals(); + } + }); + + it("with autosave off, keeps them and mounts only a few blocks while the blocks themselves have no height", async () => { + let height = 600; + const watched = new Set(); + const observers: Array<(entries: unknown[]) => void> = []; + vi.stubGlobal( + "ResizeObserver", + class { + constructor(cb: (entries: unknown[]) => void) { + observers.push(cb); + } + observe(el: Element) { + watched.add(el); + } + unobserve(el: Element) { + watched.delete(el); + } + disconnect() {} + }, + ); + const descriptors = (["clientHeight", "offsetHeight"] as const).map( + (name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)!] as const, + ); + for (const [name] of descriptors) + Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get: () => height }); + try { + savedStaged.length = 0; + useProject.setState({ settings: { files: { autoSave: false } } as never }); + render(); + const view = await editableSide(paths[0]!, "b"); + act(() => view.dispatch({ changes: { from: 0, insert: "EDIT " }, userEvent: "input" })); + // `display: none` on the island: the container and every block measure 0 px. + height = 0; + act(() => + observers.forEach((cb) => + cb([...watched].map((target) => ({ target, borderBoxSize: [{ blockSize: 0, inlineSize: 0 }] }))), + ), + ); + await act(() => new Promise((r) => setTimeout(r, 20))); + expect(savedStaged).toEqual([]); + expect(block(paths[0]!)).not.toBeNull(); + expect(document.querySelectorAll("[data-combined-block]").length).toBeLessThanOrEqual(6); + } finally { + for (const [name, descriptor] of descriptors) Object.defineProperty(HTMLElement.prototype, name, descriptor); + vi.unstubAllGlobals(); + } + }); + it("with autosave on, saves them to the index once scrolled away", async () => { await editAndScrollAway(true); expect(block(paths[0]!)).toBeNull(); From c4f7fec86c0f28759cafb9f50caca20d2d5459e6 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:42:28 +0800 Subject: [PATCH 09/66] fix(build): keep output the channel delivers after the build result (#6988) Tauri delivers channel messages over 8 KiB through an async fetch and holds later ones back, so output can arrive after the command result. Output and step events of the latest build are still applied after it finished, until another build takes the window. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- src/features/build/build.test.tsx | 68 +++++++++++++++++++++++++++++++ src/features/build/store.ts | 24 +++++++++-- 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/src/features/build/build.test.tsx b/src/features/build/build.test.tsx index 03152e432..3b72af6d3 100644 --- a/src/features/build/build.test.tsx +++ b/src/features/build/build.test.tsx @@ -276,6 +276,74 @@ describe("build feature", () => { }); }); + it("keeps output the channel delivers after the build result (an >8 KiB line is fetched late)", async () => { + // Tauri sends a channel message over 8 KiB through an async fetch and holds every later message + // back to keep their order, so the command's result can arrive before the rest of the output. + const run = startBuild("build"); + await act(async () => {}); + const long = `${"w".repeat(8_307)}`; + const warning = warn("/p/src/B.java", 2); + await act(async () => { + fake.emit!({ kind: "output", text: "short\n", stderr: false }); + fake.resolve(result([warning], true)); + await run; + }); + expect(useBuildRun.getState().status).toBe("success"); + await act(async () => { + fake.emit!({ kind: "output", text: `${long}\n`, stderr: false }); + fake.emit!({ kind: "output", text: "stream-done\n", stderr: false }); + fake.emit!({ kind: "message", message: warning }); + fake.emit!({ kind: "progress", message: "late", fraction: null }); + fake.emit!({ kind: "output", text: "\nProcess finished with exit code 0\n", stderr: false }); + await new Promise((r) => setTimeout(r, 30)); + }); + const s = useBuildRun.getState(); + expect(s.lines.map((l) => l.text)).toEqual(["short", long, "stream-done", "", "Process finished with exit code 0"]); + // The result already carries every message; a late one is not added twice. + expect(s.messages).toEqual([warning]); + expect(s.message).toBeNull(); + + // A newer build owns the console: the old channel's stragglers are dropped. + const stale = fake.emit!; + const second = startBuild("build"); + await act(async () => {}); + await act(async () => { + stale({ kind: "output", text: "stale\n", stderr: false }); + await new Promise((r) => setTimeout(r, 30)); + }); + expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale"); + await act(async () => { + fake.resolve(result([], true)); + await second; + }); + }); + + it("drops a finished build's late events once a launch build owns the Build window", async () => { + const run = startBuild("build"); + await act(async () => {}); + const late = fake.emit!; + await act(async () => { + fake.resolve(result([], true)); + await run; + }); + const follower = followLaunchBuild(44 as never, "Build before launch: App"); + follower.onEvent({ kind: "started", system: "maven", title: "launch" }); + await act(async () => { + late({ kind: "step", command: "stale-step", cwd: "/stale" }); + late({ kind: "output", text: "stale\n", stderr: false }); + await new Promise((r) => setTimeout(r, 30)); + }); + const s = useBuildRun.getState(); + expect(s.lines.map((l) => l.text)).not.toContain("stale"); + expect(s.stepCwd).toBeNull(); + follower.finish("success"); + await act(async () => { + late({ kind: "output", text: "stale2\n", stderr: false }); + await new Promise((r) => setTimeout(r, 30)); + }); + expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale2"); + }); + it("streams a failing build into the tree and console, then notifies and clears next time", async () => { const run = startBuild("build"); await act(async () => {}); diff --git a/src/features/build/store.ts b/src/features/build/store.ts index ab2ccbfd5..631cc202e 100644 --- a/src/features/build/store.ts +++ b/src/features/build/store.ts @@ -237,6 +237,9 @@ export async function startCompileFile(file: string, activate = true): Promise void, ): Promise { const ownsBuild = () => useBuildRun.getState().request === request; + currentBuild = request; + // Tauri delivers a channel message over 8 KiB through an async fetch and holds the later ones back + // to keep their order, so output can still arrive after the command's result. It belongs to this + // build until another build (or a launch build) takes the window; messages and progress are complete + // in the result by then. + const accepts = () => currentBuild === request; + let finished = false; await maybeEditorService() ?.saveAll() .catch(() => undefined); @@ -258,15 +268,17 @@ async function executeBuild( timer = undefined; const events = queue; queue = []; - if (!ownsBuild() || !events.length) return; + if (!accepts() || !events.length) return; let s = useBuildRun.getState(); - for (const e of events) s = { ...s, ...applyBuildEvent(s, e) }; + for (const e of events) { + if (!finished || e.kind === "output" || e.kind === "step") s = { ...s, ...applyBuildEvent(s, e) }; + } useBuildRun.setState(s); - if (s.message) + if (!finished && s.message) upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: s.message, fraction: null, done: false, cancel }); }; const onEvent = (e: BuildEvent) => { - if (!ownsBuild()) return; + if (!accepts()) return; queue.push(e); timer ??= setTimeout(flush, 16); }; @@ -276,6 +288,7 @@ async function executeBuild( result = await invoke(useBuildRun.getState().files, onEvent); if (!ownsBuild()) return null; flush(); + finished = true; const status: BuildStatus = result.success ? "success" : "failed"; useBuildRun.setState({ status, @@ -311,6 +324,7 @@ async function executeBuild( } catch (e) { if (!ownsBuild()) return null; flush(); + finished = true; if (isCancelled(e)) { useBuildRun.setState({ status: "cancelled", files: [], message: null }); } else { @@ -385,6 +399,7 @@ export function followLaunchBuild( const take = () => { if (owned || isBuilding()) return; owned = true; + currentBuild = null; const previous = useBuildRun.getState().files; useBuildRun.setState({ ...INITIAL, request, kind: "build", title, status: "running", files: previous }); setContext(BUILD_LAST_STATUS, null); @@ -458,6 +473,7 @@ export function rerunBuild() { } export function resetBuildRun() { + currentBuild = null; stopBuild(); removeTask(BUILD_TASK_ID); setContext(BUILD_RUNNING, false); From a441b2a906ee0fc0b2db72300a02c813be307627 Mon Sep 17 00:00:00 2001 From: Chris-young42 <3101940893@qq.com> Date: Mon, 30 Nov 2026 17:42:42 +0800 Subject: [PATCH 10/66] fix(java): remove extra spaces from annotation completions (#6989) JDT LS appends a space to annotation completions; it is dropped when nothing follows that needs a separator, so no trailing whitespace after @Override or space before the parenthesis. Co-authored-by: Chris-young42 <175955694+Chris-young42@users.noreply.github.com> --- src/editor/lsp/completion.test.ts | 57 +++++++++++++++++++++++++++++++ src/editor/lsp/completion.ts | 28 ++++++++++++--- 2 files changed, 81 insertions(+), 4 deletions(-) diff --git a/src/editor/lsp/completion.test.ts b/src/editor/lsp/completion.test.ts index 75d5c2194..fce8d4329 100644 --- a/src/editor/lsp/completion.test.ts +++ b/src/editor/lsp/completion.test.ts @@ -283,6 +283,63 @@ describe("applying completions", () => { expect(view.state.selection.main.head).toBe(14); }); + it.each([ + { doc: " @Over|\n", prefix: "Over", label: "Override", expected: " @Override|\n" }, + { doc: '@Supp|("unused")', prefix: "Supp", label: "SuppressWarnings", expected: '@SuppressWarnings|("unused")' }, + { doc: "@java.lang.Over|", prefix: "Over", label: "Override", expected: "@java.lang.Override|" }, + { + doc: "@Over| public void run() {}", + prefix: "Over", + label: "Override", + expected: "@Override| public void run() {}", + }, + { + doc: "@Over|public void run() {}", + prefix: "Over", + label: "Override", + expected: "@Override |public void run() {}", + }, + { doc: "implements Run|\n", prefix: "Run", label: "Runnable", expected: "implements Runnable |\n" }, + ])("applies a Java interface completion in $doc", ({ doc, prefix, label, expected }) => { + const { view, req, pos } = setup(doc); + const suggestion = item({ label, kind: "interface", insertText: `${label} `, isSnippet: true }); + apply(view, makeCompletion(suggestion, { ...req, language: "java" }), pos - prefix.length); + expect(view.state.doc.toString()).toBe(expected.replace("|", "")); + expect(view.state.selection.main.head).toBe(expected.indexOf("|")); + }); + + it("replaces a Java annotation name before its existing arguments with Tab", () => { + const { view, req, pos } = setup('@Sup|pressWarnings("unused")'); + const suggestion = item({ + label: "SuppressWarnings", + kind: "interface", + insertText: "SuppressWarnings ", + isSnippet: true, + replaceRange: { start: { line: 0, col: 1 }, end: { line: 0, col: pos } }, + replaceRangeTab: { start: { line: 0, col: 1 }, end: { line: 0, col: 17 } }, + }); + applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, pos, "replace"); + expect(view.state.doc.toString()).toBe('@SuppressWarnings("unused")'); + expect(view.state.selection.main.head).toBe(17); + }); + + it("keeps spacing in a Java annotation attribute completion", () => { + const { view, req } = setup("@Tag(va|)"); + const suggestion = item({ label: "value", kind: "field", insertText: "value = ", isSnippet: true }); + apply(view, makeCompletion(suggestion, { ...req, language: "java" }), 5); + expect(view.state.doc.toString()).toBe("@Tag(value = )"); + expect(view.state.selection.main.head).toBe(13); + }); + + it("accounts for what follows each Java annotation when completing at several carets", () => { + const { view, req } = setup("@Ov|\n@Ovpublic void run() {}", "", [EditorState.allowMultipleSelections.of(true)]); + view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(3), EditorSelection.cursor(7)]) }); + const suggestion = item({ label: "Override", kind: "interface", insertText: "Override ", isSnippet: true }); + applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, 3, "insert"); + expect(view.state.doc.toString()).toBe("@Override\n@Override public void run() {}"); + expect(view.state.selection.ranges.map((r) => r.head)).toEqual([9, 20]); + }); + it("lets Tab step out of the parentheses a completion inserted", () => { const { view, req } = setup("service.cr|", "", [tabOut]); applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert"); diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index ab2a0bd23..229a852b2 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -245,6 +245,23 @@ function applyLsp(view: EditorView, completion: Completion, from: number, to: nu applyLspCompletion(view, completion, from, to, replaceMode ? "replace" : "insert"); } +function completionInsertText( + item: CompletionItem, + language: string | null, + doc: Text, + from: number, + to: number, +): string { + const { insertText } = item; + // JDT LS can append a space to a bare annotation name. It is useful only as a separator. + if (language !== "java" || item.kind !== "interface" || insertText !== `${item.label} `) return insertText; + const line = doc.lineAt(from); + const before = line.text.slice(0, from - line.from); + const after = doc.sliceString(to, to + 2); + if (!/@(?:[\p{L}\p{N}\p{M}_$]+\.)*$/u.test(before) || identifierEnd(after, 0) > 0) return insertText; + return item.label; +} + /** ↵ (`insert`) or ⇥ (`replace`: also overwrites the rest of the identifier). */ export function applyLspCompletion( view: EditorView, @@ -291,6 +308,7 @@ export function applyLspCompletion( return; } + const insertText = completionInsertText(item, req.language, state.doc, start, end); let insertedParens: ReturnType = null; let bareCall: number | null = null; if (item.isSnippet) { @@ -300,7 +318,7 @@ export function applyLspCompletion( start = tr.changes.mapPos(start, 1); end = tr.changes.mapPos(end, 1); } - const source = lspSnippetToCm(item.insertText, snippetVariables(req.path)); + const source = lspSnippetToCm(insertText, snippetVariables(req.path)); applySnippet(view, [{ from: start, to: end, snippet: source }], completion); // A call snippet without a stop (`ArrayList<>()`): the caret goes inside until // signature help says there is nothing to pass. @@ -320,7 +338,7 @@ export function applyLspCompletion( ? callParens(item, state.doc.lineAt(start), start, end) : null; insertedParens = parens; - const changes = state.changes([...extra, { from: start, to: end, insert: item.insertText + (parens ? "()" : "") }]); + const changes = state.changes([...extra, { from: start, to: end, insert: insertText + (parens ? "()" : "") }]); const caret = changes.mapPos(end, 1) - (parens === "inside" ? 1 : 0); view.dispatch({ changes, @@ -391,11 +409,13 @@ function applyAtCarets( // Parentheses depend on what follows each site: `a.cr|` gets them, `b.cr|()` does not. const textAt = (site: { from: number; to: number }): { text: string; caret: number } => { - if (item.isSnippet) return lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path)); + const { language, path } = completion.req; + const insertText = completionInsertText(item, language, state.doc, site.from, site.to); + if (item.isSnippet) return lspSnippetToPlainWithCaret(insertText, snippetVariables(path)); const parens = editorPrefs().completion.insertParentheses ? callParens(item, state.doc.lineAt(site.from), site.from, site.to) : null; - const text = item.insertText + (parens ? "()" : ""); + const text = insertText + (parens ? "()" : ""); return { text, caret: text.length - (parens === "inside" ? 1 : 0) }; }; const texts = sites.map(textAt); From 0104ed63c1e4e3c628dfd2871d0eb39ac024fa96 Mon Sep 17 00:00:00 2001 From: Bin <106022674+ffgenius@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:42:57 +0800 Subject: [PATCH 11/66] fix(project-tree): open external files on double-click only (#6993) Single-click in the project tree opened files associated with an external application. Those now open on double-click only. Co-authored-by: ffgenius <106022674+ffgenius@users.noreply.github.com> --- .../project-tree/ProjectView.test.tsx | 23 +++++++++++++++++++ src/features/project-tree/ProjectView.tsx | 2 ++ 2 files changed, 25 insertions(+) diff --git a/src/features/project-tree/ProjectView.test.tsx b/src/features/project-tree/ProjectView.test.tsx index 277cdd6fa..163e8e1dc 100644 --- a/src/features/project-tree/ProjectView.test.tsx +++ b/src/features/project-tree/ProjectView.test.tsx @@ -7,6 +7,7 @@ import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/pla import { usePlatform } from "@/platform/platformInfo"; import { provideEditorService, + registerExternalFileOpenHandler, registerProjectViewRoot, setFileDecorations, type EditorService, @@ -493,6 +494,28 @@ describe("ProjectView", () => { expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true }); }); + it("selects a file opened externally on single click and opens it on double click", async () => { + fs = new MemoryFs({ "/w/acme/notes.docx": "x" }, ROOT); + setProjectFsForTests(fs, ROOT); + initProjectTree(ROOT, "acme"); + const disposeExternal = registerExternalFileOpenHandler({ + id: "test.external", + matches: (path) => path.endsWith(".docx"), + open: vi.fn(async () => true), + }); + try { + const { row, rows } = setup(); + await waitFor(() => expect(rows()).toContain("notes.docx")); + const content = row("notes.docx").querySelector("[data-project-path]")!; + fireEvent.click(content, { detail: 1 }); + expect(openFile).not.toHaveBeenCalled(); + fireEvent.doubleClick(row("notes.docx")); + expect(openFile).toHaveBeenLastCalledWith("/w/acme/notes.docx", { preview: undefined, focus: true }); + } finally { + disposeExternal(); + } + }); + it("opens a selected file in a read-only Quick Preview with Space without creating an editor tab", async () => { dispatchViaKeymap(); ipc.fsReadText.mockResolvedValue(ok("# Preview\n\nRead without opening a tab.")); diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsx index bda69a8b6..fabcfa7d5 100644 --- a/src/features/project-tree/ProjectView.tsx +++ b/src/features/project-tree/ProjectView.tsx @@ -34,6 +34,7 @@ import { macStroke, strokeOf } from "@/platform/keymap"; import { OWNS_FILE_DROP, getFileDecoration, + opensExternally, prepareMenuGroups, useFileDecoration, useFileDecorations, @@ -718,6 +719,7 @@ export function ProjectView() { if (o.singleClickExpand) toggleExpanded(node); return; } + if (opensExternally(node.path)) return; if (!o.singleClickOpen && !previewTabEnabled()) return; const opts = { preview: o.singleClickOpen ? undefined : true, focus: false }; if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts); From c085f52b594b8ab1b51dd243ecc8dc237d3ff3ae Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:43:14 +0800 Subject: [PATCH 12/66] fix(editor): paste an image from the Markdown editor's context menu without WebKit's Paste callout (#6994) On macOS the context-menu Paste in a Markdown editor called execCommand(paste), which shows the WebKit Paste callout. Images and copied image files are read through the backend instead; text takes the native path. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- src/editor/core/cm/clipboard.test.ts | 70 ++++++++++++++++++++++++++++ src/editor/core/cm/clipboard.ts | 17 ++++++- src/editor/core/cm/markdownImages.ts | 37 +++++++++++---- 3 files changed, 113 insertions(+), 11 deletions(-) diff --git a/src/editor/core/cm/clipboard.test.ts b/src/editor/core/cm/clipboard.test.ts index f3faae2ac..18b188c47 100644 --- a/src/editor/core/cm/clipboard.test.ts +++ b/src/editor/core/cm/clipboard.test.ts @@ -3,8 +3,10 @@ import { EditorSelection, EditorState, Transaction, type Extension } from "@code import { indentService, indentUnit } from "@codemirror/language"; import { EditorView } from "@codemirror/view"; import { commands } from "@/platform/ipc"; +import { usePlatform } from "@/platform/platformInfo"; import { EDITOR_EXTRA_DEFAULTS, type LineClipboardOptions } from "@/platform/editorSettings"; import { isRemoteWindow } from "@/platform/remote"; +import { useWebConnection } from "@/platform/webBridge"; import { clearClipboardHistory, clipboardHistory, @@ -27,6 +29,7 @@ const views: EditorView[] = []; beforeEach(() => { clearClipboardHistory(); vi.stubGlobal("__TAURI_INTERNALS__", {}); + usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => false) }); Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: vi.fn(() => false) }); }); @@ -211,6 +214,73 @@ it.each([ expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/); }); +describe("macOS menu paste into Markdown reads the clipboard natively", () => { + // WebKit's execCommand("paste") from a menu makes macOS show a "Paste" callout. + function markdownView() { + usePlatform.setState({ os: "macos" }); + const view = new EditorView({ + extensions: [ + clipboardDocumentPath.of("/p/a.md"), + clipboardFilesExtension, + markdownImages({ path: "/p/a.md", folder: "assets", pattern: "image-{timestamp}" }), + ], + parent: document.body, + }); + views.push(view); + vi.mocked(document.queryCommandSupported).mockReturnValue(true); + return view; + } + + it("saves a copied image without the webview's paste", async () => { + vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] }); + vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: "data:image/png;base64,iVBORw==" }); + const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null }); + const view = markdownView(); + await pasteEditorClipboard(view); + await vi.waitFor(() => expect(view.state.doc.toString()).toMatch(/^!\[\]\(assets\/image-\d{8}-\d{6}\.png\)$/)); + expect(create.mock.calls[0]![1]).toBe("iVBORw=="); + expect(document.execCommand).not.toHaveBeenCalled(); + }); + + it("keeps the execCommand paste in web mode, where the backend has no clipboard", async () => { + useWebConnection.setState({ active: true }); + try { + const list = vi.spyOn(commands, "clipboardFileList"); + vi.mocked(document.execCommand).mockReturnValue(true); + await pasteEditorClipboard(markdownView()); + expect(document.execCommand).toHaveBeenCalledWith("paste"); + expect(list).not.toHaveBeenCalled(); + } finally { + useWebConnection.setState({ active: false }); + } + }); + + it("pastes the text when the clipboard holds no image", async () => { + vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] }); + vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: null }); + vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: "plain" }); + const view = markdownView(); + await pasteEditorClipboard(view); + expect(view.state.doc.toString()).toBe("plain"); + expect(document.execCommand).not.toHaveBeenCalled(); + }); + + it("embeds a copied image file like the paste event, not as a path", async () => { + vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/src/pic.png"] }); + const image = vi.spyOn(commands, "clipboardImage"); + vi.stubGlobal("__TAURI_INTERNALS__", { + invoke: vi.fn(async () => "data:image/png;base64,iVBORw=="), + }); + const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null }); + const view = markdownView(); + await pasteEditorClipboard(view); + await vi.waitFor(() => expect(view.state.doc.toString()).toBe("![](assets/pic.png)")); + expect(create.mock.calls[0]![0]).toMatch(/assets\/pic\.png$/); + expect(image).not.toHaveBeenCalled(); + expect(document.execCommand).not.toHaveBeenCalled(); + }); +}); + it("does not insert into a read-only editor", async () => { const list = vi.spyOn(commands, "clipboardFileList"); const view = new EditorView({ extensions: [clipboardFilesExtension, EditorState.readOnly.of(true)] }); diff --git a/src/editor/core/cm/clipboard.ts b/src/editor/core/cm/clipboard.ts index 702cf39de..5f74eca91 100644 --- a/src/editor/core/cm/clipboard.ts +++ b/src/editor/core/cm/clipboard.ts @@ -1,10 +1,13 @@ import { EditorSelection, Facet, Prec, type EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard"; +import { call, commands, isTauri } from "@/platform/ipc"; +import { usePlatform } from "@/platform/platformInfo"; +import { isWebMode } from "@/platform/webBridge"; import type { LinePasteMode } from "@/platform/editorSettings"; import { isRemoteWindow } from "@/platform/remote"; import { isLinewiseClipboardText } from "../clipboardHistory"; -import { isMarkdown, relativeImagePath } from "./markdownImages"; +import { isMarkdown, pasteMarkdownImages, relativeImagePath } from "./markdownImages"; export const clipboardDocumentPath = Facet.define({ combine: (paths) => paths[0] ?? "" }); @@ -125,9 +128,19 @@ export function pasteEditorText(view: EditorView, text: string) { export async function pasteEditorClipboard(view: EditorView) { if (!view.dom.isConnected || view.state.readOnly) return; + const markdown = isMarkdown(view.state.facet(clipboardDocumentPath)); + // macOS WebKit asks the user to confirm execCommand("paste") from the editor context menu with a "Paste" callout + // (the app-menu Edit > Paste is a native paste: selector and never gets here); the + // backend reads the image (or copied image files) without asking, so text then takes the native path below. + const native = markdown && isTauri() && !isWebMode() && usePlatform.getState().os === "macos"; try { + if (native) { + const paths: string[] = await call(commands.clipboardFileList()).catch(() => []); + const image = paths.length ? null : await call(commands.clipboardImage()).catch(() => null); + if (pasteMarkdownImages(view, image ?? paths)) return; + } // Successful native paste preserves image blobs and may complete after execCommand returns. - if (isMarkdown(view.state.facet(clipboardDocumentPath)) && document.queryCommandSupported("paste")) { + if (markdown && !native && document.queryCommandSupported("paste")) { view.focus(); if (document.execCommand("paste")) return; } diff --git a/src/editor/core/cm/markdownImages.ts b/src/editor/core/cm/markdownImages.ts index 6605f5b03..54af422c6 100644 --- a/src/editor/core/cm/markdownImages.ts +++ b/src/editor/core/cm/markdownImages.ts @@ -111,6 +111,29 @@ interface ImageOptions { pattern: string; } +type ImageSource = () => Promise<{ blob: Blob | string; name: string }>; + +// OS paths belong to this client even in a remote project. +const fileSource = + (path: string): ImageSource => + async () => ({ blob: await invokeLocal("fs_read_image", { path }), name: path.replace(/^.*[\\/]/, "") }); + +const imageInserters = new WeakMap void>(); + +/** + * Saves and links images the menu Paste read natively, as a paste event would: image files by path, or a + * raw clipboard image as a PNG data URL. False when `view` does not take images (not Markdown, read-only, + * or not image files). + */ +export function pasteMarkdownImages(view: EditorView, images: string[] | string): boolean { + const insert = imageInserters.get(view); + if (!insert || view.state.readOnly) return false; + if (typeof images === "string") insert([async () => ({ blob: images, name: "" })]); + else if (images.length && images.every((p) => IMAGE_FILE.test(p))) insert(images.map(fileSource)); + else return false; + return true; +} + export function markdownImages(options: ImageOptions): Extension { if (!isMarkdown(options.path)) return []; return ViewPlugin.fromClass( @@ -118,7 +141,9 @@ export function markdownImages(options: ImageOptions): Extension { alive = true; pending = new Set<{ from: number; to: number }>(); unregister: () => void; + readonly insertSources = (sources: ImageSource[]) => this.insert(sources); constructor(readonly view: EditorView) { + imageInserters.set(view, this.insertSources); this.unregister = registerFileDropHandler((paths, x, y) => { const rect = view.dom.getBoundingClientRect(); if ( @@ -130,14 +155,7 @@ export function markdownImages(options: ImageOptions): Extension { view.state.readOnly ) return false; - this.insert( - paths.map((path) => async () => { - // OS paths belong to this client even in a remote project. - const url = await invokeLocal("fs_read_image", { path }); - return { blob: url, name: path.replace(/^.*[\\/]/, "") }; - }), - view.posAtCoords({ x, y }) ?? view.state.selection.main.head, - ); + this.insert(paths.map(fileSource), view.posAtCoords({ x, y }) ?? view.state.selection.main.head); return true; }); } @@ -150,8 +168,9 @@ export function markdownImages(options: ImageOptions): Extension { destroy() { this.alive = false; this.unregister(); + if (imageInserters.get(this.view) === this.insertSources) imageInserters.delete(this.view); } - insert(sources: Array<() => Promise<{ blob: Blob | string; name: string }>>, position?: number) { + insert(sources: ImageSource[], position?: number) { const selection = this.view.state.selection.main; const range = { from: position ?? selection.from, to: position ?? selection.to }; this.pending.add(range); From fe21c67537cb5c0a7841447a4ca2e54acde1e9ba Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 18:50:10 +0900 Subject: [PATCH 13/66] fix(debugger): do not open lldb-dap's disassembly pseudo paths as files (#6961) lldb-dap reports frames without debug info with a sourceReference and a pseudo path such as libswiftCore.dylib`swift_willThrow, which opened as a missing file. An absolute path that does not exist on a referenced source is dropped, so the stop selects the first frame with source. Closes #6960 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-dap/src/lib.rs | 15 ++++++++++++++- crates/ide-dap/src/tests.rs | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 19f381371..9379b7834 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -614,6 +614,15 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult`) stay. +fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool { + let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0); + reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists() +} + /// DAP stack frame → [`StackFrame`] (1-based → 0-based). pub(crate) fn frame_from(f: &Value) -> StackFrame { let source = f.get("source"); @@ -626,7 +635,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame { StackFrame { id: f.get("id").and_then(Value::as_i64).unwrap_or_default(), name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(), - path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into), + path: source + .and_then(|s| s.get("path")) + .and_then(Value::as_str) + .filter(|p| !is_pseudo_path(source, p)) + .map(Into::into), line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), presentation_hint: hint, diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index 4b71c289b..6fc6bed78 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() { assert!(json.get("instructionPointerReference").is_none()); } +#[test] +fn frames_drop_pseudo_paths_of_referenced_sources() { + let frame = |path: &str, reference: i64| { + frame_from(&json!({"id": 1, "name": "f", "line": 1, + "source": {"path": path, "sourceReference": reference}})) + .path + }; + let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow"; + assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly"); + assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent"); + let here = env!("CARGO_MANIFEST_DIR"); + assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file"); + assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path"); +} + #[tokio::test] async fn smart_step_into_and_reset_frame() { let h = harness(Script::default()); From 59bcf7eac53299976f7dadc3fe675110f36a8986 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:50:29 +0800 Subject: [PATCH 14/66] fix(refactor): keep external changes when a file move's reference edits are rejected (#6990) FileMoves::perform restored its pre-edit snapshots when the reference edits were rejected, overwriting a change another program wrote after the snapshot. apply_edit is transactional and leaves nothing behind on error, so a rejected edit is now returned without a restore; a failed move still rolls back the applied edits. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-workspace/src/file_moves.rs | 42 ++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/ide-workspace/src/file_moves.rs b/crates/ide-workspace/src/file_moves.rs index 49825af08..be3e5cf93 100644 --- a/crates/ide-workspace/src/file_moves.rs +++ b/crates/ide-workspace/src/file_moves.rs @@ -99,7 +99,9 @@ impl FileMoves { /// Applies `edit` (paths as before the move, as `workspace/willRenameFiles` /// returns them), then performs `moves`. Edited files are snapshotted in - /// Local History first. On failure everything done so far is rolled back. + /// Local History first. `apply_edit` must be transactional: on error it leaves none of + /// its own changes behind, so a rejected edit keeps external changes. A failed + /// file move rolls back the applied edits. /// Returns the id for [`undo`](Self::undo). pub fn perform( &self, @@ -134,11 +136,8 @@ impl FileMoves { } before.push(text); } - if !paths.is_empty() - && let Err(e) = apply_edit(edit) - { - restore(documents, &paths, &before); - return Err(e); + if !paths.is_empty() { + apply_edit(edit)?; } if let Err(e) = crate::file_ops::move_files(moves) { restore(documents, &paths, &before); @@ -305,6 +304,37 @@ mod tests { assert_eq!(fs::read_to_string(root.join("Use.java")).unwrap(), "Bar f; // edited\n"); } + #[test] + fn rejected_reference_edits_preserve_changes_after_the_snapshot() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::write(root.join("source.ts"), "source\n").unwrap(); + fs::write(root.join("main.ts"), "old\n").unwrap(); + let docs = documents(); + let mut edit = WorkspaceEdit { + files: vec![FileEdit::Edit { + path: root.join("main.ts").into(), + version: None, + edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "updated".into() }], + }], + ..Default::default() + }; + docs.prepare_workspace_edit(&mut edit).unwrap(); + let apply_edit = |edit: &WorkspaceEdit| { + // An external writer lands after perform captured its rollback text. + fs::write(root.join("main.ts"), "external edit after snapshot\n").unwrap(); + docs.apply_file_move_edits(edit) + }; + let moves = FileMoves::new(); + let mv = vec![FileMove { from: root.join("source.ts").into(), to: root.join("renamed.ts").into() }]; + let error = moves.perform(&docs, None, &mv, &edit, "Move", &apply_edit).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync); + assert_eq!(fs::read_to_string(root.join("main.ts")).unwrap(), "external edit after snapshot\n"); + assert_eq!(fs::read_to_string(root.join("source.ts")).unwrap(), "source\n"); + assert!(!root.join("renamed.ts").exists()); + assert_eq!(moves.last(), None); + } + #[test] fn moved_paths() { let mv = vec![FileMove { from: "/p/a".into(), to: "/p/b/a".into() }]; From a66c9e6d05c2c97ad9386986f9be311217d1b1dd Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:50:44 +0800 Subject: [PATCH 15/66] fix(vcs): retry git status without rename detection when a partial clone cannot fetch a blob (#6987) In a blobless partial clone rename detection needs a staged blob it cannot fetch (Restricted Mode sets GIT_NO_LAZY_FETCH, or the promisor is unreachable) and git status fails. Status retries once with --no-renames when git reports the promisor remote. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-vcs/src/status.rs | 20 +++- crates/ide-vcs/tests/partial_clone.rs | 144 ++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 crates/ide-vcs/tests/partial_clone.rs diff --git a/crates/ide-vcs/src/status.rs b/crates/ide-vcs/src/status.rs index b6548f17e..5d60e25fd 100644 --- a/crates/ide-vcs/src/status.rs +++ b/crates/ide-vcs/src/status.rs @@ -311,6 +311,22 @@ fn network_args(r: &Repo) -> Vec { NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect() } +/// Runs `git status`; when rename detection needs a blob that cannot be fetched (Restricted Mode +/// sets `GIT_NO_LAZY_FETCH`, or the promisor remote is unreachable), retries once without it. +/// The message is stable because `cli::command` pins `LC_ALL=C`. +fn run_status(r: &Repo, mut args: Vec<&str>) -> IdeResult { + let out = crate::cli::run_raw_env(r.root(), &args, None, &read_only())?; + if out.code == Some(0) { + return Ok(out); + } + if String::from_utf8_lossy(&out.stderr).contains("promisor remote") { + let at = args.iter().position(|a| *a == "status").map_or(args.len(), |i| i + 1); + args.insert(at, "--no-renames"); + return crate::cli::run_env(r.root(), &args, None, &read_only()); + } + Err(crate::cli::failure(&args, &out.stderr, &out.stdout, out.code)) +} + /// `git status --porcelain=v2`: what git lists, unreadable directories skipped. /// In Restricted Mode git compares content without the repository's clean/process /// filters and doesn't ask submodules for their own status (which runs their config). @@ -323,7 +339,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult { if !crate::execution_allowed() { args.push("--ignore-submodules=dirty"); } - let out = crate::cli::run_env(r.root(), &args, None, &read_only())?; + let out = run_status(r, args)?; Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored)) } @@ -340,7 +356,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe } args.push("--"); args.extend(paths.iter().map(String::as_str)); - let out = crate::cli::run_env(r.root(), &args, None, &read_only())?; + let out = run_status(r, args)?; Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored)) } diff --git a/crates/ide-vcs/tests/partial_clone.rs b/crates/ide-vcs/tests/partial_clone.rs new file mode 100644 index 000000000..b79c984d1 --- /dev/null +++ b/crates/ide-vcs/tests/partial_clone.rs @@ -0,0 +1,144 @@ +//! Partial clones (`--filter=blob:none`) with a sparse checkout: blobs outside the +//! checkout are never fetched, and gitoxide's status cannot read them. + +use ide_vcs::{ChangeKind, LogQuery, Repos}; +use std::path::Path; +use std::process::Command; + +fn git(dir: &Path, args: &[&str]) { + let out = Command::new("git") + .current_dir(dir) + .args(["-c", "init.defaultBranch=main", "-c", "core.autocrlf=false", "-c", "protocol.file.allow=always"]) + .args(args) + .env("GIT_TERMINAL_PROMPT", "0") + .output() + .expect("git runs"); + assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn git_available() -> bool { + Command::new("git").arg("--version").output().is_ok_and(|o| o.status.success()) +} + +fn file_url(path: &Path) -> String { + let path = path.to_string_lossy().replace('\\', "/"); + format!("file:///{}", path.trim_start_matches('/')) +} + +/// A blobless, cone-mode sparse clone of a small source repository; `docs/` and `app/` blobs stay remote. +fn blobless_clone(base: &Path) -> std::path::PathBuf { + let source = base.join("source"); + std::fs::create_dir_all(source.join("docs")).unwrap(); + std::fs::create_dir_all(source.join("app")).unwrap(); + git(&source, &["init", "-q"]); + git(&source, &["config", "user.name", "Test User"]); + git(&source, &["config", "user.email", "test@example.com"]); + git(&source, &["config", "commit.gpgsign", "false"]); + std::fs::write(source.join("README.md"), "hello\n").unwrap(); + let guide: String = (1..=200).map(|i| format!("line {i}\n")).collect(); + std::fs::write(source.join("docs/guide.txt"), &guide).unwrap(); + std::fs::write(source.join("app/main.rs"), "fn main() {}\n").unwrap(); + git(&source, &["add", "-A"]); + git(&source, &["commit", "-q", "-m", "init"]); + + let bare = base.join("bare.git"); + git(base, &["clone", "-q", "--bare", "source", "bare.git"]); + git(&bare, &["config", "uploadpack.allowFilter", "true"]); + git(&bare, &["config", "uploadpack.allowAnySHA1InWant", "true"]); + + let work = base.join("work"); + git(base, &["clone", "-q", "--filter=blob:none", "--sparse", &file_url(&bare), "work"]); + git(&work, &["config", "user.name", "Test User"]); + git(&work, &["config", "user.email", "test@example.com"]); + // A global `status.renames=false` would make the baseline pass without the fix. + git(&work, &["config", "status.renames", "true"]); + assert!(!work.join("app/main.rs").exists(), "app/ is outside the sparse checkout"); + work +} + +#[test] +fn blobless_sparse_clone_keeps_its_repository_and_status() { + if !git_available() { + eprintln!("git is not available; skipping"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let work = blobless_clone(&base); + let bare = base.join("bare.git"); + + std::fs::write(work.join("README.md"), "hello\nchanged\n").unwrap(); + std::fs::write(work.join("new.txt"), "new\n").unwrap(); + // A staged deletion of a never-fetched blob plus a near-identical addition: rename + // detection would have to fetch the missing blob (`git rm --sparse` needs git 2.35+). + git(&work, &["rm", "-q", "--sparse", "docs/guide.txt"]); + let renamed: String = (1..=199).map(|i| format!("line {i}\n")).collect(); + std::fs::write(work.join("guide2.txt"), renamed).unwrap(); + git(&work, &["add", "guide2.txt"]); + + // The promisor remote is gone: status must not need it. + std::fs::rename(&bare, base.join("gone.git")).unwrap(); + + let repos = Repos::discover(&work, &|_| false).unwrap(); + let repo = repos.primary().expect("the partial clone is a repository"); + assert_eq!(repo.root(), work); + assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main")); + assert_eq!(repo.log(&LogQuery::default()).unwrap().len(), 1); + + let status = repos.status().expect("status of a partial clone"); + let find = |rel: &str| status.iter().find(|f| f.rel_path == rel); + let readme = find("README.md").expect("README.md listed"); + assert_eq!((readme.staged, readme.unstaged), (None, Some(ChangeKind::Modified))); + let new = find("new.txt").expect("new.txt listed"); + assert_eq!(new.unstaged, Some(ChangeKind::Untracked)); + // Rename detection needs the never-fetched blob, so the retry without it lists an addition. + let moved = find("guide2.txt").expect("guide2.txt listed"); + assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None)); + let removed = find("docs/guide.txt").expect("docs/guide.txt listed"); + assert_eq!(removed.staged, Some(ChangeKind::Deleted)); + // Skip-worktree entries outside the checkout are not missing files. + assert!(find("app/main.rs").is_none(), "{status:?}"); + assert_eq!(status.len(), 4, "{status:?}"); + + // The watcher's scoped refresh (a trusted project's `git status` with a pathspec) retries the + // same way. + repo.set_execution_allowed(true); + let scoped = repo.status_paths(&[work.join("guide2.txt"), work.join("docs/guide.txt")]).expect("scoped status"); + let find = |rel: &str| scoped.iter().find(|f| f.rel_path == rel); + let moved = find("guide2.txt").expect("guide2.txt listed"); + assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None)); + assert_eq!(find("docs/guide.txt").expect("docs/guide.txt listed").staged, Some(ChangeKind::Deleted)); + assert_eq!(scoped.len(), 2, "{scoped:?}"); +} + +#[test] +fn blobless_clone_still_detects_a_rename_between_local_blobs() { + if !git_available() { + eprintln!("git is not available; skipping"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let work = blobless_clone(&base); + // README.md is inside the cone, so both sides of the rename are local blobs. + git(&work, &["mv", "README.md", "README2.md"]); + + let repos = Repos::discover(&work, &|_| false).unwrap(); + let repo = repos.primary().expect("the partial clone is a repository"); + let status = repos.status().expect("status of a partial clone"); + let moved = status.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed"); + assert_eq!( + (moved.staged, moved.renamed_from.as_deref()), + (Some(ChangeKind::Renamed), Some("README.md")), + "{status:?}" + ); + + repo.set_execution_allowed(true); + let scoped = repo.status_paths(&[work.join("README2.md"), work.join("README.md")]).expect("scoped status"); + let moved = scoped.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed"); + assert_eq!( + (moved.staged, moved.renamed_from.as_deref()), + (Some(ChangeKind::Renamed), Some("README.md")), + "{scoped:?}" + ); +} From d5f7e0a99beeff0860dd8fdeb478bb121bc679a6 Mon Sep 17 00:00:00 2001 From: arookieofc Date: Mon, 30 Nov 2026 01:50:57 -0800 Subject: [PATCH 16/66] fix(maven): delegate launch classpath to Maven without jdtls (#6984) With delegateBuild on a Maven module, launches without jdtls (java-analyzer) used the language server classpath, which ignores child POM exclusions. They now merge the classpath Maven resolves, as the jdtls path does, and fall back to the server classpath when the probe fails. Fixes #5586 Co-authored-by: arookieofc <186315048+arookieofc@users.noreply.github.com> --- crates/ide-host/src/ops/java.rs | 148 +++++++++++++++++++++++++------- 1 file changed, 118 insertions(+), 30 deletions(-) diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 6cd7ff0ec..97a266227 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -544,38 +544,24 @@ async fn resolve_launch_without_jdtls( let cancel = cancel.clone(); tokio::task::spawn_blocking(move || { let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings); - match from_server { - // The IDE's Java build gave the whole classpath; the server adds its JDK. - Some(server) if by_service => { - info.project_root = server.classpath.project_root; - info.java_home = server.jdk_home.map(Into::into); - } - None if by_service => {} - Some(server) => { - info.project_root = server.classpath.project_root; - info.module_paths = server.classpath.module_paths; - info.java_home = server.jdk_home.map(Into::into); - append_unique_class_paths(&mut class_paths, server.classpath.class_paths); - } - None => { - if !is_maven_module(root, &model, &module) { - return Err(IdeError::unavailable( - "Cannot resolve the classpath: the Java language server does not report it \ - (java-analyzer/projectClasspath), and the module is not a Maven project", - )); - } + let is_maven = is_maven_module(root, &model, &module); + let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven; + apply_without_jdtls_classpath( + &mut class_paths, + &mut info, + from_server, + by_service, + is_maven, + delegated_maven, + || { let local_repo = ide_sdk::apply::maven_local_repository(root, settings); - let classpath = if aggregator && policy == BuildPolicy::NoBuild { - compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)? + if aggregator && policy == BuildPolicy::NoBuild { + compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel) } else { - compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)? - }; - append_unique_class_paths( - &mut class_paths, - std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()), - ); - } - } + compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel) + } + }, + )?; info.class_paths = class_paths; apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test); finish_launch(&mut info, root, &module, settings, &model, &data_dir); @@ -825,6 +811,59 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool { a == b || entry_key(a, windows) == entry_key(b, windows) } +/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or +/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven +/// module), delegates classpath resolution to Maven itself (falling back to the language server's +/// classpath on error, matching the jdtls path) so child POM `` and Maven dependency +/// mediation are respected (#5586). +fn apply_without_jdtls_classpath( + class_paths: &mut Vec, + info: &mut JavaLaunchInfo, + from_server: Option, + by_service: bool, + is_maven: bool, + delegated_maven: bool, + probe_maven: impl FnOnce() -> IdeResult, +) -> IdeResult<()> { + match from_server { + // The IDE's Java build gave the whole classpath; the server adds its JDK. + Some(server) if by_service => { + info.project_root = server.classpath.project_root; + info.java_home = server.jdk_home.map(Into::into); + Ok(()) + } + None if by_service => Ok(()), + Some(server) if delegated_maven => { + info.project_root = server.classpath.project_root; + info.module_paths = server.classpath.module_paths; + info.java_home = server.jdk_home.map(Into::into); + info.class_paths = server.classpath.class_paths; + merge_maven_launch_classpath(class_paths, info, probe_maven(), &[]) + } + Some(server) => { + info.project_root = server.classpath.project_root; + info.module_paths = server.classpath.module_paths; + info.java_home = server.jdk_home.map(Into::into); + append_unique_class_paths(class_paths, server.classpath.class_paths); + Ok(()) + } + None => { + if !is_maven { + return Err(IdeError::unavailable( + "Cannot resolve the classpath: the Java language server does not report it \ + (java-analyzer/projectClasspath), and the module is not a Maven project", + )); + } + let classpath = probe_maven()?; + append_unique_class_paths( + class_paths, + std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()), + ); + Ok(()) + } + } +} + /// Merge the Maven launch classpath without turning a recoverable probe failure into a /// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath /// and leave the reason in the run console. Maven lists the module's and its reactor @@ -1259,6 +1298,55 @@ mod tests { ); } + #[test] + fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() { + let server = ide_lsp::java_project::ServerClasspath { + classpath: ide_lsp::jdtls::JavaClasspath { + project_root: Some(PathBuf::from("/work/child").into()), + // Static server resolver kept an excluded parent transitive jar (#5586). + class_paths: vec![ + "/work/child/target/classes".into(), + "/m2/log4j-slf4j-impl-2.12.1.jar".into(), + "/m2/logback-classic.jar".into(), + ], + module_paths: vec![], + }, + jdk_home: Some(PathBuf::from("/jdk8")), + }; + let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"]) + .unwrap() + .to_string_lossy() + .into_owned(); + let mut class_paths = vec!["/work/child/target/classes".to_owned()]; + let mut info = JavaLaunchInfo::default(); + apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven)) + .unwrap(); + assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]); + assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into())); + assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into())); + assert!(info.hints.is_empty(), "{:?}", info.hints); + } + + #[test] + fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() { + let server = ide_lsp::java_project::ServerClasspath { + classpath: ide_lsp::jdtls::JavaClasspath { + project_root: Some(PathBuf::from("/work/child").into()), + class_paths: vec!["/m2/server-fallback.jar".into()], + module_paths: vec![], + }, + jdk_home: None, + }; + let mut class_paths = vec!["/work/child/target/classes".to_owned()]; + let mut info = JavaLaunchInfo::default(); + apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || { + Err(IdeError::internal("maven offline")) + }) + .unwrap(); + assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]); + assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints); + } + #[test] fn cancelled_maven_classpath_probe_propagates_without_fallback() { let mut class_paths = vec!["snapshot.jar".to_owned()]; From f28dd8125b38a36d3df6372ee198d1c7ae0b9773 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:51:51 +0800 Subject: [PATCH 17/66] fix(deps): update yanked async-executor 1.14.0 to 1.14.1 (#6971) crates.io yanked async-executor 1.14.0 for a use-after-free when a Waker fires during Executor::drop (smol-rs/async-executor#164). Lock-only update to 1.14.1. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b9cbcc802..8b19cd0c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -252,9 +252,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", From 399ae25ab602c74b963956c9238a2bb2e608518b Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 17:58:47 +0800 Subject: [PATCH 18/66] fix(agents): keep a long agent form scrollable above the composer (#7003) An agent form (ACP elicitation, used by opencode for its questions) had no height limit, so a form with several fields pushed its last choices, its buttons and the composer out of view with nothing to scroll. FormCard now uses the pinned question card layout (at most half the window, scrolling within), and the pinned card shrinks when the session is shorter so the composer stays in view. Fixes #6945 --- e2e/agentQuestions.spec.ts | 47 ++++++++++++++++++++++++++ src/features/agents/FormCard.tsx | 3 +- src/features/agents/Session.module.css | 6 ++-- 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/e2e/agentQuestions.spec.ts b/e2e/agentQuestions.spec.ts index 66f174efb..e82a81414 100644 --- a/e2e/agentQuestions.spec.ts +++ b/e2e/agentQuestions.spec.ts @@ -242,3 +242,50 @@ for (const theme of ["dark", "light"] as const) { } } } + +test("a long agent form scrolls above the composer instead of being cut off", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1000, height: 520 }); + const fields = Array.from({ length: 5 }, (_, q) => ({ + name: `q${q + 1}`, + title: `Question ${q + 1}`, + kind: "choice" as const, + required: true, + options: Array.from({ length: 4 }, (_, o) => ({ value: `a${o + 1}`, label: `Answer ${q + 1}.${o + 1}` })), + })); + await page.evaluate( + async ({ task, fields }) => { + const store = await import("/src/features/agents/store.ts"); + store.useAgents.setState({ + loaded: true, + tasks: new Map([[task.id, task]]), + entries: new Map([ + [ + task.id, + [{ type: "permission", id: 1, title: "Plan the change", options: [], chosen: null, form: { fields } }], + ], + ]), + }); + store.openTaskInEditorLocation(task.id); + }, + { task, fields }, + ); + const card = page.getByRole("form", { name: "Plan the change" }); + await expect(card).toBeVisible(); + const composer = page.getByRole("textbox", { name: "Message", exact: true }); + await expect(composer).toBeInViewport(); + for (let q = 1; q <= 5; q++) { + const last = card.getByRole("radio", { name: `Answer ${q}.4` }); + await last.scrollIntoViewIfNeeded(); + const box = (await last.boundingBox())!; + const hit = await page.evaluate( + ({ x, y }) => document.elementFromPoint(x, y)?.closest("label")?.textContent ?? null, + { x: box.x + box.width / 2, y: box.y + box.height / 2 }, + ); + expect(hit).toContain(`Answer ${q}.4`); + await last.check(); + } + const submit = card.getByRole("button", { name: "Submit", exact: true }); + await submit.scrollIntoViewIfNeeded(); + await expect(submit).toBeInViewport({ ratio: 1 }); + await expect(submit).toBeEnabled(); +}); diff --git a/src/features/agents/FormCard.tsx b/src/features/agents/FormCard.tsx index 98d9e6c09..cca15543b 100644 --- a/src/features/agents/FormCard.tsx +++ b/src/features/agents/FormCard.tsx @@ -1,4 +1,5 @@ import { useId, useState } from "react"; +import clsx from "clsx"; import type { AgentForm, AgentFormField, AgentTask } from "@/bindings"; import { Button, Checkbox, Input, Radio, T } from "@/ui"; import type { PermissionEntry } from "./permission"; @@ -48,7 +49,7 @@ export function FormCard({ task, entry, form }: { task: AgentTask; entry: Permis }; return (
{ event.preventDefault(); diff --git a/src/features/agents/Session.module.css b/src/features/agents/Session.module.css index 10bc2d8e6..7a852ecfa 100644 --- a/src/features/agents/Session.module.css +++ b/src/features/agents/Session.module.css @@ -1632,9 +1632,11 @@ font-size: var(--agent-fs-ui, var(--fs-ui)); container: question-card / inline-size; } -/* A question that outlived its turn waits above the composer, at the composer's width. */ +/* A question that outlived its turn waits above the composer, at the composer's width. It scrolls within at most + half the window, and less when the session is shorter, so the composer and the card's buttons stay in view. */ .questionCardPinned { - flex: none; + flex: 0 1 auto; + min-height: 0; max-height: 50vh; overflow-y: auto; width: 100%; From 1748c98ac819d1c42fb71d0382566b478f5e8daa Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 17:59:41 +0800 Subject: [PATCH 19/66] test(agents): type the store import of the long agent form e2e (#7004) The e2e from #7003 imported the store by a literal /src path, which pnpm typecheck rejects (TS2307); it now imports through a variable typed as the store module. --- e2e/agentQuestions.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/e2e/agentQuestions.spec.ts b/e2e/agentQuestions.spec.ts index e82a81414..d80238065 100644 --- a/e2e/agentQuestions.spec.ts +++ b/e2e/agentQuestions.spec.ts @@ -254,7 +254,8 @@ test("a long agent form scrolls above the composer instead of being cut off", as })); await page.evaluate( async ({ task, fields }) => { - const store = await import("/src/features/agents/store.ts"); + const storePath = "/src/features/agents/store.ts"; + const store: typeof AgentStore = await import(storePath); store.useAgents.setState({ loaded: true, tasks: new Map([[task.id, task]]), From 7fef1e10a8528715fa6f70734569deb5a3c0734e Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 19:03:40 +0900 Subject: [PATCH 20/66] fix(ai-completion): say why no suggestions appear and let the model be chosen (#6936) The plugin's optional net:localhost permission is not ticked by default, and a missing Ollama model answers 404; both only reached the IDE log. Failed requests now show one warning that says why and what to do, and a new AI Completion: Set Model command (Set Endpoint URL also asks for its value from the palette). The host answers an empty list instead of "no server supports inline completion" when a plugin offers ghost text, so the editor keeps asking while typing. Fixes #6930 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/lsp.rs | 35 ++++- crates/ide-host/src/plugins/providers.rs | 5 + crates/ide-host/tests/plugins.rs | 32 +++++ plugins/official/ai-completion/Cargo.lock | 2 +- plugins/official/ai-completion/Cargo.toml | 2 +- .../official/ai-completion/dist/plugin.wasm | Bin 233705 -> 230006 bytes .../ai-completion/dist/plugin.wasm.sources | 2 +- plugins/official/ai-completion/plugin.toml | 9 +- plugins/official/ai-completion/src/lib.rs | 120 +++++++++++++++++- 9 files changed, 193 insertions(+), 14 deletions(-) diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index c8a8d1f2c..9cc29f714 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -336,20 +336,36 @@ pub async fn lsp_inline_completion( let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) { Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => { let cancel = cancel.clone(); - plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten() + plugin_call(move || { + let offered = plugins.offers_inline_completion(&d.language); + (offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s)) + }) + .await } _ => None, }; host.end_request(request); + inline_items(result, plugin) +} + +/// The plugin's suggestion, else the servers'. When a plugin offers ghost text +/// for the document, "no server supports inline completion" is not returned: +/// the editor would stop asking while typing for 30 s, and a plugin that had +/// nothing this time (cancelled by the next keystroke) may have some next time. +fn inline_items( + servers: IdeResult>, + plugin: Option<(bool, Option)>, +) -> IdeResult> { match plugin { - Some((_, s)) => Ok(vec![InlineCompletionItem { + Some((_, Some(s))) => Ok(vec![InlineCompletionItem { insert_text: s.insert_text, range: s.replace, filter_text: None, command: None, server: PLUGIN_SERVER, }]), - None => result, + Some((true, None)) => provider_server(servers), + _ => servers, } } @@ -2429,6 +2445,19 @@ pub fn plugin_formatters() -> IdeResult bool { + !self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty() + } + /// Ghost text from the first plugin that has some. Not bound by the /// edit-path soft deadline (it may need the network) but by `cancel`: /// the editor cancels a request as soon as the user types on. diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 620854a29..e18e600aa 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -3027,6 +3027,38 @@ fn official_ai_completion_cancels_superseded_requests() { assert!(times[9] < Duration::from_millis(500), "{times:?}"); } +/// Installed with the optional network permission refused (it is not ticked by +/// default), a suggestion request says so in the window instead of failing silently. +#[test] +fn official_ai_completion_explains_a_refused_network_permission() { + let f = fixture(Limits::default()); + f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap(); + let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO); + f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap(); + f.take_events(); + let doc = ide_plugin::ProviderDocument { + path: f.project.join("src/a.rs"), + language: "rust".into(), + version: 1, + text: "let x = ".into(), + }; + for _ in 0..2 { + assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none()); + } + assert!(seen.lock().is_empty(), "denied before connecting"); + let notices: Vec = f + .take_events() + .into_iter() + .filter_map(|(_, e)| match e { + PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body), + _ => None, + }) + .collect(); + assert_eq!(notices.len(), 1, "once: {notices:?}"); + assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}"); + assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash"); +} + /// Checkstyle: a save runs the approved `checkstyle` and publishes /// diagnostics; quick fixes come through the code-action provider; saving /// again cancels the check still running. diff --git a/plugins/official/ai-completion/Cargo.lock b/plugins/official/ai-completion/Cargo.lock index f482b25d2..433f1815c 100644 --- a/plugins/official/ai-completion/Cargo.lock +++ b/plugins/official/ai-completion/Cargo.lock @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "openidea-plugin-openidea-ai-completion" -version = "0.1.0" +version = "0.1.1" dependencies = [ "openidea-plugin", "serde_json", diff --git a/plugins/official/ai-completion/Cargo.toml b/plugins/official/ai-completion/Cargo.toml index 255622aa5..d2bfc5f76 100644 --- a/plugins/official/ai-completion/Cargo.toml +++ b/plugins/official/ai-completion/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openidea-plugin-openidea-ai-completion" -version = "0.1.0" +version = "0.1.1" edition = "2024" publish = false diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index 6282a5798105a1d0315764781ad72ceadd2e882d..b3ac50a4b18f3743d11eaf7c026c0b70e6e9fdc4 100644 GIT binary patch delta 58964 zcmd44349bq^EW=-Gn?IHH^~HYkp!6Ca0I!+l^`N!5Cj1Q@5d8RQ3)uAJRXn71_=s? z=Kzh$Epnd{2+9={1>{sw@diaj1qB7g2h{(!x@R^C0Uv+Q`}@D2*JEdgww1 z>dv<_lYS{pT9(TjTU^()T6YZ@G4Qs5xAY$|aL8TF2M@Ssz+j~M1`HoQWVruP#yTfB zMZB)bb4(BVVw96I7|-#z^Y|8sy(i$m#wcMbjL z2a&XBltpD&>?(?rs>daje;Z^aT;bo2{`Cietx#qYWC^gAtncBC%rtg~WG zL;bkBNAw@@&$~5%(2N214IIH(LLH_#Bh55tTEZxn;zWY?vs%uS;6w7aj?*U8FZtwm zA+7)2cQOqyCh~|gD|DU{mzb0pb^p=&X)M~0J&Yes>*tR;{>0KYfy!JX`d~DQOrK1` zOT5Z^_~C~&B;xU~#`h-F6Zwzm5$Eef$9bA(2PE&c_$)E=K0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U4fns?CC0Vm_4Y5K<2lXqv7~$iv!`d&Y=35 zh^*wTytr?rh_v%Uht&#tMtW@Gvz6SZ+J$!&uk<+5uvae_?gbKQTHnels?9u66XlL{ zryf4N1PQzZX=-(ODZo*T&{Vg0dKE87&u~z`Mw>h`#o<+0lJ-y, + /// The last failure shown to the user, so a notice is not repeated. + last_notice: Option, } struct Config { @@ -48,6 +50,34 @@ fn config() -> Config { Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") } } +/// What to tell the user about a failed request: why, and what to do. +pub fn advice(endpoint: &str, model: &str, openai: bool, failure: &Result) -> String { + match failure { + Err(Error::Denied(_)) => format!( + "AI Completion may not connect to {endpoint}. Allow its network access in Settings › Plugins › AI Completion." + ), + Ok(text) if !openai && text.starts_with("HTTP 404") => format!( + "The model {model} is not available at {endpoint}. Run `ollama pull {model}`, or choose an installed model with AI Completion: Set Model." + ), + Err(Error::Failed(e)) if e.contains("timed out") => format!( + "{endpoint} took too long to answer; the model may still be loading, or be too large for this machine." + ), + Err(Error::Failed(e)) if !openai => format!("Could not reach Ollama at {endpoint} ({e}). Is it running?"), + Ok(text) => format!("{endpoint} answered {text}"), + Err(e) => format!("Could not reach {endpoint}: {e}"), + } +} + +/// The command's argument, or what the user types (pre-filled with `current`); +/// `None` when dismissed. +fn arg_or_input(arg: Option<&str>, prompt: &str, current: &str) -> Result, Error> { + let value = match arg { + Some(a) => Some(a.to_owned()), + None => host::input(prompt, Some(current))?, + }; + Ok(value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())) +} + /// The last `max` characters of `s` (on a char boundary). fn tail(s: &str, max: usize) -> &str { match s.char_indices().rev().nth(max.saturating_sub(1)) { @@ -112,14 +142,21 @@ impl Providers for AiCompletion { // Superseded by the next keystroke: nothing to report. Err(Error::Cancelled) => None, other => { - let msg = match other { - Ok(r) => format!("HTTP {}: {}", r.status, head(&r.text(), 200)), + let failure = other.map(|r| format!("HTTP {}: {}", r.status, head(&r.text(), 200))); + let msg = match &failure { + Ok(m) => m.clone(), Err(e) => e.to_string(), }; if self.last_error.as_ref() != Some(&msg) { host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint)); self.last_error = Some(msg); } + // Otherwise a failure only shows in the IDE log, where nobody looks. + let notice = advice(&c.endpoint, &c.model, c.openai, &failure); + if self.last_notice.as_ref() != Some(¬ice) { + host::notify(NotificationLevel::Warning, "AI Completion", ¬ice); + self.last_notice = Some(notice); + } None } } @@ -144,11 +181,23 @@ impl Plugin for AiCompletion { } } "set-endpoint" => { - let url = arg.map(str::trim).filter(|u| u.starts_with("http://") || u.starts_with("https://")); - let url = url.ok_or("give the endpoint URL, e.g. http://localhost:11434")?; - storage::set("endpoint", url)?; + let Some(url) = arg_or_input(arg, "Endpoint URL (e.g. http://localhost:11434)", &config().endpoint)? + else { + return Ok(None); + }; + if !(url.starts_with("http://") || url.starts_with("https://")) { + return Err("give the endpoint URL, e.g. http://localhost:11434".into()); + } + storage::set("endpoint", &url)?; format!("Using {url}.") } + "set-model" => { + let Some(model) = arg_or_input(arg, "Model (as `ollama list` shows it)", &config().model)? else { + return Ok(None); + }; + storage::set("model", &model)?; + format!("Using the model {model}.") + } "toggle" => { let enabled = !config().enabled; storage::set("enabled", if enabled { "true" } else { "false" })?; @@ -156,6 +205,8 @@ impl Plugin for AiCompletion { } _ => return Err(Error::NotFound(format!("command {id}"))), }; + // A new setting may fix (or change) the failure: tell again. + self.last_notice = None; host::notify(NotificationLevel::Info, "AI Completion", &msg); Ok(Some(msg)) } @@ -228,7 +279,7 @@ mod tests { } #[test] - fn quiet_when_cancelled_denied_or_mid_word() { + fn quiet_when_cancelled_or_mid_word() { let host = MockHost::install().with_capabilities(&["storage"]); let mut p = AiCompletion::default(); assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied"); @@ -243,4 +294,61 @@ mod tests { assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none()); assert_eq!(host2.requests().len(), 1, "disabled: no request"); } + + #[test] + fn tells_the_user_why_once_and_what_to_do() { + // Installed without the optional network permission (the default for it). + let host = MockHost::install().with_capabilities(&["storage"]); + let mut p = AiCompletion::default(); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none()); + assert!(p.inline_completion(&doc("let x = 1"), Position::new(0, 9)).is_none()); + let notes = host.notifications(); + assert_eq!(notes.len(), 1, "once, not per keystroke: {notes:?}"); + assert!(notes[0].body.contains("Settings › Plugins › AI Completion"), "{}", notes[0].body); + + // A model that is not pulled: Ollama answers 404. + let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]); + host.on_fetch(|_| { + Ok(HttpResponse { + status: 404, + headers: vec![], + body: br#"{"error":{"message":"model \"qwen2.5-coder:1.5b\" not found, try pulling it first"}}"# + .to_vec(), + }) + }); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none()); + let body = &host.notifications()[0].body; + assert!(body.contains("ollama pull qwen2.5-coder:1.5b") && body.contains("Set Model"), "{body}"); + + // Ollama not running. + host.on_fetch(|_| Err(Error::Failed("connection refused".into()))); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none()); + assert!(host.notifications()[1].body.contains("Is it running?")); + host.on_fetch(|_| Err(Error::Failed("error sending request: operation timed out".into()))); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none()); + assert!(host.notifications()[2].body.contains("took too long")); + } + + #[test] + fn set_model_takes_an_argument_or_asks() { + let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]); + host.on_fetch(|_| { + Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() }) + }); + let mut p = AiCompletion::default(); + p.run_command("set-model", &host.invocation(), Some(" qwen2.5-coder:7b ")).unwrap(); + assert_eq!(config().model, "qwen2.5-coder:7b"); + // From the command palette: no argument, so it asks. + host.answer_next_prompt(Some(&["codellama:7b-code"])); + p.run_command("set-model", &host.invocation(), None).unwrap(); + p.inline_completion(&doc("let x = "), Position::new(0, 8)).unwrap(); + let body: Value = serde_json::from_slice(host.requests()[0].body.as_ref().unwrap()).unwrap(); + assert_eq!(body["model"], "codellama:7b-code"); + // Dismissed: nothing changes. + assert_eq!(p.run_command("set-model", &host.invocation(), None).unwrap(), None); + assert_eq!(config().model, "codellama:7b-code"); + host.answer_next_prompt(Some(&["http://127.0.0.1:11434"])); + p.run_command("set-endpoint", &host.invocation(), None).unwrap(); + assert_eq!(config().endpoint, "http://127.0.0.1:11434"); + } } From a09c9aa9ad22e3652d063ddd9dd0aa7d916ebd3e Mon Sep 17 00:00:00 2001 From: Waiting-Night <53596273+wangyuewen-china@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:06:54 +0800 Subject: [PATCH 21/66] fix(java): navigate inherited method references to their declarations (#6953) JDT's selection-based definition can answer the functional interface method (Function.apply) for a method reference whose method is inherited. Go to Definition on a Java method reference now asks the app-owned JDT command openidea.java.methodReferenceDefinition (java-usages 1.20.1) for the AST method binding; Lombok accessors without a source range fall back to their field or declaring type. The bundled jar is reproducible from source (SHA-256 a111a935...); tests/method-reference.py checks the command against a real JDT LS. Co-authored-by: wangyuewen-china <53596273+wangyuewen-china@users.noreply.github.com> --- crates/ide-lsp/src/jdtls.rs | 17 +- crates/ide-lsp/src/lib.rs | 75 +++++++- crates/ide-sdk/src/java.rs | 2 +- java/java-usages/MANIFEST.MF | 2 +- java/java-usages/README.md | 11 +- java/java-usages/openidea-java-usages.jar | Bin 193709 -> 200675 bytes java/java-usages/plugin.xml | 3 + .../MethodReferenceDefinitionCommand.java | 131 ++++++++++++++ java/java-usages/tests/method-reference.py | 167 ++++++++++++++++++ 9 files changed, 403 insertions(+), 5 deletions(-) create mode 100644 java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java create mode 100644 java/java-usages/tests/method-reference.py diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index ef6160a28..b4f67ca42 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -9,7 +9,8 @@ use crate::LspManager; use crate::server::{Running, Server}; use ide_core::error::{ErrorData, ErrorKind}; use ide_core::event::LspRefreshKind; -use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; +use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos}; +use lsp_types as lsp; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use specta::Type; @@ -20,6 +21,7 @@ use std::time::{Duration, Instant}; pub(crate) const SERVER: &str = "jdtls"; const GENERATED_SOURCES: &str = "openidea.java.generatedSources"; +const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition"; pub(crate) mod configuration; pub(crate) mod exception_breakpoints; @@ -771,6 +773,19 @@ impl LspManager { } } + /// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`. + /// JDT's selection-based definition can return the functional interface method when the + /// referenced method is inherited; the extension resolves the AST binding instead. + pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult> { + let uri = crate::path_to_uri_string(path); + let value = self + .jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)]) + .await?; + let locations: Vec = serde_json::from_value(value).unwrap_or_default(); + let conv = self.conv(crate::text::Encoding::Utf16); + Ok(locations.iter().filter_map(|location| conv.location(location)).collect()) + } + /// The jdtls instance serving `path` (a module directory or source file), /// started if needed and waited for. async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc, Running)> { diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 46faba21d..febff3f13 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -327,6 +327,25 @@ fn goto_is_empty(r: &Option) -> bool { } } +/// Whether the caret is on the method name of a Java method reference (`Type::method`). +/// A method reference can name a functional interface's method through JDT's selection-based +/// definition when the referenced method is inherited, so ask the AST binding command instead. +fn java_method_reference_at(text: &DocText, pos: Pos) -> bool { + let line = text.line(pos.line as usize); + let mut utf16 = 0u32; + let mut at = line.len(); + for (i, c) in line.char_indices() { + if utf16 >= pos.col { + at = i; + break; + } + utf16 += c.len_utf16() as u32; + } + let before = line[..at].trim_end(); + let Some(colon) = before.rfind("::") else { return false }; + before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$') +} + fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError { match e { RpcError::Cancelled => IdeError::cancelled(), @@ -1793,7 +1812,31 @@ impl LspManager { } let (method, cap, feature) = goto_method(kind); let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?; - self.goto_in(&snap, &targets, method, pos, None, None).await + let result = self.goto_in(&snap, &targets, method, pos, None, None).await; + // JDT's selection-based definition can name the functional interface method for an + // inherited method reference. Ask the Java binding command when that is what came back, + // when the caret is on a method reference, or when the server found no target at all. + let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos); + if kind == GotoKind::Definition + && snap.language.as_str() == "java" + && (method_reference + || result.as_ref().is_ok_and(|locs| { + locs.is_empty() + || locs.iter().any(|l| { + let path = l.path.to_string_lossy().replace('\\', "/"); + let uri = l.uri.as_deref().unwrap_or_default(); + path.contains("java/util/function") + || path.contains("java.util.function") + || uri.contains("java/util/function") + || uri.contains("java.util.function") + }) + })) + && let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await + && !found.is_empty() + { + return Ok(found); + } + result } /// Go to Implementation, with the implementations found first passed to `partial` while @@ -4677,6 +4720,36 @@ mod code_action_tests { } } +#[cfg(test)] +mod java_method_reference_tests { + use super::java_method_reference_at; + use crate::text::DocText; + use ide_core::Pos; + + #[test] + fn finds_the_method_name_of_a_method_reference() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);"); + let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32; + assert!(java_method_reference_at(&text, Pos::new(0, col))); + } + + #[test] + fn allows_whitespace_around_the_method_reference_operator() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);"); + let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32; + assert!(java_method_reference_at(&text, Pos::new(0, col))); + } + + #[test] + fn ignores_regular_calls_and_the_referenced_type() { + let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);"); + let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32; + assert!(!java_method_reference_at(&text, Pos::new(0, type_col))); + let call = DocText::new("wrapper.set(getUpdateTime(), now);"); + assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32))); + } +} + #[cfg(test)] mod did_change_content_tests { use super::*; diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 4bbf32e26..ca3a00a6f 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.19.0", + "1.20.1", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index b0de4c680..e3ffb7c09 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA Java usages Bundle-SymbolicName: ai.openidea.usages;singleton:=true -Bundle-Version: 1.19.0 +Bundle-Version: 1.20.1 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core, org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime, diff --git a/java/java-usages/README.md b/java/java-usages/README.md index ac1f868a5..acc7e6c35 100644 --- a/java/java-usages/README.md +++ b/java/java-usages/README.md @@ -6,6 +6,10 @@ The app-owned OSGi command `openidea.java.usages` returns `{location, kind, acce `kind` retains field/getter/setter/unknown identity for compatibility. Optional `access` is read/write/readWrite/unknown. Missing access metadata is unknown; old servers and ordinary LSP locations remain visible under either filter. +`openidea.java.methodReferenceDefinition(uri, line, column)` resolves the method name +of a `Type::method` or `expr::method` reference through its AST binding and returns the +declaring method's location. This keeps inherited methods on their parent declaration +where JDT's selection-based definition may return the functional interface method. An absent or failing extension command uses standard LSP references, without access classification or toolbar controls. This includes errors during scope widening. The Rust bridge logs the failure once per project session. Cancelled requests and @@ -88,7 +92,7 @@ is not a claim of full IntelliJ feature parity. ## Rebuild and delivery The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as -`java-usages-1.18.0.jar`, and added alongside existing initialization bundles. +`java-usages-1.20.1.jar`, and added alongside existing initialization bundles. Users need no compiler, Maven or Python. Manifest/install version must change when replacing the bundle because OSGi caches bundles. @@ -142,6 +146,10 @@ protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception breakpoint intention; its reproducible SHA-256 is `d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`. +Version 1.20.1 adds `openidea.java.methodReferenceDefinition`, which resolves inherited Java method +references from their AST binding instead of JDT's selection result. Lombok-generated accessors +without a source range fall back to their field or declaring type; its reproducible SHA-256 is +`a111a9359b8f13dcd06e14e72fa287943cfe953325bff6f940912cae199caec7`. ```sh export PATH=/path/to/jdk25/bin:$PATH @@ -173,6 +181,7 @@ OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /pat python3 java/java-usages/tests/hierarchy.py /path/to/jdtls python3 java/java-usages/tests/implementations.py /path/to/jdtls python3 java/java-usages/tests/exception-type.py /path/to/jdtls +python3 java/java-usages/tests/method-reference.py /path/to/jdtls ``` The harnesses select the JDT LS configuration for the current platform. The first diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index c17b6e429788fef80bd56041d22067e88f7a6e20..bdafdf6678845e7c514d9f668e6da1ec79b5d5be 100644 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@Ot9al7a} zrd}DY`6?PAbJ!Ue=CE&H^NY!oZTmV#=3+(`kk0L@%*?mgKpLc`O9FLG&%V#7GJOXZ zvjL06DMp6r@%I_Er@!Q67Mrfi%`C<8?>$f~P@743dK@>iGm|Bd!^12J;;>KO&&_PZ z^jZKUqBvcShuM(nv=oRF&h%axL@P``#lvjCr0xRZNKOBc#Kby1E`y0}x*{)7nB5ym zc*1rj_UV-%;rl*F!lytY%kv>34fB{dr_1vJt=U)u7vY~?%?DH?Q;#H4u#t&n`Yn)f zL>okS!2%}f>DSqSzO7ioB)|g=N`?l;h%TstB}{zN-*Ykx$RL7_fq@IA5J)#LHa(br Vke^wEPl-W^ArNSW+Y2V3H~=ozaX0_~ diff --git a/java/java-usages/plugin.xml b/java/java-usages/plugin.xml index 98cab62c7..79aa04153 100644 --- a/java/java-usages/plugin.xml +++ b/java/java-usages/plugin.xml @@ -27,6 +27,9 @@ + + + diff --git a/java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java b/java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java new file mode 100644 index 000000000..d8d2d0f1d --- /dev/null +++ b/java/java-usages/src/ai/openidea/navigation/MethodReferenceDefinitionCommand.java @@ -0,0 +1,131 @@ +package ai.openidea.navigation; + +import ai.openidea.Documents; +import java.util.List; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.ITypeRoot; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ExpressionMethodReference; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.MethodReference; +import org.eclipse.jdt.core.dom.NodeFinder; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.SuperMethodReference; +import org.eclipse.jdt.core.dom.TypeMethodReference; +import org.eclipse.jdt.core.manipulation.CoreASTProvider; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; +import org.eclipse.jdt.ls.core.internal.JDTUtils; +import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers; +import org.eclipse.lsp4j.Location; + +/** + * Resolves a method reference (for example {@code Child::getGoodsSpace}) to the declaration + * of the referenced method. JDT's selection-based definition request can return the + * functional interface method ({@code Function.apply}) when the method is inherited; + * bindings retain the actual method identity instead. + */ +public final class MethodReferenceDefinitionCommand implements IDelegateCommandHandler { + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + Documents.awaitChanges(monitor); + String uri = (String) arguments.get(0); + int line = ((Number) arguments.get(1)).intValue(); + int column = ((Number) arguments.get(2)).intValue(); + ITypeRoot root = JDTUtils.resolveTypeRoot(uri); + if (root == null || !root.exists()) return List.of(); + CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor); + if (ast == null) return List.of(); + int offset = JsonRpcHelpers.toOffset(root, line, column); + if (offset < 0) return List.of(); + + MethodReference reference = enclosingReference(ast, offset); + if (reference == null) return List.of(); + SimpleName name = methodName(reference); + if (name == null) return List.of(); + int start = name.getStartPosition(); + if (offset < start || offset > start + name.getLength()) return List.of(); + + IMethodBinding binding = reference.resolveMethodBinding(); + if (binding == null) return List.of(); + IMethodBinding declaration = binding.getMethodDeclaration(); + if (declaration == null) return List.of(); + Location location = locationOf(declaration); + return location == null ? List.of() : List.of(location); + } + + /** + * The declaration's source location. Lombok-generated accessors have a binding and a Java + * element but no source range; then the field the accessor reads (or the declaring type) + * is the closest source declaration. Without this fallback the standard definition request + * stays at the functional interface method. + */ + private static Location locationOf(IMethodBinding declaration) throws Exception { + var element = declaration.getJavaElement(); + Location location = element == null ? null : JDTUtils.toLocation(element); + if (location != null) return location; + if (element instanceof IMember member && member.getClassFile() != null) + return JDTUtils.toLocation(member.getClassFile()); + + ITypeBinding owner = declaration.getDeclaringClass(); + if (owner == null) return null; + var ownerElement = owner.getJavaElement(); + if (!(ownerElement instanceof IType type) || !type.exists()) return null; + + for (IMethod method : type.getMethods()) { + if (!method.getElementName().equals(declaration.getName())) continue; + if (method.getNumberOfParameters() != declaration.getParameterTypes().length) continue; + location = JDTUtils.toLocation(method); + if (location != null) return location; + } + + String fieldName = propertyName(declaration.getName()); + if (fieldName != null) { + IField field = type.getField(fieldName); + if (field.exists()) { + location = JDTUtils.toLocation(field); + if (location != null) return location; + } + } + return JDTUtils.toLocation(type); + } + + /** The field name of a bean accessor (`getUpdateTime` / `setUpdateTime` / `isEnabled`). */ + private static String propertyName(String methodName) { + String rest; + if (methodName.startsWith("get") || methodName.startsWith("set")) { + rest = methodName.substring(3); + } else if (methodName.startsWith("is")) { + rest = methodName.substring(2); + } else { + return null; + } + if (rest.isEmpty()) return null; + if (rest.length() > 1 && Character.isUpperCase(rest.charAt(0)) && Character.isUpperCase(rest.charAt(1))) { + return rest; + } + return Character.toLowerCase(rest.charAt(0)) + rest.substring(1); + } + + private static MethodReference enclosingReference(CompilationUnit ast, int offset) { + ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode(); + for (ASTNode node = leaf; node != null; node = node.getParent()) { + if (node instanceof MethodReference reference) return reference; + } + return null; + } + + private static SimpleName methodName(MethodReference reference) { + return switch (reference) { + case TypeMethodReference type -> type.getName(); + case ExpressionMethodReference expression -> expression.getName(); + case SuperMethodReference superReference -> superReference.getName(); + default -> null; + }; + } +} diff --git a/java/java-usages/tests/method-reference.py b/java/java-usages/tests/method-reference.py new file mode 100644 index 000000000..a518a7964 --- /dev/null +++ b/java/java-usages/tests/method-reference.py @@ -0,0 +1,167 @@ +"""Go to Definition on a method reference, against a real JDT LS. Arguments: jdtls home, optional bundle jar. + +Each case puts the caret on a method reference's name and checks that +`openidea.java.methodReferenceDefinition` answers the referenced method's declaration (an inherited +method on its parent, not the functional interface method), and nothing elsewhere. +""" +import json +import pathlib +import platform +import queue +import subprocess +import sys +import tempfile +import threading +import time + +home = pathlib.Path(sys.argv[1]).resolve() +bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar' +work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-method-reference-')) +config = work / 'config' +config.mkdir() +system, machine = platform.system(), platform.machine().lower() +config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux') +config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name] +config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file()) +(config / 'config.ini').write_bytes(config_source.read_bytes()) +project = work / 'project' +(project / 'src/app').mkdir(parents=True) +(project / '.project').write_text('apporg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature') +(project / '.classpath').write_text('') +sources = { + 'Parent.java': '''package app; + +public class Parent { + public String getGoodsSpace() { + return "space"; + } + + public static String describe(Object o) { + return String.valueOf(o); + } +} +''', + 'Child.java': '''package app; + +public class Child extends Parent { + public int own() { + return 1; + } +} +''', + 'Main.java': '''package app; + +import java.util.List; +import java.util.function.Function; + +public class Main { + void run(List children) { + Function inherited = Child::getGoodsSpace; + Function own = Child::own; + Function statics = Child::describe; + children.forEach(System.out::println); + String plain = new Child().getGoodsSpace(); + } +} +''', +} +for name, text in sources.items(): + (project / 'src/app' / name).write_text(text) +uri = lambda name: (project / 'src/app' / name).as_uri() + +log = (work / 'stderr.log').open('w') +proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log) +messages = queue.Queue() +lock = threading.Lock() + + +def send(message): + data = json.dumps(message).encode() + with lock: + proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data) + proc.stdin.flush() + + +def read(): + while True: + headers = {} + while True: + line = proc.stdout.readline() + if not line: + return + if line == b'\r\n': + break + k, v = line.decode().split(':', 1) + headers[k.lower()] = v.strip() + message = json.loads(proc.stdout.read(int(headers['content-length']))) + if 'method' in message and 'id' in message: + send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None}) + else: + messages.put(message) + + +threading.Thread(target=read, daemon=True).start() +seq = 0 + + +def request(method, params): + global seq + seq += 1 + send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params}) + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + msg = messages.get(timeout=max(1, deadline - time.monotonic())) + if msg.get('id') == seq: + if 'error' in msg: + raise RuntimeError(msg['error']) + return msg.get('result') + raise TimeoutError(method) + + + + +def where(loc): + return (loc['uri'].rsplit('/', 1)[-1], loc['range']['start']['line']) + + +def line_of(file, needle): + return next(i for i, t in enumerate(sources[file].splitlines()) if needle in t) + + +CASES = [ + ('Child::getGoodsSpace', 'getGoodsSpace', 3, [('Parent.java', line_of('Parent.java', 'getGoodsSpace'))]), + ('Child::own', 'own', 1, [('Child.java', line_of('Child.java', 'own()'))]), + ('Child::describe', 'describe', 2, [('Parent.java', line_of('Parent.java', 'describe'))]), + ('Child::getGoodsSpace', 'Child', 2, []), + ('new Child().getGoodsSpace', 'getGoodsSpace', 2, []), +] + +try: + init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}}) + commands = init['capabilities']['executeCommandProvider']['commands'] + assert 'openidea.java.methodReferenceDefinition' in commands, commands + send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}}) + for name, text in sources.items(): + send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}}) + request('java/buildWorkspace', True) + failed = [] + lines = sources['Main.java'].splitlines() + for line_needle, needle, at, expected in CASES: + line = next(i for i, t in enumerate(lines) if line_needle in t) + column = lines[line].index(needle, lines[line].index(line_needle)) + at + got = request('workspace/executeCommand', {'command': 'openidea.java.methodReferenceDefinition', 'arguments': [uri('Main.java'), line, column]}) + got = [where(l) for l in got or []] + ok = got == expected + if not ok: + failed.append((line_needle, needle)) + print('OK' if ok else 'FAIL', repr(line_needle), 'at', repr(needle), got) + # The functional interface's method is what the standard request answers for the inherited case. + line = next(i for i, t in enumerate(lines) if 'Child::getGoodsSpace' in t) + std = request('textDocument/definition', {'textDocument': {'uri': uri('Main.java')}, 'position': {'line': line, 'character': lines[line].index('getGoodsSpace') + 3}}) + print('standard definition:', std) + assert not failed, failed + print('method-reference: all cases passed') +finally: + proc.terminate() + proc.wait(timeout=20) + print('Evidence:', work, file=sys.stderr) From ac88059d0f20e265b37a56d7c19d9ce9548ee31a Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 19:11:27 +0900 Subject: [PATCH 22/66] fix(plugins): index the first 20,000 files of a large project instead of none (#6958) Plugin navigation discovery refused the whole project above 20,000 matching files, counted out-of-scope and git-ignored files toward the cap, and showed the raw error text half translated. Discovery now keeps the first 20,000 in-scope, non-ignored files, reports total/truncated, and shows one warning naming the project and the counts. Fixes #6940 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/plugins/index_ops.rs | 50 +++++++++++++++++++++--- crates/ide-index/src/lib.rs | 4 +- crates/ide-index/src/tests.rs | 6 ++- src/bindings.ts | 6 +++ src/features/plugins/navigation.test.ts | 29 +++++++++++++- src/features/plugins/navigation.ts | 15 +++++++ src/platform/locales/text/en.json | 3 +- src/platform/locales/text/zh.json | 3 +- 8 files changed, 105 insertions(+), 11 deletions(-) diff --git a/crates/ide-host/src/plugins/index_ops.rs b/crates/ide-host/src/plugins/index_ops.rs index 63292745a..7d476b14b 100644 --- a/crates/ide-host/src/plugins/index_ops.rs +++ b/crates/ide-host/src/plugins/index_ops.rs @@ -9,6 +9,22 @@ pub struct NavigationFiles { pub paths: Vec, pub indexing: bool, pub extensions: Vec, + /// In-scope files matching `extensions`; `paths` holds the first + /// `MAX_NAVIGATION_FILES` of them. + pub total: u32, + pub truncated: bool, +} + +/// Discovery offers at most this many files; larger projects get navigation +/// on the first ones instead of none. +const MAX_NAVIGATION_FILES: usize = 20_000; + +/// The first `limit` files `in_scope` accepts, and how many it accepts in all. +fn first_in_scope(files: Vec, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec, usize) { + let mut files: Vec<_> = files.into_iter().filter(in_scope).collect(); + let total = files.len(); + files.truncate(limit); + (files, total) } #[command(trust = trusted)] @@ -24,19 +40,25 @@ pub async fn plugin_navigation_files( blocking(move || { let extensions = plugins.navigation_extensions(&project.root); if extensions.is_empty() { - return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] }); + return Ok(NavigationFiles { + paths: vec![], + indexing: false, + extensions: vec![], + total: 0, + truncated: false, + }); } let indexing = project.index.status().indexing; - let files = project.index.files_with_extensions(&extensions, 20_001); - if files.len() > 20_000 { - return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files")); - } + let files = project.index.files_with_extensions(&extensions, usize::MAX); // A project window group's members are project scope: their files are // in the group's index (the group root holds none of them). let members = crate::project::workspace_member_roots(&project.root); let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m)); + let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES); Ok(NavigationFiles { - paths: files.into_iter().filter(in_scope).map(Into::into).collect(), + truncated: total > files.len(), + total: u32::try_from(total).unwrap_or(u32::MAX), + paths: files.into_iter().map(Into::into).collect(), indexing, extensions, }) @@ -210,3 +232,19 @@ ide_command::domain!( plugin_navigation_invalidate, plugin_navigation_markers, ); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() { + let files: Vec = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect(); + let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3); + // Out-of-scope files neither take a slot nor count toward the total. + assert_eq!(total, 4); + assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from)); + let (kept, total) = first_in_scope(kept, |_| true, 20_000); + assert_eq!((kept.len(), total), (3, 3)); + } +} diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index f2860d4e0..83367ab1c 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -258,7 +258,8 @@ impl ProjectIndex { } /// Bounded file inventory for background plugin indexers; honors the same - /// project/exclude scope as search and never walks the filesystem. + /// project/exclude scope as search, leaves VCS-ignored files out and never + /// walks the filesystem. pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec { self.shared .data @@ -266,6 +267,7 @@ impl ProjectIndex { .files .iter() .flatten() + .filter(|f| !f.ignored) .filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e))) .take(limit) .map(|f| f.path.clone()) diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index cd067cd26..198ae4962 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() { } #[test] -fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() { +fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() { let java = "package demo; interface UserMapper { void find(); }"; let f = Fixture::new(&[ ("src/UserMapper.java", java), ("src/mapper.xml", ""), ("target/Generated.java", "class Generated {}"), ("other.txt", "ignored"), + (".gitignore", "gen/\n"), + ("gen/Ignored.java", "class Ignored {}"), ]); let index = f.open(); + // Go to File lists the git-ignored file; plugin navigation leaves it out. + assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]); let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100); assert_eq!(paths.len(), 2); assert!(paths.iter().all(|p| p.starts_with(f.root.join("src")))); diff --git a/src/bindings.ts b/src/bindings.ts index c249989fe..005cef527 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11748,6 +11748,12 @@ export type NavigationFiles = { paths: IpcPath[], indexing: boolean, extensions: string[], + /** + * In-scope files matching `extensions`; `paths` holds the first + * `MAX_NAVIGATION_FILES` of them. + */ + total: number, + truncated: boolean, }; export type NavigationResult = { diff --git a/src/features/plugins/navigation.test.ts b/src/features/plugins/navigation.test.ts index 85e76e76b..f7965754d 100644 --- a/src/features/plugins/navigation.test.ts +++ b/src/features/plugins/navigation.test.ts @@ -5,7 +5,8 @@ import { useProject } from "@/platform/project"; import { usePlugins } from "./store"; import { useEditorRegistry } from "@/editor/api"; import { lspDoc } from "@/editor/lsp/lsp"; -import { synchronizeDocumentIndexes } from "@/workbench/contributions"; +import { notifications, provideNotificationService, synchronizeDocumentIndexes } from "@/workbench/contributions"; +import { setLocale, txTemplate, useI18n } from "@/platform/i18n"; const mocks = vi.hoisted(() => ({ files: vi.fn(), @@ -215,3 +216,29 @@ it("keeps unrelated language-server queries available when plugin discovery fail await expect(synchronizeDocumentIndexes("/project/notes.txt", "refactor")).resolves.toBe(true); expect(mocks.index).not.toHaveBeenCalled(); }); + +it("indexes the first files of a large project and says how many it covers, in one sentence", async () => { + mocks.files.mockResolvedValue({ + status: "ok", + data: { paths: ["/project/A.java"], indexing: false, extensions: ["java"], total: 28684, truncated: true }, + }); + useProject.setState({ project: { root: "/project", name: "big-demo", trusted: true } as never }); + const notify = vi.fn(); + const previous = notifications(); + const locale = useI18n.getState().locale; + provideNotificationService({ notify } as never); + try { + await setLocale("zh"); + off = startPluginNavigation(); + await vi.advanceTimersByTimeAsync(250); + expect(mocks.index.mock.calls[0]?.[0]).toEqual(["/project/A.java"]); + expect(notify).toHaveBeenCalledTimes(1); + const body = notify.mock.calls[0]![0].body; + expect(body).toBe("插件导航仅覆盖 big-demo 中 28,684 个文件里的 1 个;可排除文件夹以缩小范围"); + // The balloon and the OS toast look the text up again: it stays whole. + expect(txTemplate(body)).toBe(body); + } finally { + provideNotificationService(previous); + await setLocale(locale); + } +}); diff --git a/src/features/plugins/navigation.ts b/src/features/plugins/navigation.ts index 32c4e6ad7..27ed37f6b 100644 --- a/src/features/plugins/navigation.ts +++ b/src/features/plugins/navigation.ts @@ -47,6 +47,19 @@ export function startPluginNavigation(): () => void { body: String(error), }); } + let reportedTruncated = false; + function reportTruncated(count: number, total: number) { + if (reportedTruncated) return; + reportedTruncated = true; + const project = useProject.getState().project; + const name = project?.displayName || project?.name || ""; + notifications().notify({ + group: "plugins", + level: "warning", + title: "Plugin navigation indexing incomplete", + body: tx`Plugin navigation covers ${count.toLocaleString()} of ${total.toLocaleString()} files in ${name}; exclude folders to narrow it`, + }); + } let fileExtensions = new Set(); const extensions = () => fileExtensions; const eligible = (path: string) => extensions().has(path.split(".").pop() ?? ""); @@ -142,6 +155,7 @@ export function startPluginNavigation(): () => void { inventory.paths.forEach((p) => known.add(p)); queue(fresh); queue([...views.values()], true); + if (inventory.truncated) reportTruncated(inventory.paths.length, inventory.total); } catch (error) { discovered = false; discoveryFailed = true; @@ -165,6 +179,7 @@ export function startPluginNavigation(): () => void { discoveryFailed = false; discovery = null; reportedError = false; + reportedTruncated = false; notify(); if (ready()) void call(commands.pluginNavigationInvalidate(null)) diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 51dd5a142..e36b79bf5 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4810,5 +4810,6 @@ "{count} files aren't in the Xcode project": "{count} files aren't in the Xcode project", "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.", "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.", - "Open in Xcode": "Open in Xcode" + "Open in Xcode": "Open in Xcode", + "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c023750f0..63ca504eb 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11463,5 +11463,6 @@ "{count} files aren't in the Xcode project": "{count} 个文件不在 Xcode 项目中", "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。", "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。", - "Open in Xcode": "在 Xcode 中打开" + "Open in Xcode": "在 Xcode 中打开", + "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围" } From 88b463d888203d9c289992254ff2e5a018322569 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 19:11:42 +0900 Subject: [PATCH 23/66] fix(debugger): let a tsx program behind a remote root run under Attach to Node.js (#6926) On a loopback address js-debug makes the program require its child-process bootloader by a local path; behind a remote root (published container port, SSH tunnel) that path is missing, tsx's esbuild worker exits and the program waits for it forever. Attach to Node.js with a remote root, and Node.js debugging on SSH/Docker/Compose run targets, now pass autoAttachChildProcesses: false. Closes #6925 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- src/features/debugger/__tests__/remote.test.ts | 4 ++++ src/features/debugger/remote.ts | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/features/debugger/__tests__/remote.test.ts b/src/features/debugger/__tests__/remote.test.ts index 5a456d156..b8350da17 100644 --- a/src/features/debugger/__tests__/remote.test.ts +++ b/src/features/debugger/__tests__/remote.test.ts @@ -245,7 +245,11 @@ describe("remote attach requests", () => { port: 9229, localRoot: "/p", remoteRoot: "/usr/src/app", + autoAttachChildProcesses: false, }); + // Without a remote root the program may be local, and its child processes are followed. + const local = JSON.parse(remoteAttachConfig(configOf(nodeRemoteType), "/p")!.extraJson!); + expect(local).not.toHaveProperty("autoAttachChildProcesses"); }); it("Attach to Node.js reconnects automatically only when the option is on", () => { diff --git a/src/features/debugger/remote.ts b/src/features/debugger/remote.ts index 2afa0b808..a2586aa96 100644 --- a/src/features/debugger/remote.ts +++ b/src/features/debugger/remote.ts @@ -502,7 +502,11 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig | type: "pwa-node", address: host, port: portOf(p, 9229), - ...(map ? { localRoot: map.local, remoteRoot: map.remote } : {}), + // On a loopback address (a published container port, an SSH tunnel) js-debug makes the + // program require its child-process bootloader by a path on this machine. Behind a + // remote root that path is missing: tsx's esbuild worker dies of it and the program + // waits for that worker forever. + ...(map ? { localRoot: map.local, remoteRoot: map.remote, autoAttachChildProcesses: false } : {}), skipFiles: skip ? ["/**", "**/node_modules/**"] : [], ...(p.restart === "true" ? { restart: true } : {}), }); From 8ab776ada6288d1653b208c5091bb24f01508b32 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:14:01 +0800 Subject: [PATCH 24/66] fix(keymap): import an Emacs-based IDEA keymap on top of $default, not macOS (#7008) presetOf picked the macOS preset for any parent whose name contains "mac", including "Emacs", so a keymap derived from IDEA's Emacs keymap was imported as based on macOS. The match is now on the word (Mac OS X, macOS), and Emacs and its copies map to the $default preset they inherit in IDEA. Refs #6896 --- src/platform/ideaKeymap.test.ts | 16 ++++++++++++++++ src/platform/ideaKeymap.ts | 6 ++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/platform/ideaKeymap.test.ts b/src/platform/ideaKeymap.test.ts index 49deaa67b..f15323032 100644 --- a/src/platform/ideaKeymap.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -49,6 +49,22 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.overrides).toEqual({}); }); + it("bases a keymap derived from Emacs on $default, not macOS", () => { + for (const parent of ["Emacs", "Emacs copy"]) { + const k = parseIdeaKeymap(``); + expect(k.parent).toBe("intellij-windows"); + } + for (const [parent, preset] of [ + ["Mac OS X", "intellij-macos"], + ["macOS System Shortcuts", "intellij-macos"], + ["Eclipse (Mac OS X)", "eclipse-macos"], + ["VSCode (macOS)", "vscode-macos"], + ["Default for KDE", "intellij-windows"], + ]) { + expect(parseIdeaKeymap(``).parent).toBe(preset); + } + }); + it("maps Duplicate Entire Lines, which has no shortcut in the presets", () => { const k = parseIdeaKeymap( ``, diff --git a/src/platform/ideaKeymap.ts b/src/platform/ideaKeymap.ts index 786036c14..3a07f22df 100644 --- a/src/platform/ideaKeymap.ts +++ b/src/platform/ideaKeymap.ts @@ -31,11 +31,13 @@ export interface ImportedIdeaKeymap { /** IDEA's bundled keymap names (``) → our presets. */ function presetOf(parent: string | null): string { const p = parent ?? ""; - const mac = /mac/i.test(p); + // "Mac OS X 10.5+", "Eclipse (Mac OS X)", "VSCode (macOS)"; not the "mac" inside "Emacs". + const mac = /\bmac(?: ?os)?\b/i.test(p); if (/^eclipse/i.test(p)) return mac ? "eclipse-macos" : "eclipse-windows"; if (/^vs ?code/i.test(p)) return mac ? "vscode-macos" : "vscode-windows"; if (mac) return "intellij-macos"; - if (p === "$default" || /^default for/i.test(p)) return "intellij-windows"; + // IDEA's Emacs keymap (and copies of it) inherits $default. + if (p === "$default" || /^default for/i.test(p) || /^emacs\b/i.test(p)) return "intellij-windows"; return defaultPreset(); } From a8a0cdb3155c1140348349afe9086ee568652a9c Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:16:20 +0800 Subject: [PATCH 25/66] fix(plugins): load precompiled plugin components in the signed macOS app (#7010) compile_cached loaded the cached .cwasm with Component::deserialize_file, which maps the file and makes its pages executable; the hardened runtime of the signed app refuses that, so every activation discarded the cache and compiled the plugin again. The file is now read into memory and deserialized from the bytes. A new test checks the cache is hit; signed with the app entitlements it fails with the old code. Refs #6954 --- crates/ide-plugin/src/runtime.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 6306754cf..f6519e668 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -613,11 +613,14 @@ impl PluginEngine { pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result { let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?; let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes))); - if file.is_file() { + // Read into memory rather than `deserialize_file`: that maps the file and makes its pages + // executable, which the hardened runtime of the signed macOS app refuses ("failed to make + // memory executable"), so the cache never hit and every activation compiled again. + if let Ok(precompiled) = std::fs::read(&file) { // SAFETY: the cache directory belongs to the IDE (inside its plugins // directory) and is written only by `store_precompiled` below from // components this engine compiled; a corrupt file fails validation. - match unsafe { Component::deserialize_file(&self.engine, &file) } { + match unsafe { Component::deserialize(&self.engine, &precompiled) } { Ok(component) => return Ok(component), Err(e) => { tracing::info!("discarding precompiled {}: {e}", file.display()); @@ -3035,6 +3038,26 @@ impl Runtime { mod tests { use super::*; + /// The second compile of the same component loads the cached one instead of compiling and + /// writing it again (a failed load deletes and rewrites the file). + #[test] + fn a_precompiled_component_is_loaded_from_the_cache() { + let engine = PluginEngine::new().unwrap(); + let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm"); + let cache = tempfile::tempdir().unwrap(); + engine.compile_cached(&wasm, cache.path()).unwrap(); + let cached = || { + let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect(); + assert_eq!(entries.len(), 1, "{entries:?}"); + let file = entries[0].clone(); + (std::fs::metadata(&file).unwrap().modified().unwrap(), file) + }; + let before = cached(); + std::thread::sleep(std::time::Duration::from_millis(20)); + engine.compile_cached(&wasm, cache.path()).unwrap(); + assert_eq!(cached(), before, "loaded, not compiled and stored again"); + } + #[test] fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() { let fields = [ From 1cfbb24b31c7a6b3de7d85c47723c7589971e0cd Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:18:33 +0800 Subject: [PATCH 26/66] fix(project-tree): add Select Opened File as a Project View action for the keymap (#7011) The keymap listed "Select Opened File" only as the Database view action, so a shortcut assigned to it revealed the file in the Database view and did nothing in a project without data sources. Like IDEA's SelectOpenedFileInProjectView, the Project view now has its own Select Opened File action (the toolbar button runs it), and imported IDEA keymaps map SelectOpenedFileInProjectView and SelectInProjectView. Fixes #6978 --- src/features/project-tree/HeaderActions.tsx | 4 ++-- src/features/project-tree/actions.ts | 10 ++++++++++ src/features/project-tree/selectIn.test.ts | 12 ++++++++++++ src/platform/ideaActions.ts | 2 ++ src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + 6 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/features/project-tree/HeaderActions.tsx b/src/features/project-tree/HeaderActions.tsx index 44c6fcf8b..87888f3f9 100644 --- a/src/features/project-tree/HeaderActions.tsx +++ b/src/features/project-tree/HeaderActions.tsx @@ -100,9 +100,9 @@ export function ProjectHeaderActions() { {!alwaysSelect && ( )} diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts index 539d78975..72c781614 100644 --- a/src/features/project-tree/actions.ts +++ b/src/features/project-tree/actions.ts @@ -254,6 +254,16 @@ export function registerProjectActions(): () => void { keywords: ["locate", "reveal", "scroll from source", "select opened file"], run: ({ arg }) => void selectInProjectView(typeof arg === "string" ? arg : null), }, + { + // IDEA's SelectOpenedFileInProjectView: the Project view toolbar's locate button. + id: "project.selectOpenedFile", + title: "Select Opened File", + category: "Project View", + icon: "locate", + when: OPEN, + keywords: ["locate", "reveal", "scroll from source", "select in project view"], + run: () => void selectInProjectView(null), + }, { id: "project.reveal", title: "Reveal in Project View", diff --git a/src/features/project-tree/selectIn.test.ts b/src/features/project-tree/selectIn.test.ts index 517389c62..b4853ce68 100644 --- a/src/features/project-tree/selectIn.test.ts +++ b/src/features/project-tree/selectIn.test.ts @@ -152,6 +152,18 @@ describe("Select In (⌥F1)", () => { expect(useContextMenuStore.getState().menu).toBeNull(); }); + it("Select Opened File is a Project View action of its own, as in IDEA's keymap", async () => { + const { IDEA_ACTIONS } = await import("@/platform/ideaActions"); + disposers.push(registerProjectActions(), () => setContext("projectOpen", false)); + setContext("projectOpen", true); + expect(getAction("project.selectOpenedFile")).toMatchObject({ + title: "Select Opened File", + category: "Project View", + }); + expect(IDEA_ACTIONS.SelectOpenedFileInProjectView).toBe("project.selectOpenedFile"); + expect(IDEA_ACTIONS.SelectInProjectView).toBe("navigate.selectInProjectView"); + }); + it("expands an in-project folder when expand is true and reveals out-of-project folders in the file manager", async () => { const { useProjectTree } = await import("./store"); const prev = useProjectTree.getState(); diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index 25663dd98..0789cb8ac 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -6,6 +6,8 @@ export const IDEA_ACTIONS: Readonly> = { GotoDeclaration: "navigate.declaration", GotoImplementation: "navigate.implementation", GotoTypeDeclaration: "navigate.typeDeclaration", + SelectInProjectView: "navigate.selectInProjectView", + SelectOpenedFileInProjectView: "project.selectOpenedFile", GotoSuperMethod: "navigate.superMethod", GotoTest: "navigate.gotoTest", GotoRelated: "navigate.relatedSymbol", diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 2e17e48e5..8a85ab86e 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -531,6 +531,7 @@ export const intellijMacos: Record = { "db.showDiagram": ["Meta+Alt+Shift+U"], "db.showDiagramPopup": ["Meta+Alt+U"], "db.selectOpened": [], + "project.selectOpenedFile": [], "db.expandAll": [], "db.collapseAll": [], // Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there. diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 0b3be6116..1c251e4ec 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -529,6 +529,7 @@ export const intellijWindows: Record = { "db.showDiagram": ["Ctrl+Alt+Shift+U"], "db.showDiagramPopup": ["Ctrl+Alt+U"], "db.selectOpened": [], + "project.selectOpenedFile": [], "db.expandAll": [], "db.collapseAll": [], // Terminal (keyWhen: terminalFocus); after VCS Update / Go to Test so it wins there. From cc9279a6d6026fbbfd4324b9738517f673e85c87 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:22:26 +0800 Subject: [PATCH 27/66] fix(editor): indent Slint element blocks by their braces (#7012) Slint borrows the C mode for highlighting until slint-lsp's semantic tokens arrive, and Enter used that mode's statement indentation: after a child element's closing brace the next line went back to column 0, and nested blocks below it opened one level short. Slint now uses the brace-based fallback indentation even though a highlighting mode is loaded. No other language with a borrowed mode has this mismatch. Fixes #6976 --- src/editor/core/cm/languages.test.ts | 44 ++++++++++++++++++++++++++-- src/editor/core/cm/languages.ts | 9 +++++- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/editor/core/cm/languages.test.ts b/src/editor/core/cm/languages.test.ts index ac9979a5b..5e07204b3 100644 --- a/src/editor/core/cm/languages.test.ts +++ b/src/editor/core/cm/languages.test.ts @@ -1,12 +1,12 @@ import { EditorSelection, EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { insertNewlineAndIndent } from "@codemirror/commands"; -import { LanguageDescription, type Language } from "@codemirror/language"; +import { LanguageDescription, indentUnit, type Language } from "@codemirror/language"; import { describe, expect, it } from "vitest"; import { getIndentation } from "@codemirror/language"; import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight"; import { logWarning } from "./highlight"; -import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages"; +import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages"; describe("language modes", () => { it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => { @@ -765,3 +765,43 @@ describe("language modes", () => { expect(found).not.toContain("yes:keyword"); }); }); + +describe("Slint indentation", () => { + it("indents element blocks by their braces under the C highlighting mode", async () => { + const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!); + const slint = commentTokens({ + id: "slint", + name: "Slint", + extensions: ["slint"], + uiMode: "C", + lineComment: "//", + blockComment: ["/*", "*/"], + indent: { tabSize: 4, insertSpaces: true }, + }); + const enter = (doc: string, at = doc.length) => { + const view = new EditorView({ + state: EditorState.create({ + doc, + selection: EditorSelection.cursor(at), + extensions: [support!, slint, indentUnit.of(" ")], + }), + parent: document.body, + }); + insertNewlineAndIndent(view); + const out = view.state.doc.toString(); + view.destroy(); + return out; + }; + const app = "export component App inherits Window {"; + expect(enter(app)).toBe(`${app}\n `); + expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`); + expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `); + // After a child element closes, the next line stays at the child's level. + expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe( + `${app}\n Text {\n text: "hi";\n }\n `, + ); + expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe( + `${app}\n Text {\n }\n Rectangle {\n `, + ); + }); +}); diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts index 09fce0bb2..a49c4ede0 100644 --- a/src/editor/core/cm/languages.ts +++ b/src/editor/core/cm/languages.ts @@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([ "gitattributes", ]); +/** + * Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's + * element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after + * one lands at the wrong column. These use the brace-based fallback indentation instead. + */ +const BRACE_INDENT_OVER_MODE = new Set(["slint"]); + function opensBlock(code: string, language: string | undefined): boolean { if (!code) return false; if (/[{([]$/.test(code)) return true; @@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string */ export function fallbackIndent(language?: string): Extension { return indentService.of((cx, pos) => { - if (cx.state.facet(languageFacet)) return undefined; + if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined; const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line; const stripComment = (text: string) => indentationCode(text, lineComment); From 7ff223001bc9d68de26a2596fb3d9f0259a22fc0 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:25:17 +0800 Subject: [PATCH 28/66] fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013) With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings. Fixes #6974 --- src/platform/fonts.test.ts | 23 +++++++++++++++++++++++ src/platform/fonts.ts | 22 ++++++++++++++++++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/platform/fonts.test.ts b/src/platform/fonts.test.ts index eaf8d7c58..01cfbcb5a 100644 --- a/src/platform/fonts.test.ts +++ b/src/platform/fonts.test.ts @@ -101,6 +101,29 @@ describe("resolveMonoFont", () => { }); }); +describe("a chosen family that isn't installed", () => { + afterEach(() => { + vi.resetModules(); + }); + + it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => { + const fonts = await import("./fonts"); + // Before the native catalog loads nothing is known to be missing. + expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`); + fonts.noteInstalledFonts(["PingFang SC", "Menlo"]); + expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe( + `"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`, + ); + // Installed, bundled and generic families keep the fallback right after them; so does no fallback. + expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`); + expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe( + `"Inter", "Inter Variable", "PingFang SC", ${BASE}`, + ); + expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`); + expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`); + }); +}); + describe("discovered Nerd Font fallbacks (#3723)", () => { afterEach(() => { vi.resetModules(); diff --git a/src/platform/fonts.ts b/src/platform/fonts.ts index 9990f2ae8..f9cc7a1c7 100644 --- a/src/platform/fonts.ts +++ b/src/platform/fonts.ts @@ -98,12 +98,15 @@ async function loadUserFont(name: string, alias: string): Promise { * face is named alone unless the native catalog lists an installed JetBrains Mono. */ let monoInstalled: boolean | null = null; +/** Lower-cased installed family names from the native catalog, once it has loaded. */ +let installedFamilies: ReadonlySet | null = null; const bundledMonoOnly = () => guessOs() === "linux" && monoInstalled !== true; const BUNDLED_MONO_STACK = '"JetBrains Mono Variable", ui-monospace, monospace'; /** Records whether the system has JetBrains Mono installed (`installed`: the native catalog, not the bundled list). */ export function noteInstalledFonts(installed: readonly string[], root?: HTMLElement): void { - monoInstalled = installed.some((name) => name.trim().toLowerCase() === BUNDLED_MONO_FAMILY.toLowerCase()); + installedFamilies = new Set(installed.map((name) => name.trim().toLowerCase())); + monoInstalled = installedFamilies.has(BUNDLED_MONO_FAMILY.toLowerCase()); installMonoStack(root); } @@ -256,7 +259,22 @@ export function monoFontFamily(family: string | undefined, fallback = "", base = const name = familyName(family ?? ""); const fb = familyName(fallback); const head = familyFaces(name || BUNDLED_MONO_FAMILY); - return [...head, ...(fb ? familyFaces(fb) : []), base].join(", "); + // A chosen family that isn't installed leaves every glyph to the fallback, often a CJK face + // whose Latin letters are proportional: a grid measures its cells by the widest of them and + // the text comes out spread apart. The bundled face stands in for the missing one, and the + // fallback still covers what that lacks. + const standIn = fb && name && familyMissing(name) ? familyFaces(BUNDLED_MONO_FAMILY) : []; + return [...head, ...standIn, ...(fb ? familyFaces(fb) : []), base].join(", "); +} + +const GENERIC_FAMILIES = + /^(?:monospace|ui-monospace|sans-serif|serif|system-ui|ui-sans-serif|ui-serif|cursive|fantasy)$/i; + +/** Whether the native catalog has loaded and doesn't list `name` (bundled and generic families always count as present). */ +function familyMissing(name: string): boolean { + if (!installedFamilies) return false; + const key = name.toLowerCase(); + return !installedFamilies.has(key) && !BUNDLED_FACES.has(key) && !GENERIC_FAMILIES.test(name); } /** Tools › Terminal › Font, shared by the terminal and the Run console. */ From b9e555300f42ed83fff0919dbe4f9c465db6eea7 Mon Sep 17 00:00:00 2001 From: Ivan <87540740+Pecnikas@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:30:57 +0500 Subject: [PATCH 29/66] fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997) Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before. Fixes #6937 Co-authored-by: Pecnikas <87540740+Pecnikas@users.noreply.github.com> --- src-tauri/src/application_focus.rs | 2 ++ src-tauri/src/macos.rs | 10 ++++++++++ src-tauri/src/window_groups.rs | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/src-tauri/src/application_focus.rs b/src-tauri/src/application_focus.rs index be929ce70..7b4edfd53 100644 --- a/src-tauri/src/application_focus.rs +++ b/src-tauri/src/application_focus.rs @@ -26,6 +26,8 @@ impl ApplicationFocus { pub fn changed(app: &tauri::AppHandle, focused: bool) { let generation = app.state::().changed(focused); if focused { + #[cfg(target_os = "macos")] + crate::window_groups::detach_deferred(app); return; } let app = app.clone(); diff --git a/src-tauri/src/macos.rs b/src-tauri/src/macos.rs index 9eb560dae..28ebadadd 100644 --- a/src-tauri/src/macos.rs +++ b/src-tauri/src/macos.rs @@ -114,6 +114,16 @@ pub fn sync_tab_group( }) } +pub fn fullscreen_in_background(window: &WebviewWindow) -> bool { + let target = window.clone(); + on_main(window, move || { + let active = + MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive()); + !active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen)) + }) + .unwrap_or(false) +} + /// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own. pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> { let target = window.clone(); diff --git a/src-tauri/src/window_groups.rs b/src-tauri/src/window_groups.rs index 29d0797b1..40b3dc1d7 100644 --- a/src-tauri/src/window_groups.rs +++ b/src-tauri/src/window_groups.rs @@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> { select(app, caller, caller) } +#[cfg(target_os = "macos")] +static DEFERRED_DETACH: parking_lot::Mutex> = parking_lot::Mutex::new(Vec::new()); + pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> { let err = |e: tauri::Error| IdeError::internal(e.to_string()); let state = app.state::(); + #[cfg(target_os = "macos")] + if state.groups.lock().group(caller).is_some() + && app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w)) + { + DEFERRED_DETACH.lock().push(caller.to_owned()); + return Ok(()); + } let Some(next) = state.groups.lock().detach(caller) else { changed(app); return Ok(()); @@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> { Ok(()) } +#[cfg(target_os = "macos")] +pub fn detach_deferred(app: &AppHandle) { + let labels = std::mem::take(&mut *DEFERRED_DETACH.lock()); + for label in labels { + let _ = detach(app, &label); + } +} + pub fn destroyed(app: &AppHandle, caller: &str) { let Some(state) = app.try_state::() else { return }; let next = state.groups.lock().detach(caller); From 88a6bbca14b339bf32dec2eb27edb4f2e82c4345 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:32:37 +0800 Subject: [PATCH 30/66] perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006) history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-vcs/src/history.rs | 72 +++++++++++++++++++++++------ crates/ide-vcs/tests/log_lock.rs | 79 ++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 15 deletions(-) create mode 100644 crates/ide-vcs/tests/log_lock.rs diff --git a/crates/ide-vcs/src/history.rs b/crates/ide-vcs/src/history.rs index 803eedb1b..b73b7aa4b 100644 --- a/crates/ide-vcs/src/history.rs +++ b/crates/ide-vcs/src/history.rs @@ -464,11 +464,16 @@ fn renamed_from( Ok(None) } +/// The log index, locked only around reads and writes: Git runs without it, so commit +/// details and one-commit queries need not wait for a long history walk. +fn lock(index: &std::sync::Mutex) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> { + index.lock().unwrap_or_else(|p| p.into_inner()) +} + pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner()); let result = if q.summary_only { let mut all = q.clone(); all.skip = 0; @@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::>()).unwrap_or_default(); let shallow: HashSet = shallow_vec.iter().copied().collect(); let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?); - let cached = index.views.get(&key).cloned(); + let cached = lock(&r.log_index).views.get(&key).cloned(); let view = if let Some(cached) = cached { cached } else { // Immutable metadata is reused across roots, filters, merges and ref changes. all.request = q.request; - let rows = - std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?)); + let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows( + r, + &all, + cancel, + &r.log_index, + )?)); + let mut index = lock(&r.log_index); if index.views.len() >= 4 { index.views.clear(); } @@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0); let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) }; let total = view.rows.len() as u32; + let mut index = lock(&r.log_index); let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu } Ok(result) } else { - log_indexed(r, q, cancel, &mut index) + log_indexed(r, q, cancel, &r.log_index) }; - index.flush(); + lock(&r.log_index).flush(); result } @@ -640,7 +651,7 @@ fn log_indexed( r: &Repo, q: &LogQuery, cancel: &CancellationToken, - index: &mut crate::log_index::LogIndex, + shared: &std::sync::Mutex, ) -> IdeResult> { let repo = r.gix()?; let shallow: HashSet = @@ -676,6 +687,8 @@ fn log_indexed( && q.since_ms.is_none() && q.until_ms.is_none() { + let mut guard = lock(shared); + let index = &mut *guard; update_head_reachable(&repo, index, cancel)?; let id = tips[0]; let record = index.get(&repo, id)?; @@ -706,7 +719,9 @@ fn log_indexed( commit.message_truncated = false; return Ok(vec![commit]); } - let rows = log_indexed_rows(r, q, cancel, index)?; + let rows = log_indexed_rows(r, q, cancel, shared)?; + let mut guard = lock(shared); + let index = &mut *guard; let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -724,7 +739,7 @@ fn log_indexed_rows( r: &Repo, q: &LogQuery, cancel: &CancellationToken, - index: &mut crate::log_index::LogIndex, + shared: &std::sync::Mutex, ) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); @@ -775,7 +790,7 @@ fn log_indexed_rows( } } } - Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?) + Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?) } else { None }; @@ -802,14 +817,17 @@ fn log_indexed_rows( }; let authors: Vec<_> = q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect(); - update_head_reachable(&repo, index, cancel)?; let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::>()); type Walk<'a> = Box> + 'a>; let walk: Walk<'_> = if let Some(ids) = range_ids { Box::new(ids.into_iter().map(Ok)) } else if q.summary_only { - let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?; - Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok)) + // One guard for both: a concurrent query with another shallow set resets `nodes`. + let mut guard = lock(shared); + let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?; + let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?; + drop(guard); + Box::new(sorted.into_iter().map(Ok)) } else if repo.is_shallow().unwrap_or(false) || q.request.is_some() { // The process can be interrupted even during indegree preparation. Git also // respects shallow boundaries while retaining a topological order. @@ -866,7 +884,7 @@ fn log_indexed_rows( LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder, LogOrder::Date => topo::Sorting::DateOrder, }; - let topo = topo::Builder::from_iters(&repo.objects, tips, None::>) + let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::>) .sorting(sorting) .parents(if q.first_parent { Parents::First } else { Parents::All }) .with_commit_graph(graph) @@ -876,11 +894,20 @@ fn log_indexed_rows( }; let walk: Walk<'_> = if q.order == LogOrder::Standard { let ids = walk.collect::>>()?; - Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok)) + Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok)) } else { walk }; let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten(); + let mut guard = lock(shared); + let index = &mut *guard; + // Under the guard that builds the rows: a query run meanwhile (after a branch switch) + // may have moved the shared set to another HEAD. + update_head_reachable(&repo, index, cancel)?; + // A query started before a shallow change may have reset `nodes` to its older set. + if index.shallow != shallow { + index.ensure_nodes(&repo, &tips, &shallow, cancel)?; + } let db = index.db().cloned(); let txn = db.as_ref().and_then(|db| db.begin_read().ok()); let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok()); @@ -952,6 +979,21 @@ fn log_indexed_rows( Ok(out) } +/// Sorts with the shared nodes only when they were built for this query's shallow set. +fn sort_shared( + repo: &gix::Repository, + ids: Vec, + q: &LogQuery, + shallow: &HashSet, + cancel: &CancellationToken, + shared: &std::sync::Mutex, +) -> IdeResult> { + let guard = lock(shared); + let empty = HashMap::new(); + let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty }; + sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes) +} + /// A ready-node stack gives incoming merge parents priority, while child counts /// prevent an ancestor shared with another branch from moving ahead of its children. fn sort_subset( diff --git a/crates/ide-vcs/tests/log_lock.rs b/crates/ide-vcs/tests/log_lock.rs new file mode 100644 index 000000000..e14622842 --- /dev/null +++ b/crates/ide-vcs/tests/log_lock.rs @@ -0,0 +1,79 @@ +//! A long file history walk must not hold the log index while Git runs: commit details and +//! one-commit queries (inline blame, the blame popup) share that index. +#![cfg(unix)] + +use ide_vcs::{LogQuery, Repo}; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::Command; +use std::time::{Duration, Instant}; + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(dir) + .args([ + "-c", + "init.defaultBranch=main", + "-c", + "user.name=T", + "-c", + "user.email=t@e", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +#[test] +fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("repo"); + std::fs::create_dir(&dir).unwrap(); + git(&dir, &["init", "-q"]); + for i in 0..3 { + std::fs::write(dir.join("file"), format!("{i}")).unwrap(); + git(&dir, &["add", "-A"]); + git(&dir, &["commit", "-qm", &format!("c{i}")]); + } + // A git whose path-limited history walks take seconds. + let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap(); + let started = tmp.path().join("walk-started"); + let wrapper = tmp.path().join("slow-git"); + std::fs::write( + &wrapper, + format!( + "#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n", + started.display(), + real.trim() + ), + ) + .unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + let repo = Repo::discover(&dir).unwrap().unwrap(); + repo.set_execution_allowed(true); + repo.set_git_executable(Some(&wrapper)); + std::thread::scope(|scope| { + let walk = scope.spawn(|| { + repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len() + }); + let deadline = Instant::now() + Duration::from_secs(20); + while !started.exists() { + assert!(Instant::now() < deadline, "the history walk never started"); + std::thread::sleep(Duration::from_millis(20)); + } + let asked = Instant::now(); + let details = repo.log_details("HEAD").unwrap(); + let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap(); + let waited = asked.elapsed(); + println!("queries waited {waited:?}"); + assert_eq!(details.message, "c2"); + assert_eq!(head.len(), 1); + assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing"); + assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk"); + assert_eq!(walk.join().unwrap(), 3); + }); +} From c8dc6134857e5a3db4a6d093d53d68bf181eba1f Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 18:36:46 +0800 Subject: [PATCH 31/66] fix(projects): offer New Tab when opening a remote project or from a remote window (#7017) The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group. Fixes #6923 --- src/platform/locales/text/en.json | 1 + src/platform/locales/text/ru.json | 1 + src/platform/locales/text/tr.json | 1 + src/platform/locales/text/zh-TW.json | 1 + src/platform/locales/text/zh.json | 1 + src/workbench/projectWindow.test.ts | 30 ++++++++++++++++++++---- src/workbench/projectWindow.ts | 34 +++++++++++++++------------- 7 files changed, 48 insertions(+), 21 deletions(-) diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e36b79bf5..a89ff02d7 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3740,6 +3740,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.", "Hot reload on save failed: {0}": "Hot reload on save failed: {0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?", "New Tab": "New Tab", "New tab in current window": "New tab in current window", "Show Only Widgets": "Show Only Widgets", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index fe6ce8ffc..435c1b6b7 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -9762,6 +9762,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Сохранение файла Dart во время запущенной сессии отладки Flutter перезагружает приложение, если в файле нет ошибок.", "Hot reload on save failed: {0}": "Ошибка горячей перезагрузки при сохранении: {0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта, присоединять к уже открытым проектам или открывать как новую вкладку в этом окне.\nКак открыть «{name}»?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта или как новую вкладку в этом окне.\nКак открыть «{name}»?", "Show Only Widgets": "Показывать только виджеты", "Update failed": "Не удалось выполнить обновление", "Updating branches": "Обновление веток", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index eae689952..d3615f884 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -2668,6 +2668,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Çalışan Flutter hata ayıklama oturumunda Dart dosyası kaydedildiğinde, dosyada hata yoksa uygulama yeniden yüklenir.", "Hot reload on save failed: {0}": "Kaydetmede sıcak yeniden yükleme başarısız: {0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir, açık projelere bağlanabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?", "New Tab": "Yeni sekme", "New tab in current window": "Geçerli pencerede yeni sekme", "Show Only Widgets": "Yalnızca Bileşenleri Göster", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 96cb167cd..66fd1a18c 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9195,6 +9195,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "儲存正在執行的 Flutter 偵錯工作階段裡的 Dart 檔案時重新載入應用,檔案有錯誤時跳過。", "Hot reload on save failed: {0}": "儲存時熱過載失敗:{0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案、附加到已開啟的專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?", "Show Only Widgets": "僅顯示 Widget", "Update failed": "更新失敗", "Updating branches": "正在更新分支", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 63ca504eb..13538650e 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10315,6 +10315,7 @@ "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "保存正在运行的 Flutter 调试会话里的 Dart 文件时重新加载应用,文件有错误时跳过。", "Hot reload on save failed: {0}": "保存时热重载失败:{0}", "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目、附加到已打开的项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?", + "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?", "Show Only Widgets": "仅显示 Widget", "Update failed": "更新失败", "Updating branches": "正在更新分支", diff --git a/src/workbench/projectWindow.test.ts b/src/workbench/projectWindow.test.ts index 3ed189d27..9183155cd 100644 --- a/src/workbench/projectWindow.test.ts +++ b/src/workbench/projectWindow.test.ts @@ -7,9 +7,11 @@ import { ask } from "./messages"; import { commands } from "@/platform/ipc"; const windowOpenRemote = vi.fn(); +const windowGroupJoin = vi.fn(); +const remoteWindow = vi.hoisted(() => ({ value: false })); vi.mock("./messages", () => ({ ask: vi.fn() })); vi.mock("@/platform/remote", () => ({ - isRemoteWindow: () => false, + isRemoteWindow: () => remoteWindow.value, connectRemote: vi.fn(), })); vi.mock("@/platform/ipc", () => ({ @@ -18,10 +20,12 @@ vi.mock("@/platform/ipc", () => ({ commands: { settingsSet: vi.fn(async () => ({ general: { openProjectIn: "attach" } })), windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a), + windowGroupJoin: (...a: unknown[]) => windowGroupJoin(...a), }, })); beforeEach(() => { vi.clearAllMocks(); + remoteWindow.value = false; useProject.setState({ project: { root: "/a", name: "A", settings: {}, trusted: true, isGit: false }, settings: {}, @@ -40,14 +44,20 @@ it("offers attach for this open without remembering it", async () => { expect(await chooseProjectWindow("C")).toBe(button); expect(ask).toHaveBeenCalledTimes(2); }); -it("does not attach without a project or when opening a remote project", async () => { +it("offers a new tab but no attach for a remote project or from a remote window", async () => { useProject.setState({ settings: { general: { openProjectIn: "attach" } } as never, }); vi.mocked(ask).mockResolvedValue({ button: "cancel", checked: false }); expect(await chooseProjectWindow("remote", false)).toBeNull(); - expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]); - useProject.setState({ project: null }); + expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]); + remoteWindow.value = true; + expect(await chooseProjectWindow("B")).toBeNull(); + expect(vi.mocked(ask).mock.calls[1]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]); + useProject.setState({ project: null, lightEdit: true }); + expect(await chooseProjectWindow("B")).toBeNull(); + expect(vi.mocked(ask).mock.calls[2]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]); + useProject.setState({ project: null, lightEdit: false }); expect(await chooseProjectWindow("B")).toBe("same"); }); @@ -65,7 +75,7 @@ it("opens a project tab by policy, or a new window when this one can't take one" useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never); expect(openPolicy()).toBe("tab"); expect(await chooseProjectWindow("B")).toBe("tab"); - expect(await chooseProjectWindow("remote", false)).toBe("new"); + expect(await chooseProjectWindow("remote", false)).toBe("tab"); useProject.setState({ project: null, lightEdit: true }); expect(await chooseProjectWindow("B")).toBe("new"); expect(ask).not.toHaveBeenCalled(); @@ -91,6 +101,16 @@ describe("a recent project opened with a modifier key", () => { usePlatform.setState({ os }); }); + it("opens a remote project as a project tab of this window", async () => { + windowOpenRemote.mockResolvedValueOnce({ kind: "current" }).mockResolvedValueOnce({ kind: "opened", label: "w2" }); + const here = vi.fn(async () => {}); + useProject.setState({ settings: { general: { openProjectIn: "tab" } } as never }); + expect(await openRemoteProject(target, "/home/me/app", here)).toBe(true); + expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true); + expect(windowGroupJoin).toHaveBeenCalledWith("w2"); + expect(here).not.toHaveBeenCalled(); + }); + it("opens a remote project in that window without asking", async () => { windowOpenRemote.mockResolvedValue({ kind: "opened" }); const here = vi.fn(async () => {}); diff --git a/src/workbench/projectWindow.ts b/src/workbench/projectWindow.ts index 309d63db3..292d8da51 100644 --- a/src/workbench/projectWindow.ts +++ b/src/workbench/projectWindow.ts @@ -40,26 +40,26 @@ export async function chooseProjectWindow( ): Promise<"new" | "same" | "attach" | "tab" | null> { const { project, lightEdit } = useProject.getState(); if (!project && !lightEdit) return "same"; - // Both ways of keeping this window's project: a workspace folder, or a project tab of this window. - const canAdd = allowAttach && !!project && !isRemoteWindow(); + // Attach adds a local folder to this local window's workspace; a project tab is a window of its + // own joined to this one's group, so it takes remote projects and remote windows too. + const canTab = !!project; + const canAttach = allowAttach && canTab && !isRemoteWindow(); const mode = openPolicy(); // A project tab needs this window's project beside it; without one, a new window is the closest. - if (mode === "tab") return canAdd ? "tab" : "new"; + if (mode === "tab") return canTab ? "tab" : "new"; if (mode !== "ask") return mode; const r = await ask({ title: t("app.window.askTitle"), - width: canAdd ? 640 : undefined, - body: canAdd + width: canAttach ? 640 : undefined, + body: canAttach ? tx`Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open "${name}"?` - : t("app.window.askBody", { name }), + : canTab + ? tx`Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open "${name}"?` + : t("app.window.askBody", { name }), buttons: [ { id: "cancel", label: t("common.cancel") }, - ...(canAdd - ? [ - { id: "attach", label: t("app.window.askAttach") }, - { id: "tab", label: tx`New Tab` }, - ] - : []), + ...(canAttach ? [{ id: "attach", label: t("app.window.askAttach") }] : []), + ...(canTab ? [{ id: "tab", label: tx`New Tab` }] : []), { id: "new", label: t("app.window.askNew") }, { id: "same", label: t("app.window.askThis"), primary: true }, ], @@ -81,8 +81,8 @@ export async function chooseProjectWindow( /** * Opens folder `path` of `target` (an SSH host or a WSL distribution): focuses the - * window that has it, else opens it in a new window or (`here`) this one per - * "Open project in", or where `override` says. `false`: cancelled. + * window that has it, else opens it in a new window, a project tab of this window or + * (`here`) this one per "Open project in", or where `override` says. `false`: cancelled. */ export async function openRemoteProject( target: RemoteTarget, @@ -93,8 +93,10 @@ export async function openRemoteProject( if ((await call(commands.windowOpenRemote(target, path, false))).kind === "focused") return true; const mode = override ?? (await chooseProjectWindow(path.replace(/\/+$/, "").split("/").pop() || path, false)); if (!mode) return false; - if (mode === "new") { - await call(commands.windowOpenRemote(target, path, true)); + if (mode === "new" || mode === "tab") { + const outcome = await call(commands.windowOpenRemote(target, path, true)); + // As a local project tab: the window holding the project, new or focused, joins this one's group. + if (mode === "tab" && outcome.kind !== "current") await call(commands.windowGroupJoin(outcome.label)); return true; } // The remote host's project doesn't take this window's untitled buffers. From 182c7c1dbb0aa8cd515c6cfb461d8b368129e715 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=9B=E7=BA=AA=E5=85=8B?= <245674286@qq.com> Date: Mon, 30 Nov 2026 19:42:00 +0800 Subject: [PATCH 32/66] feat(editor): double-click the empty tab strip to maximize the editor (#6969) A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller. Closes #6968 Co-authored-by: xuejike <3352235+xuejike@users.noreply.github.com> --- docs/en/guide/editor.mdx | 2 ++ docs/zh/guide/editor.mdx | 2 ++ src/editor/core/view/EditorArea.tsx | 2 ++ src/ui/Tabs.test.tsx | 10 ++++++++++ src/ui/Tabs.tsx | 16 +++++++++++++++- 5 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index 294d27e0e..3f53f2fb6 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -145,6 +145,8 @@ Tab placement, the tab limit and what happens when it is reached, the preview ta With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered. +Double-click a tab, or the empty part of the tab strip, to maximize the editor: all tool windows are hidden, and doing it again brings them back. Double-clicking a preview tab keeps it open as a regular tab instead. + ## Split editors | Action | macOS | Windows / Linux | diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index d292cc19a..da721ae6a 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -143,6 +143,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。 +双击标签页或标签页栏的空白处可以最大化编辑器:隐藏所有工具窗口,再双击一次即恢复。双击预览标签页则会把它转为常规标签页。 + ## 拆分编辑器 | 操作 | macOS | Windows / Linux | diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 08fa0a23b..2a917b01d 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -399,6 +399,8 @@ function PaneView({ paneId }: { paneId: string }) { onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)} onTogglePin={(id) => ctrl.togglePin(paneId, id)} closeOnShiftClick + // IDEA: a double click on the strip's empty part maximizes the editor, as on a tab. + onBlankDoubleClick={() => void executeAction("toolwindow.hideAll")} onDoubleClick={(id) => { // IDEA: a preview tab becomes a regular one; any other tab maximizes the editor. if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id); diff --git a/src/ui/Tabs.test.tsx b/src/ui/Tabs.test.tsx index d5ebc4d1c..56f5d7501 100644 --- a/src/ui/Tabs.test.tsx +++ b/src/ui/Tabs.test.tsx @@ -103,6 +103,16 @@ describe("Tabs interactions", () => { expect(onClose).toHaveBeenCalledWith("b"); }); + it("double click on the empty strip calls onBlankDoubleClick, not on a tab", () => { + const onBlank = vi.fn(); + const { container } = render( {}} onBlankDoubleClick={onBlank} />); + fireEvent.doubleClick(screen.getByRole("tab", { name: "A" })); + expect(onBlank).not.toHaveBeenCalled(); + fireEvent.doubleClick(screen.getByRole("tablist")); + fireEvent.doubleClick(container.firstElementChild!); + expect(onBlank).toHaveBeenCalledTimes(2); + }); + it("Shift+left-click closes an editor tab without selecting it", () => { const onClose = vi.fn(); const onSelect = vi.fn(); diff --git a/src/ui/Tabs.tsx b/src/ui/Tabs.tsx index 57368298f..2c6d8b178 100644 --- a/src/ui/Tabs.tsx +++ b/src/ui/Tabs.tsx @@ -136,6 +136,8 @@ export interface TabsProps { /** Shift+left-click a tab closes it (editor tabs; plain clicks still select). */ closeOnShiftClick?: boolean; onDoubleClick?: (id: string) => void; + /** Double click on the empty part of the strip (not on a tab or button), e.g. to maximize the editor. */ + onBlankDoubleClick?: () => void; onContextMenu?: (id: string, e: MouseEvent) => void; /** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */ variant?: "editor" | "compact"; @@ -176,6 +178,7 @@ export function Tabs({ onTogglePin, closeOnShiftClick, onDoubleClick, + onBlankDoubleClick, onContextMenu, variant = "editor", trailing, @@ -397,7 +400,18 @@ export function Tabs({ ); return ( -
+
{ + // Only the strip's own background counts: tabs, buttons and trailing content handle their own clicks. + if (e.target === e.currentTarget || e.target === scrollRef.current) onBlankDoubleClick(); + } + : undefined + } + > {vertical && trailing &&
{trailing}
}
Date: Mon, 30 Nov 2026 19:43:10 +0800 Subject: [PATCH 33/66] feat(search): select Search Everywhere results in the Project view (#6955) File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders. Co-authored-by: Greenker <76565859+Greenker@users.noreply.github.com> --- .../search/__tests__/dialogs.test.tsx | 34 +++++++++ .../search/everywhere/SearchEverywhere.tsx | 74 ++++++++++++++----- 2 files changed, 88 insertions(+), 20 deletions(-) diff --git a/src/features/search/__tests__/dialogs.test.tsx b/src/features/search/__tests__/dialogs.test.tsx index 8d9c1177d..3e33f819f 100644 --- a/src/features/search/__tests__/dialogs.test.tsx +++ b/src/features/search/__tests__/dialogs.test.tsx @@ -62,6 +62,7 @@ vi.mock("../find/windowStore", async (orig) => ({ const contributions = await import("@/workbench/contributions"); const { commands, emitLocalIdeEvent } = await import("@/platform/ipc"); +const { ContextMenuHost } = await import("@/ui"); const { RecentPopupsOverlay } = await import("../recent/RecentPopups"); const { cycleSwitcher, showRecentPopup, hideRecentPopup, useRecentPopup } = await import("../recent/store"); const { openLocation } = await import("../common/open"); @@ -448,6 +449,39 @@ function clickOption(index: number, modifiers = {}) { fireEvent.click(row, modifiers); } +describe("Search Everywhere result actions", () => { + it.each(["keyboard", "right click"] as const)("selects a file in the Project view from the %s menu", async (how) => { + const run = vi.fn(); + const project = useProject.getState().project; + useProject.setState({ project: { root: "/p", name: "p", isGit: false } as never }); + const dispose = registerAction({ + id: "navigate.selectInProjectView", + title: "Select in Project View", + run: ({ arg }) => run(arg), + }); + try { + render( + <> + + + , + ); + act(() => showSearchEverywhere("files", { query: "order" })); + await tick(); + if (how === "keyboard") fireEvent.keyDown(screen.getByLabelText("Search query"), { key: "Enter", altKey: true }); + else fireEvent.contextMenu(resultOptions()[0]!); + await tick(); + fireEvent.click(screen.getByRole("menuitem", { name: /Select in Project View/ })); + await tick(); + expect(run).toHaveBeenCalledExactlyOnceWith("/p/src/OrderController.kt"); + expect(useSearchEverywhere.getState().open).toBe(false); + } finally { + dispose(); + useProject.setState({ project }); + } + }); +}); + describe("Search Everywhere multi-selection", () => { it("extends, shrinks, crosses the anchor and clamps Shift selection; plain arrows select one", async () => { const input = await showDuplicateFiles(); diff --git a/src/features/search/everywhere/SearchEverywhere.tsx b/src/features/search/everywhere/SearchEverywhere.tsx index a3bc86dcb..b6fb476c3 100644 --- a/src/features/search/everywhere/SearchEverywhere.tsx +++ b/src/features/search/everywhere/SearchEverywhere.tsx @@ -34,13 +34,14 @@ import { selectRow, selectedRows, rowSelectionMode, + showContextMenu, type RowSelection, type MenuItem, T, } from "@/ui"; import { useFileDecoration } from "@/workbench/contributions"; import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown"; -import { badgeKind, basename, openInListOrder, openLocation, relDir } from "../common/open"; +import { badgeKind, basename, openInListOrder, openLocation, projectRoot, relDir } from "../common/open"; import { parseLocationQuery } from "../common/query"; import { setTextSearchOption, useFindPopup } from "../find/store"; import { CodePreview, type PreviewHighlight } from "../find/parts"; @@ -441,35 +442,67 @@ function SearchEverywhereDialog() { /** IDEA's ⌥↵ on an action: record a shortcut for it (written to the active keymap). */ const assignShortcut = (id: string) => closeThen(() => void executeAction("settings.assignShortcut", id)); + /** Actions of a file, symbol or text result: IDEA's ⌥↵ menu and the row's context menu. */ + const resultMenu = (row: NavigationRow): MenuItem[] => { + const copy = (text: string) => void writeClipboardText(text).catch(() => {}); + const folder = row.kind === "file" && row.folder; + const root = projectRoot(); + const inProject = !!root && (row.path === root || row.path.startsWith(root.endsWith("/") ? root : `${root}/`)); + const items: MenuItem[] = [ + { label: "Open", run: () => activate(row) }, + { + label: "Open to the Side", + shortcut: formatBinding("Shift+Enter"), + disabled: !!folder, + run: () => activate(row, true), + }, + // IDEA's Select in Project View (Select Opened File): shows a result opened in another + // application (.doc in WPS) in the Project view, where its place in the project is visible. + ...(inProject + ? [ + { + label: "Select in Project View", + shortcut: shortcutLabel("navigate.selectInProjectView") ?? undefined, + run: () => closeThen(() => void executeActionFrom("search", "navigate.selectInProjectView", row.path)), + }, + ] + : []), + { kind: "separator" }, + ]; + items.push( + { label: "Copy Path", run: () => copy(nativePath(row.path)) }, + { label: "Copy Path from Project Root", run: () => copy(row.rel) }, + ...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []), + ...(row.kind === "file" || row.kind === "text" + ? [ + { + label: "Find in Directory…", + run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })), + }, + ] + : []), + ); + return items; + }; + const openIntentions = () => { const row = activeRow; if (!row || row.kind === "section" || row.kind === "more" || row.kind === "command") return; if (row.kind === "action") return row.run ? undefined : assignShortcut(row.id); const anchor = listRef.current?.querySelector('[data-lead="true"]') ?? inputRef.current; if (!anchor) return; - const copy = (text: string) => void writeClipboardText(text).catch(() => {}); const items: MenuItem[] = - row.kind === "setting" - ? [{ label: "Open Settings Page", run: () => activate(row) }] - : [ - { label: "Open", run: () => activate(row) }, - { label: "Open to the Side", shortcut: formatBinding("Shift+Enter"), run: () => activate(row, true) }, - { kind: "separator" }, - { label: "Copy Path", run: () => copy(nativePath(row.path)) }, - { label: "Copy Path from Project Root", run: () => copy(row.rel) }, - ...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []), - ...(row.kind === "file" || row.kind === "text" - ? [ - { - label: "Find in Directory…", - run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })), - }, - ] - : []), - ]; + row.kind === "setting" ? [{ label: "Open Settings Page", run: () => activate(row) }] : resultMenu(row); setMenu({ anchor, items, placement: "right-start" }); }; + const onRowContextMenu = (row: SeRow, index: number, e: MouseEvent) => { + if (row.kind !== "file" && row.kind !== "symbol" && row.kind !== "text") return; + e.preventDefault(); + select(index, e); + showContextMenu(e, resultMenu(row)); + }; + const onKeyDown = (e: KeyboardEvent) => { if (isImeKey(e.nativeEvent)) return; if (tab === "text" && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) { @@ -574,6 +607,7 @@ function SearchEverywhereDialog() { if (preview && previewOf(r) && e.type === "click" && e.detail !== 2) return; activate(r, e.shiftKey); }} + onContextMenu={onRowContextMenu} focusable={false} rowHeight={rowHeight} sectionHeight={rowHeight} From 2ecb44098aa779ec022b1e78b45830e93dad5bf2 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 19:48:37 +0800 Subject: [PATCH 34/66] fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030) A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts. --- crates/ide-dap/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 9379b7834..bf29baa13 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -618,9 +618,10 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult`) stay. +/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive. fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool { let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0); - reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists() + reference > 0 && Path::new(path).has_root() && !Path::new(path).exists() } /// DAP stack frame → [`StackFrame`] (1-based → 0-based). From 4d5ee2d01c1809659a115518791e3386a31224d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=9B=E7=BA=AA=E5=85=8B?= <245674286@qq.com> Date: Mon, 30 Nov 2026 19:56:24 +0800 Subject: [PATCH 35/66] feat(agents): drag and delete the whole task list selection (#6933) In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it. Closes #6932 Co-authored-by: xuejike <3352235+xuejike@users.noreply.github.com> --- src/features/agents/AgentsView.test.tsx | 21 ++++++--- src/features/agents/AgentsView.tsx | 54 +++++++++++++++++++----- src/features/agents/store.ts | 35 +++++++++++---- src/features/agents/taskActions.ts | 7 +++ src/platform/keymaps/intellij-macos.ts | 1 + src/platform/keymaps/intellij-windows.ts | 1 + src/platform/keymaps/vscode-macos.ts | 1 + src/platform/keymaps/vscode-windows.ts | 1 + src/ui/Tree.tsx | 12 +++++- 9 files changed, 109 insertions(+), 24 deletions(-) diff --git a/src/features/agents/AgentsView.test.tsx b/src/features/agents/AgentsView.test.tsx index 8104312be..4b11a539b 100644 --- a/src/features/agents/AgentsView.test.tsx +++ b/src/features/agents/AgentsView.test.tsx @@ -162,7 +162,7 @@ describe("Agents selection", () => { vi.mocked(openTask).mockClear(); context("two"); expect(selectedTasks()).toEqual(["one", "two", "three"]); - expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy(); + expect(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })).toBeTruthy(); expect(openTask).not.toHaveBeenCalled(); }); @@ -298,9 +298,20 @@ describe("Agents docked view", () => { setup(); expect(screen.queryByRole("button", { name: "Open in Editor" })).toBeNull(); select("two"); - expect(openTask).toHaveBeenCalledWith("two"); + expect(openTask).toHaveBeenCalledWith("two", { focus: false }); expect(dockTask).not.toHaveBeenCalled(); }); + + it("keeps focus in the list when a click opens a task, so Delete deletes that task", async () => { + setup(); + const tree = screen.getByRole("tree", { name: "Agent tasks" }); + tree.focus(); + select("two"); + expect(openTask).toHaveBeenCalledWith("two", { focus: false }); + // The shortcut runs the action without an argument: it takes the list's selection. + await taskActions.find((a) => a.id === "agents.deleteTasks")!.run({ ctx: {}, arg: undefined }); + await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("two", false)); + }); }); describe("Agents bulk actions", () => { @@ -311,7 +322,7 @@ describe("Agents bulk actions", () => { select("one"); select("three", { shiftKey: true }); context("two"); - fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" })); + fireEvent.click(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })); await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3)); expect(confirmChecked).toHaveBeenCalledTimes(1); expect(confirmChecked).toHaveBeenCalledWith( @@ -329,7 +340,7 @@ describe("Agents bulk actions", () => { select("one"); select("two", { shiftKey: true }); context("four"); - fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" })); + fireEvent.click(screen.getByRole("menuitem", { name: /^Delete…/ })); await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false)); }); @@ -784,6 +795,6 @@ describe("Agents pinned and grouped tasks", () => { expect(openTask).not.toHaveBeenCalled(); fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 }); fireEvent.click(sourceSpan, { button: 0 }); - expect(openTask).toHaveBeenCalledWith("two"); + expect(openTask).toHaveBeenCalledWith("two", { focus: false }); }); }); diff --git a/src/features/agents/AgentsView.tsx b/src/features/agents/AgentsView.tsx index 569e36230..c1cb4c77c 100644 --- a/src/features/agents/AgentsView.tsx +++ b/src/features/agents/AgentsView.tsx @@ -52,8 +52,8 @@ import { openHome, pinTasks, refreshExternalSessions, - reorderTask, reorderTaskGroup, + reorderTasks, showImportSessions, useAgents, } from "./store"; @@ -238,6 +238,8 @@ export function AgentsView() { searchingRef.current = matches !== null; }, [matches]); const cancelDragRef = useRef<(() => void) | undefined>(undefined); + /** Every task the current drag carries, in list order; set when it starts. */ + const draggedIdsRef = useRef([]); const [tasksEl, setTasksEl] = useState(null); const [dropIndicator, setDropIndicator] = useState(null); useEffect(() => { @@ -266,11 +268,18 @@ export function AgentsView() { const { tasks, organize } = useAgents.getState(); const source = tasks.get(data.payload); if (!source) return null; + // Dragging a selected task moves the whole selection. + const ids = draggedIdsRef.current.includes(source.id) ? draggedIdsRef.current : [source.id]; + const sources = ids.flatMap((id) => { + const task = tasks.get(id); + return task ? [task] : []; + }); + const sourceIds = sources.map((t) => t.id); if (targetKey === PINNED_SECTION) { return { indicator: { kind: "section", key: targetKey } as DropIndicator, - apply: () => pinTasks([source.id], true), + apply: () => pinTasks(sourceIds, true), }; } if (targetKey.startsWith("ug:")) { @@ -278,23 +287,33 @@ export function AgentsView() { if (!organize.groups.some((g) => g.id === groupId)) return null; return { indicator: { kind: "section", key: targetKey } as DropIndicator, - apply: () => moveTasksToGroup([source.id], groupId), + apply: () => moveTasksToGroup(sourceIds, groupId), }; } if (targetKey.startsWith("g:")) { - if (sectionOfTask(source, organize) === targetKey) return null; - if (statusSection(taskGroupStatus(source)) !== targetKey) return null; + // A status group takes the tasks of its status that are elsewhere. + const movable = sources.filter( + (t) => sectionOfTask(t, organize) !== targetKey && statusSection(taskGroupStatus(t)) === targetKey, + ); + if (!movable.length) return null; return { indicator: { kind: "section", key: targetKey } as DropIndicator, - apply: () => moveTasksToStatusGroup([source.id]), + apply: () => moveTasksToStatusGroup(movable.map((t) => t.id)), }; } if (searchingRef.current) return null; const target = tasks.get(targetKey); - if (!target || !canReorderTask(source, target, organize)) return null; + if (!target || sourceIds.includes(target.id)) return null; + const movable = sources.filter((t) => canReorderTask(t, target, organize)); + if (!movable.length) return null; return { indicator: { kind: "row", key: targetKey, position } as DropIndicator, - apply: () => reorderTask(source.id, target.id, position), + apply: () => + reorderTasks( + movable.map((t) => t.id), + target.id, + position, + ), }; }; const update = () => { @@ -383,11 +402,26 @@ export function AgentsView() { setHistoryOpen(false); void executeAction("agents.openTask", task); }; + // A click or arrow key in the list opens the session but keeps focus in the list, so its + // shortcuts (Delete) still act on the selection; Enter and double-click focus the session. + const previewTask = (task: string) => { + if (inline) showTask(task); + else void executeAction("agents.openTask", { task, focus: false }); + }; const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null; const dragTask = (e: ReactPointerEvent, task: string, source: HTMLElement = e.currentTarget) => { suppressClickRef.current = false; if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return; cancelDragRef.current?.(); + // A selected row drags the whole selection, in list order. + const current = selectedRef.current; + draggedIdsRef.current = + current.size > 1 && current.has(task) + ? roots + .flatMap((n) => (n.kind === "group" ? n.group.tasks : n.kind === "task" ? [n.task] : n.tasks)) + .map((t) => t.id) + .filter((id, i, all) => current.has(id) && all.indexOf(id) === i) + : [task]; cancelDragRef.current = startPointerDrag( e, source, @@ -478,7 +512,7 @@ export function AgentsView() { if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return; if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return; const key = (e.target as Element).closest("[data-tree-key]")?.dataset.treeKey; - if (key && tasks.has(key)) showTask(key); + if (key && tasks.has(key)) previewTask(key); }} onFocus={() => setFocusedTaskList(() => [...selectedRef.current])} onBlur={(e) => { @@ -554,7 +588,7 @@ export function AgentsView() { lead?.kind === "task" && sel.has(lead.task.id) ) - showTask(lead.task.id); + previewTask(lead.task.id); }} onActivate={(n) => n.kind === "task" && showTask(n.task.id)} onContextMenu={(n, sel, e) => { diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index c548ed681..57f8d1f75 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -57,6 +57,7 @@ import { withQuote } from "./conversation"; import { EMPTY_ORGANIZE, PINNED_SECTION, + canReorderTask, compactOrder, customSection, loadOrganize, @@ -1184,7 +1185,8 @@ export function useAgentCommands( return extra.length > 0 ? [...filtered, ...extra] : filtered; } -export function openTask(task: string) { +/** Opens the task's session; `focus: false` opens it in the editor without taking focus (a click in the task list). */ +export function openTask(task: string, options: { focus?: boolean } = {}) { if (routeToWindow(task)) return; forgetClosed(task); if (useAgents.getState().sessionLocation === "toolWindow") { @@ -1192,13 +1194,13 @@ export function openTask(task: string) { return; } useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task }); - openTaskInEditor(task); + openTaskInEditor(task, options.focus ?? true); } -function openTaskInEditor(task: string) { +function openTaskInEditor(task: string, focus = true) { // The title rides along so a restored tab has it before the tasks load. const title = useAgents.getState().tasks.get(task)?.title; - void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true }); + void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus }); } function showDockedTask(task: string) { @@ -2189,10 +2191,27 @@ export function moveTasksToStatusGroup(tasks: readonly string[]) { }); } -/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */ -export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") { - const tasks = useAgents.getState().tasks.values(); - changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position)); +/** + * Places `sourceIds` (in list order) before or after `targetId`, keeping their relative order. + * Tasks that can't go beside the target (another status than its status group) stay where they are. + */ +export function reorderTasks(sourceIds: readonly string[], targetId: string, position: "before" | "after") { + const tasks = [...useAgents.getState().tasks.values()]; + changeOrganize((organize) => { + let next = organize; + // Before: each goes right before the target. After: each goes after the one placed last. + let anchor = targetId; + const byId = new Map(tasks.map((t) => [t.id, t])); + for (const id of sourceIds) { + if (id === targetId) continue; + const source = byId.get(id); + const target = byId.get(anchor); + if (!source || !target || !canReorderTask(source, target, next)) continue; + next = reorderTaskInOrganize(next, tasks, id, anchor, position); + if (position === "after") anchor = id; + } + return next; + }); } /** Reorders a custom group before or after another custom group. */ diff --git a/src/features/agents/taskActions.ts b/src/features/agents/taskActions.ts index eb93a3f1d..e9e97fe0c 100644 --- a/src/features/agents/taskActions.ts +++ b/src/features/agents/taskActions.ts @@ -285,6 +285,11 @@ export const taskActions: Action[] = [ hidden: true, run: ({ arg }) => { if (typeof arg === "string") openTask(arg); + // `{ task, focus: false }`: a click in the task list opens the session and keeps focus there. + else if (arg && typeof arg === "object" && typeof (arg as { task?: unknown }).task === "string") { + const { task, focus } = arg as { task: string; focus?: unknown }; + openTask(task, { focus: focus !== false }); + } }, }, { @@ -396,6 +401,8 @@ export const taskActions: Action[] = [ title: "Delete Agent Tasks", category: "Agents", hidden: true, + // Without an argument the shortcut deletes the task list's selection. + keyWhen: "agentTaskListFocus", run: ({ arg }) => confirmDelete(resolveTasks(arg)), }, { diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 8a85ab86e..981510c72 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -495,6 +495,7 @@ export const intellijMacos: Record = { "agents.sendToAgent": [], // Agents task list (when it has focus) "agents.archiveTasks": ["Meta+Shift+E"], + "agents.deleteTasks": ["Delete", "Meta+Backspace"], // Database tool window (when the tree has focus; `db.openConsole` anywhere). "db.openConsole": ["Meta+Shift+L"], "db.newDataSource": [], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 1c251e4ec..a9c4f02b6 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -493,6 +493,7 @@ export const intellijWindows: Record = { "agents.sendToAgent": [], // Agents task list (when it has focus) "agents.archiveTasks": ["Ctrl+Shift+E"], + "agents.deleteTasks": ["Delete"], // Database tool window (when the tree has focus; `db.openConsole` anywhere). "db.openConsole": ["Ctrl+Shift+Q"], "db.newDataSource": [], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index d57d6a1d2..cabe47ee6 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -528,6 +528,7 @@ export const vscodeMacos: Record = { "agents.sendToAgent": [], // Agents task list (when it has focus) "agents.archiveTasks": ["Meta+Shift+E"], + "agents.deleteTasks": ["Meta+Backspace"], // Python Console: VS Code's Shift+Enter would shadow typing in Python files, so unbound. "python.console.executeSelection": [], // Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused. diff --git a/src/platform/keymaps/vscode-windows.ts b/src/platform/keymaps/vscode-windows.ts index a73bda3a8..0b9c49e50 100644 --- a/src/platform/keymaps/vscode-windows.ts +++ b/src/platform/keymaps/vscode-windows.ts @@ -45,6 +45,7 @@ export const vscodeWindows: Record = { "project.rename": ["F2"], "project.delete": ["Delete"], "db.drop": ["Delete"], + "agents.deleteTasks": ["Delete"], "project.copyAbsolutePath": ["Alt+Shift+C"], "project.open": [], "project.openInRightSplit": ["Ctrl+Enter"], diff --git a/src/ui/Tree.tsx b/src/ui/Tree.tsx index bdaf5b22c..b589434a8 100644 --- a/src/ui/Tree.tsx +++ b/src/ui/Tree.tsx @@ -749,7 +749,17 @@ export function Tree(props: TreeProps) { endSearch(); if (e.shiftKey) selectIndex(i, "range"); else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle"); - else selectIndex(i); + else if (multiSelect && selected.size > 1 && selected.has(rows[i]!.key)) { + // Pressing a row of a multi-selection keeps the selection so a drag carries all of it; + // a release without moving (a plain click) narrows it to the row. + const x0 = e.clientX; + const y0 = e.clientY; + const up = (u: globalThis.MouseEvent) => { + window.removeEventListener("mouseup", up, true); + if (Math.abs(u.clientX - x0) < 4 && Math.abs(u.clientY - y0) < 4) selectIndex(i); + }; + window.addEventListener("mouseup", up, true); + } else selectIndex(i); }; const leadRow = leadIndex >= 0 ? rows[leadIndex] : undefined; From f47a83828cbd514878920e338365ccda20760f1a Mon Sep 17 00:00:00 2001 From: Muu Date: Mon, 30 Nov 2026 19:58:05 +0800 Subject: [PATCH 36/66] feat(structure): temporarily enable filters to find matches (#6934) With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- e2e/fileStructureLayout.spec.ts | 87 ++++++++++ .../search/__tests__/fileStructure.test.tsx | 151 +++++++++++++++++- .../search/structure/StructureView.tsx | 111 +++++++++++-- src/features/search/structure/store.ts | 41 ++++- 4 files changed, 369 insertions(+), 21 deletions(-) diff --git a/e2e/fileStructureLayout.spec.ts b/e2e/fileStructureLayout.spec.ts index b9cb4828b..ca649b203 100644 --- a/e2e/fileStructureLayout.spec.ts +++ b/e2e/fileStructureLayout.spec.ts @@ -202,6 +202,93 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false"); }); +test("File Structure auto-enables temporary filters without saving them", async ({ workbench: page }) => { + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate(async () => { + const optionsPath = "/src/features/search/structure/store.ts"; + const { useStructureOptions } = await import(/* @vite-ignore */ optionsPath); + useStructureOptions.setState({ showFields: false, showNonPublic: false, showInherited: false, narrowDown: true }); + const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } }; + const symbol = (name: string, kind: string, visibility?: string) => ({ + name, + kind, + visibility, + range, + selection_range: range, + children: [], + }); + window.__ipc.handlers.doc_outline = () => [ + { + ...symbol("Container", "class"), + children: [ + symbol("hiddenField", "field"), + symbol("hiddenMethod", "method", "private"), + symbol("visible", "method"), + ], + }, + ]; + window.__ipc.handlers.lsp_type_hierarchy = () => []; + const actionsPath = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsPath); + await executeAction("navigate.fileStructure"); + }); + + const dialog = page.getByRole("dialog", { name: "File Structure" }); + const filter = dialog.getByRole("textbox", { name: "Filter symbols" }); + const tree = dialog.getByRole("tree", { name: "Symbols" }); + const fields = dialog.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = dialog.getByRole("checkbox", { name: "Show non-public" }); + const readOptions = () => + page.evaluate(async () => { + const path = "/src/features/search/structure/store.ts"; + const { useStructureOptions } = await import(/* @vite-ignore */ path); + const { showFields, showNonPublic, showInherited } = useStructureOptions.getState(); + return { showFields, showNonPublic, showInherited }; + }); + + await expect(fields).not.toBeChecked(); + await expect(nonPublic).not.toBeChecked(); + await filter.fill("hiddenField"); + await expect(fields).toBeChecked(); + await expect(nonPublic).not.toBeChecked(); + await expect(tree.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: false, showInherited: false }); + + await nonPublic.check(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false }); + const saved = await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1")); + await filter.press("End"); + await filter.press("Backspace"); + await expect(filter).toHaveValue("hiddenFiel"); + await expect(fields).not.toBeChecked(); + await expect(nonPublic).toBeChecked(); + await expect(tree.getByRole("treeitem", { name: "hiddenField", exact: true })).toBeHidden(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false }); + + await filter.fill("hiddenField"); + await expect(fields).toBeChecked(); + await fields.uncheck(); + await expect(fields).not.toBeChecked(); + await filter.press("Escape"); + await expect(filter).toHaveValue(""); + await expect(fields).not.toBeChecked(); + await filter.press("Escape"); + await expect(dialog).toBeHidden(); + expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false }); + expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved); + + await page.evaluate(async () => { + const path = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ path); + await executeAction("navigate.fileStructure"); + }); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked(); + await expect(dialog.getByRole("checkbox", { name: "Show non-public" })).toBeChecked(); + expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved); +}); + test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => { await openFromTree(page, "build.gradle.kts"); await stubDesktop(page); diff --git a/src/features/search/__tests__/fileStructure.test.tsx b/src/features/search/__tests__/fileStructure.test.tsx index 6580b2634..d65355b40 100644 --- a/src/features/search/__tests__/fileStructure.test.tsx +++ b/src/features/search/__tests__/fileStructure.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import type { OutlineItem } from "@/platform/ipc"; @@ -16,10 +16,17 @@ const { FileStructureOverlay, useFileStructurePopup } = await import("../structu const { useOutline, useStructureOptions } = await import("../structure/store"); const { useTracking } = await import("../common/tracking"); -const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => ({ +const item = ( + name: string, + kind: OutlineItem["kind"], + line: number, + children: OutlineItem[] = [], + visibility?: OutlineItem["visibility"], +): OutlineItem => ({ name, detail: null, kind, + visibility, range: { start: { line, col: 0 }, end: { line: line + 1, col: 1 } }, selection_range: { start: { line, col: 4 }, end: { line, col: 4 + name.length } }, children, @@ -61,6 +68,19 @@ function openFunctions(narrowDown: boolean) { return input; } +beforeEach(() => { + useStructureOptions.setState({ + alphabetical: false, + narrowDown: true, + showFields: true, + showNonPublic: true, + showInherited: false, + sortByVisibility: false, + showOnlyWidgets: false, + }); + useOutline.setState({ inheritedSupported: false, inherited: null, flutter: null }); +}); + afterEach(() => { act(() => useFileStructurePopup.setState({ open: false })); useTracking.setState({ caret: null }); @@ -186,6 +206,133 @@ describe("File Structure popup", () => { expect(useFileStructurePopup.getState().open).toBe(false); }); + describe("temporary filters", () => { + const filteredItems = () => [ + item("Container", "class", 0, [ + item("hiddenField", "field", 2), + item("hiddenMethod", "method", 4, [], "private"), + item("visible", "method", 6), + ]), + ]; + + it("auto-enables only the applicable filter needed for a match, without persisting it", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const saved = localStorage.getItem("openidea.structure.options.v1"); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + expect(fields).not.toBeChecked(); + expect(nonPublic).not.toBeChecked(); + + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).toBeChecked(); + expect(nonPublic).not.toBeChecked(); + expect(screen.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false }); + expect(localStorage.getItem("openidea.structure.options.v1")).toBe(saved); + + fireEvent.keyDown(input, { key: "Escape" }); + expect(fields).not.toBeChecked(); + fireEvent.keyDown(input, { key: "Escape" }); + expect(useFileStructurePopup.getState().open).toBe(false); + act(() => useFileStructurePopup.setState({ open: true })); + expect(screen.getByLabelText("Filter symbols")).toHaveValue(""); + expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked(); + expect(useStructureOptions.getState().showFields).toBe(false); + }); + + it("tries unchecked filters one at a time until a match appears, then restores all on Escape", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + + fireEvent.change(input, { target: { value: "hiddenMethod" } }); + expect(fields).toBeChecked(); + expect(nonPublic).toBeChecked(); + expect(screen.getByRole("treeitem", { name: "hiddenMethod", selected: true })).toBeVisible(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false }); + + fireEvent.keyDown(input, { key: "Escape" }); + expect(input).toHaveValue(""); + expect(fields).not.toBeChecked(); + expect(nonPublic).not.toBeChecked(); + expect(screen.getByRole("treeitem", { name: "visible" })).toBeVisible(); + }); + + it("does not immediately re-enable a restored filter after backspace", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).toBeChecked(); + + fireEvent.change(input, { target: { value: "hiddenFiel" } }); + expect(fields).not.toBeChecked(); + expect(screen.getByText("No symbols")).toBeInTheDocument(); + expect(useStructureOptions.getState().showFields).toBe(false); + }); + + it("does not auto-enable filters when Narrow down on typing is off", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + act(() => useStructureOptions.setState({ narrowDown: false })); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).not.toBeChecked(); + expect(nonPublic).not.toBeChecked(); + expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false }); + }); + + it("restores an auto-enabled filter on backspace without reverting a manual checkbox change", () => { + useStructureOptions.setState({ showFields: false, showNonPublic: false }); + const input = open(filteredItems()); + const fields = screen.getByRole("checkbox", { name: "Show fields" }); + const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" }); + fireEvent.change(input, { target: { value: "hiddenField" } }); + expect(fields).toBeChecked(); + + fireEvent.click(nonPublic); + expect(useStructureOptions.getState().showNonPublic).toBe(true); + fireEvent.change(input, { target: { value: "hiddenFielX" } }); + expect(fields).toBeChecked(); // Same-length edits do not trigger IDEA's backspace restore. + fireEvent.change(input, { target: { value: "visible" } }); + expect(fields).not.toBeChecked(); + expect(nonPublic).toBeChecked(); + expect(screen.getByRole("treeitem", { name: "visible", selected: true })).toBeVisible(); + expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull(); + expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: true }); + + fireEvent.keyDown(input, { key: "Escape" }); + fireEvent.keyDown(input, { key: "Escape" }); + act(() => useFileStructurePopup.setState({ open: true })); + expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Show non-public" })).toBeChecked(); + }); + + it("temporarily enables Show inherited members and restores it when the query gets shorter", () => { + const input = open([item("Container", "class", 0, [item("own", "method", 2)])]); + const inherited = [{ item: item("inheritedNeedle", "method", 40), path: "/lib/Base.kt", owner: "Base" }]; + act(() => useOutline.setState({ inheritedSupported: true, inherited: new Map([["0:4", inherited]]) })); + const checkbox = screen.getByRole("checkbox", { name: "Show inherited members" }); + expect(checkbox).not.toBeChecked(); + + fireEvent.change(input, { target: { value: "inheritedNeedle" } }); + expect(checkbox).toBeChecked(); + expect(screen.getByRole("treeitem", { name: /^inheritedNeedle/, selected: true })).toBeVisible(); + expect(useStructureOptions.getState().showInherited).toBe(false); + + fireEvent.change(input, { target: { value: "own" } }); + expect(checkbox).not.toBeChecked(); + expect(screen.getByRole("treeitem", { name: "own", selected: true })).toBeVisible(); + expect(screen.queryByRole("treeitem", { name: /^inheritedNeedle/ })).toBeNull(); + expect(useStructureOptions.getState().showInherited).toBe(false); + }); + }); + it("offers Show inherited members only when the server knows type hierarchies", () => { open(); expect(screen.queryByLabelText("Show inherited members")).toBeNull(); diff --git a/src/features/search/structure/StructureView.tsx b/src/features/search/structure/StructureView.tsx index d8a660e72..9b9a8e823 100644 --- a/src/features/search/structure/StructureView.tsx +++ b/src/features/search/structure/StructureView.tsx @@ -33,7 +33,16 @@ import { widgetLetter, type OutlineNode, } from "./outline"; -import { useCollapsedStructure, useLiveOutline, useOutline, useOutlineNodes, useStructureOptions } from "./store"; +import { + getOutlineNodes, + releaseInheritedMembers, + requestInheritedMembers, + useCollapsedStructure, + useLiveOutline, + useOutline, + useOutlineNodes, + useStructureOptions, +} from "./store"; import styles from "./StructureView.module.css"; import { tx } from "@/platform/i18n"; @@ -301,8 +310,30 @@ export function FileStructureOverlay() { const POPUP_ROW = 22; +type TemporaryFilter = "showFields" | "showNonPublic" | "showInherited"; +interface AutoFilter { + key: TemporaryFilter; + queryLength: number; +} +interface PopupFilters { + showFields: boolean; + showNonPublic: boolean; + showInherited: boolean; +} +const TEMPORARY_FILTERS: readonly TemporaryFilter[] = ["showFields", "showNonPublic", "showInherited"]; + +function effectivePopupFilters(options: PopupFilters, autoFilters: readonly AutoFilter[]): PopupFilters { + const enabled = (key: TemporaryFilter) => autoFilters.some((entry) => entry.key === key); + return { + showFields: options.showFields || enabled("showFields"), + showNonPublic: options.showNonPublic || enabled("showNonPublic"), + showInherited: options.showInherited || enabled("showInherited"), + }; +} + function FileStructureDialog() { useLiveOutline(); + useEffect(() => () => releaseInheritedMembers(), []); const rowHeight = useRowHeight(POPUP_ROW); const path = useOutline((s) => s.path); const items = useOutline((s) => s.items); @@ -313,8 +344,13 @@ function FileStructureDialog() { const showNonPublic = useStructureOptions((s) => s.showNonPublic); const showInherited = useStructureOptions((s) => s.showInherited); const inheritedSupported = useOutline((s) => s.inheritedSupported); - const nodes = useOutlineNodes(); const [query, setQuery] = useState(""); + const [autoFilters, setAutoFilters] = useState([]); + const effectiveOptions = useMemo( + () => effectivePopupFilters({ showFields, showNonPublic, showInherited }, autoFilters), + [showFields, showNonPublic, showInherited, autoFilters], + ); + const nodes = useOutlineNodes(false, effectiveOptions); const [showOptions, setShowOptions] = useState(false); // IDEA opens the popup fully expanded. const [collapsed, setCollapsed] = useState>(() => new Set()); @@ -351,7 +387,10 @@ function FileStructureDialog() { else tree.current?.clearSelection(); }, [query, hasQuery, caretKey, filter.preferred, filter.nodes]); - const close = () => useFileStructurePopup.setState({ open: false }); + const close = () => { + releaseInheritedMembers(); + useFileStructurePopup.setState({ open: false }); + }; const choose = (node: OutlineNode | undefined) => { if (!node || !path) return; close(); @@ -365,6 +404,53 @@ function FileStructureDialog() { return next; }); + const availableFilters: Record = { + showFields: hasFields(items ?? []), + showNonPublic: hasVisibility(items ?? []), + showInherited: inheritedSupported, + }; + const changeQuery = (nextQuery: string) => { + setQuery(nextQuery); + setCollapsed(new Set()); + let nextAuto = autoFilters; + if (nextQuery.length < query.length) { + // IDEA restores every auto-click whose query was at least this long, newest first. + nextAuto = autoFilters.filter((entry) => entry.queryLength < nextQuery.length); + if (nextAuto.length !== autoFilters.length) { + if ( + autoFilters.some((entry) => entry.key === "showInherited") && + !nextAuto.some((entry) => entry.key === "showInherited") + ) + releaseInheritedMembers(); + setAutoFilters(nextAuto); + return; + } + } + if (!nextQuery.trim() || !narrowDown) { + setAutoFilters(nextAuto); + return; + } + const persisted = useStructureOptions.getState(); + let options = effectivePopupFilters(persisted, nextAuto); + const hasMatch = () => filterOutline(getOutlineNodes(false, options), nextQuery, narrowDown).best !== null; + if (!hasMatch()) { + for (const key of TEMPORARY_FILTERS) { + if (options[key] || !availableFilters[key]) continue; + nextAuto = [{ key, queryLength: nextQuery.length }, ...nextAuto]; + options = effectivePopupFilters(persisted, nextAuto); + if (key === "showInherited") requestInheritedMembers(); + if (hasMatch()) break; + } + } + setAutoFilters(nextAuto); + }; + const changeFilter = (key: TemporaryFilter, value: boolean) => { + // A manual edit takes ownership of the checkbox; later backspaces must not undo it. + setAutoFilters((entries) => entries.filter((entry) => entry.key !== key)); + if (key === "showInherited") releaseInheritedMembers(); + useStructureOptions.setState({ [key]: value }); + }; + const onKeyDown = (e: KeyboardEvent) => { const lead = tree.current?.leadKey() ?? null; const node = lead ? byKey.get(lead) : undefined; @@ -377,7 +463,7 @@ function FileStructureDialog() { // The first Esc clears the filter, the next one closes the popup. if (!query) return; e.stopPropagation(); - setQuery(""); + changeQuery(""); break; case "ArrowDown": case "ArrowUp": { @@ -437,22 +523,22 @@ function FileStructureDialog() { {(hasFields(items ?? []) || !showFields) && ( useStructureOptions.setState({ showFields: v })} + checked={effectiveOptions.showFields} + onChange={(v) => changeFilter("showFields", v)} /> )} {hasVisibility(items ?? []) && ( useStructureOptions.setState({ showNonPublic: v })} + checked={effectiveOptions.showNonPublic} + onChange={(v) => changeFilter("showNonPublic", v)} /> )} {inheritedSupported && ( useStructureOptions.setState({ showInherited: v })} + checked={effectiveOptions.showInherited} + onChange={(v) => changeFilter("showInherited", v)} /> )}
@@ -496,10 +582,7 @@ function FileStructureDialog() { aria-label={tx("Filter symbols")} spellCheck={false} autoComplete="off" - onChange={(e) => { - setQuery(e.target.value); - setCollapsed(new Set()); - }} + onChange={(e) => changeQuery(e.target.value)} onKeyDown={onKeyDown} /> {hasQuery && !narrowDown && !filter.best && filter.nodes.length > 0 && ( diff --git a/src/features/search/structure/store.ts b/src/features/search/structure/store.ts index 44a7a93a7..62a9d56b8 100644 --- a/src/features/search/structure/store.ts +++ b/src/features/search/structure/store.ts @@ -47,6 +47,8 @@ let consumers = 0; let stop: (() => void) | null = null; let seq = 0; let flutterSeq = 0; +let reloadOutline: (() => void) | null = null; +let inheritedRequest: { doc: number; path: string } | null = null; /** A backend document id for `path` while `fn` runs (open editors are reused). */ async function withDoc(path: string, fn: (doc: number) => Promise): Promise { @@ -99,16 +101,31 @@ async function loadInherited(doc: number, path: string, items: readonly OutlineI ? true : await probeHierarchy(doc, types); if (my !== seq) return; - if (!supported || !useStructureOptions.getState().showInherited) { + const requested = inheritedRequest?.doc === doc && inheritedRequest.path === path; + if (!supported || !(useStructureOptions.getState().showInherited || requested)) { + if (requested) inheritedRequest = null; useOutline.setState({ inheritedSupported: supported, inherited: null }); return; } + useOutline.setState({ inheritedSupported: true }); const deps = inheritedDeps(path, doc, language === "python"); const entries = await Promise.all( types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const), ); - if (my === seq) - useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) }); + if (my === seq) useOutline.setState({ inherited: new Map(entries.filter(([, m]) => m.length)) }); +} + +/** Loads inherited members for a temporary popup filter without changing persisted options. */ +export function requestInheritedMembers() { + const { doc, path, inherited } = useOutline.getState(); + if (doc === null || path === null) return; + inheritedRequest = { doc, path }; + if (inherited === null) reloadOutline?.(); +} + +/** Ends a popup's temporary inherited-member request when its filter is restored or it closes. */ +export function releaseInheritedMembers() { + inheritedRequest = null; } async function loadFlutter(doc: number, language: string) { @@ -153,6 +170,7 @@ function start(): () => void { if (!ctx) { seq++; flutterSeq++; + inheritedRequest = null; useOutline.setState({ path: null, doc: null, @@ -167,6 +185,7 @@ function start(): () => void { } void load(ctx.doc, ctx.path, ctx.language); }; + reloadOutline = reloadNow; reloadNow(); const unsubActive = useEditorRegistry.subscribe((s, prev) => { if (s.active?.ctx.doc !== prev.active?.ctx.doc || s.active?.ctx.path !== prev.active?.ctx.path) reloadNow(); @@ -188,6 +207,8 @@ function start(): () => void { return () => { clearTimeout(timer); flutterSeq++; + if (reloadOutline === reloadNow) reloadOutline = null; + inheritedRequest = null; unsubFlutter(); unsubActive(); unsubInherited(); @@ -268,6 +289,8 @@ const outlinePreferences = (s: StructureOptions) => ({ showOnlyWidgets: s.showOnlyWidgets, }); +type OutlinePreferences = ReturnType; + function outlineNodes( items: OutlineState["items"], flutter: OutlineState["flutter"], @@ -285,12 +308,20 @@ function outlineNodes( return flutter && options.showOnlyWidgets ? onlyWidgets(nodes) : nodes; } -export function useOutlineNodes(widgets = false) { +/** Snapshot builder for query-event transitions, which cannot call hooks. */ +export function getOutlineNodes(widgets = false, overrides?: Partial) { + const { items, flutter, inheritedSupported, inherited } = useOutline.getState(); + const options = { ...outlinePreferences(useStructureOptions.getState()), ...overrides }; + return outlineNodes(items, widgets ? flutter : null, inheritedSupported ? inherited : null, options); +} + +export function useOutlineNodes(widgets = false, overrides?: Partial) { const items = useOutline((s) => s.items); const flutter = useOutline((s) => (widgets ? s.flutter : null)); const inherited = useOutline((s) => (s.inheritedSupported ? s.inherited : null)); const options = useStructureOptions(useShallow(outlinePreferences)); - return useMemo(() => outlineNodes(items, flutter, inherited, options), [items, flutter, inherited, options]); + const effective = useMemo(() => (overrides ? { ...options, ...overrides } : options), [options, overrides]); + return useMemo(() => outlineNodes(items, flutter, inherited, effective), [items, flutter, inherited, effective]); } function collapseStructure() { From 2b7a18ffd7f2fce5c21107143ff9113b78915f74 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 30 Nov 2026 20:04:14 +0800 Subject: [PATCH 37/66] fix(search): start Find in Files from the selection in its preview (#7033) Find in Files and Search Everywhere took the selection only from the active editor tab, so text selected in the Find in Files preview (or another focused editor, such as a diff pane) was ignored when the action ran again. The focused editor's selection now comes first, then the active editor's. Fixes #6992 --- .../search/__tests__/selectionText.test.ts | 30 +++++++++++++++++++ src/features/search/index.ts | 10 +++++-- 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 src/features/search/__tests__/selectionText.test.ts diff --git a/src/features/search/__tests__/selectionText.test.ts b/src/features/search/__tests__/selectionText.test.ts new file mode 100644 index 000000000..2384e1096 --- /dev/null +++ b/src/features/search/__tests__/selectionText.test.ts @@ -0,0 +1,30 @@ +import { afterEach, expect, it } from "vitest"; +import { EditorSelection, EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { _setActiveEditor, type TextEditorHandle } from "@/editor/api"; +import { editorSelectionText } from "../index"; + +const views: EditorView[] = []; +const view = (doc: string, from: number, to: number) => { + const v = new EditorView({ + state: EditorState.create({ doc, selection: EditorSelection.single(from, to) }), + parent: document.body, + }); + views.push(v); + return v; +}; +afterEach(() => { + _setActiveEditor(null); + views.splice(0).forEach((v) => v.destroy()); +}); + +it("takes the selection of the focused editor, such as the Find in Files preview, over the active one", () => { + const main = view("val first = 1", 4, 9); + _setActiveEditor({ view: main } as unknown as TextEditorHandle); + expect(editorSelectionText()).toBe("first"); + const preview = view("fun second() {}", 4, 10); + preview.contentDOM.focus(); + expect(editorSelectionText()).toBe("second"); + preview.contentDOM.blur(); + expect(editorSelectionText()).toBe("first"); +}); diff --git a/src/features/search/index.ts b/src/features/search/index.ts index 4d615d234..a1b378fc4 100644 --- a/src/features/search/index.ts +++ b/src/features/search/index.ts @@ -3,6 +3,7 @@ * Recent Files / Recent Locations, Find / Replace in Files + the Find tool * window, the Structure tool window + File Structure popup, and bookmarks. */ +import { EditorView } from "@codemirror/view"; import { lazyComponent, lazyWhen } from "@/ui"; import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api"; import { executeAction, registerActions } from "@/platform/actions"; @@ -82,8 +83,13 @@ async function removeMissingBookmarks(removed: readonly string[]) { } /** Single-line editor selection, used to prefill search fields. */ -function editorSelectionText(): string | null { - const view = activeEditor()?.view; +/** + * The single-line selection a search starts from: the focused editor's (a Find in Files preview, + * a diff pane), else the active editor's, as IDEA reads it from the editor in the action's context. + */ +export function editorSelectionText(): string | null { + const focused = document.activeElement?.closest(".cm-editor"); + const view = (focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null) ?? activeEditor()?.view; if (!view) return null; const { from, to } = view.state.selection.main; if (from === to || to - from > 200) return null; From baab92c804f6f8b41edd857d5f1037cde7474eff Mon Sep 17 00:00:00 2001 From: Muu Date: Mon, 30 Nov 2026 20:08:11 +0800 Subject: [PATCH 38/66] feat(vcs): create patches from selected historical files (#6981) Git Log and File History changed files get Create Patch and Copy as Patch to Clipboard, in the toolbar and the context menu. Only the selected repository-relative paths are exported, as path-filtered revision diffs with Git's empty tree on the missing side of additions and deletions and both names for renames. The existing patch dialog, base directory defaults, reverse option and clipboard flow are reused; empty, malformed, no-op, mixed-repository and external-repository selections are disabled. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- e2e/fileHistoryActions.spec.ts | 113 +++++++++++++++++ src/features/vcs/__tests__/historyOps.test.ts | 7 ++ src/features/vcs/__tests__/logPanes.test.tsx | 83 ++++++++++++ src/features/vcs/__tests__/logPatch.test.ts | 118 ++++++++++++++++++ src/features/vcs/log/CommitDetails.tsx | 30 +++++ src/features/vcs/logChanges.ts | 62 ++++++++- src/features/vcs/logPaneActions.ts | 24 ++++ src/features/vcs/patches.tsx | 54 +++++++- src/platform/keymaps/ideaParity.test.ts | 2 + src/platform/keymaps/intellij-macos.ts | 2 + src/platform/keymaps/intellij-windows.ts | 2 + src/platform/keymaps/vscode-macos.ts | 2 + 12 files changed, 493 insertions(+), 6 deletions(-) create mode 100644 src/features/vcs/__tests__/logPatch.test.ts diff --git a/e2e/fileHistoryActions.spec.ts b/e2e/fileHistoryActions.spec.ts index e9bc56660..bcf3374c7 100644 --- a/e2e/fileHistoryActions.spec.ts +++ b/e2e/fileHistoryActions.spec.ts @@ -99,3 +99,116 @@ test("File History opens its revision and compares only that file with the worki .poll(async () => ipcCalls(page, "vcs_file_at")) .toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION }); }); + +test("File History creates and copies a patch for only the selected changed file", async ({ workbench: page }) => { + const parent = "b".repeat(40); + const selectedPath = "src/selected.ts"; + const otherPath = "src/other.ts"; + const patch = `diff --git a/${selectedPath} b/${selectedPath}\n`; + await stubDesktop(page); + await page.evaluate( + async ({ root, path, revision, parent, selectedPath, otherPath }) => { + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }]; + h.vcs_branch_info = () => ({ + head: "main", + headCommit: revision, + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }); + h.vcs_branches = () => []; + h.vcs_status = () => []; + h.vcs_log = ({ query }) => + (query as { path?: string }).path + ? [ + { + id: revision, + shortId: revision.slice(0, 8), + parents: [parent], + refs: [], + author: "Author", + email: "author@example.com", + timeMs: 1, + summary: "Export selected history file", + message: "Export selected history file", + historyPath: selectedPath, + }, + ] + : []; + h.vcs_log_refs = () => ({}); + h.vcs_log_users = () => ["Author "]; + h.vcs_log_details_batch = () => []; + h.vcs_commit_files = () => [ + { path: selectedPath, kind: "modified", oldPath: null }, + { path: otherPath, kind: "modified", oldPath: null }, + ]; + h.vcs_create_patch = ({ source }) => { + const paths = (source as { paths?: string[] }).paths ?? []; + return paths.map((entry) => `diff --git a/${entry} b/${entry}\n`).join(""); + }; + h.vcs_write_patch = () => null; + h.clipboard_write_text = () => null; + + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + useProject.setState((state: { settings: Record }) => ({ + settings: { + ...state.settings, + vcs: { confirmation: { onPatchCreated: "no" } }, + }, + })); + const storeModule = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ storeModule); + useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true, statusLoaded: true }); + const contextModule = "/src/platform/context.ts"; + const { setContext } = await import(/* @vite-ignore */ contextModule); + setContext("vcsAvailable", true); + const actionsModule = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + await executeAction("vcs.showHistory", { path }); + }, + { root: ROOT, path: `${ROOT}/${selectedPath}`, revision: REVISION, parent, selectedPath, otherPath }, + ); + + const row = page.getByRole("listbox", { name: "Commits" }).getByRole("option", { + name: /Export selected history file/, + }); + await expect(row).toBeVisible(); + await row.click(); + const tree = page.getByRole("tree", { name: "Changed files" }); + const selected = tree.getByText("selected.ts", { exact: true }); + await expect(selected).toBeVisible(); + await expect(tree.getByText("other.ts", { exact: true })).toBeVisible(); + const toolbar = page.getByRole("toolbar", { name: "Changed files" }); + const create = toolbar.getByRole("button", { name: "Create Patch…", exact: true }); + await expect(create).toBeDisabled(); + await selected.click(); + await expect(create).toBeEnabled(); + await create.click(); + + const dialog = page.getByRole("dialog", { name: "Create Patch", exact: true }); + await expect(dialog.getByRole("textbox", { name: "Base directory" })).toHaveValue(ROOT); + const destination = await dialog.getByRole("textbox", { name: "Patch file" }).inputValue(); + expect(destination).toBe(`${ROOT}/Export_selected_history_file.patch`); + await dialog.getByRole("button", { name: "Create", exact: true }).click(); + const source = { from: "revisions", before: parent, after: REVISION, paths: [selectedPath] }; + await expect.poll(() => ipcCalls(page, "vcs_create_patch")).toEqual([{ repo: ROOT, base: ROOT, source }]); + await expect + .poll(() => ipcCalls(page, "vcs_write_patch")) + .toEqual([expect.objectContaining({ path: destination, patch })]); + + await selected.click({ button: "right" }); + await page + .getByRole("menu", { name: "Context menu" }) + .getByRole("menuitem", { name: "Copy as Patch to Clipboard", exact: true }) + .click(); + await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: patch }]); + await expect + .poll(() => ipcCalls(page, "vcs_create_patch")) + .toEqual([ + { repo: ROOT, base: ROOT, source }, + { repo: ROOT, base: null, source }, + ]); +}); diff --git a/src/features/vcs/__tests__/historyOps.test.ts b/src/features/vcs/__tests__/historyOps.test.ts index 2998cced9..8f7d395d8 100644 --- a/src/features/vcs/__tests__/historyOps.test.ts +++ b/src/features/vcs/__tests__/historyOps.test.ts @@ -308,6 +308,13 @@ describe("Git Log commit actions", () => { "Fix_crash_on_start.patch", ); expect(suggestedPatchName({ kind: "commits", commits: [commit("a"), commit("b")] }, "x")).toBe("2_commits.patch"); + expect( + suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("Fix: historical file!")] }, "x"), + ).toBe("Fix_historical_file.patch"); + expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [commit("a"), commit("b")] }, "x")).toBe( + "2_commits.patch", + ); + expect(suggestedPatchName({ kind: "logChanges", changes: [], commits: [] }, "Changes")).toBe("0_files.patch"); expect(suggestedPatchName({ kind: "changes", files: [] }, "///")).toBe("changes.patch"); }); }); diff --git a/src/features/vcs/__tests__/logPanes.test.tsx b/src/features/vcs/__tests__/logPanes.test.tsx index a0fede6be..2567d4cf8 100644 --- a/src/features/vcs/__tests__/logPanes.test.tsx +++ b/src/features/vcs/__tests__/logPanes.test.tsx @@ -42,10 +42,12 @@ import { graphOptionsMenu } from "../log/FilterBar"; import { EMPTY_TREE, assignLineStats, + canCreatePatchFromLogChanges, filesUnder, filterPatch, flatFileNodes, lineStatRanges, + logPatchRanges, toLogChanges, useLogChanges, } from "../logChanges"; @@ -122,6 +124,78 @@ describe("changed files model", () => { expect(rootFile!.statsFrom).toBe(EMPTY_TREE); }); + it("builds path-filtered historical patch ranges, including empty trees and both rename paths", () => { + const previous = useVcs.getState(); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] }); + try { + const older: Commit = { ...commit, id: "a".repeat(40), parents: ["9".repeat(40)], timeMs: 1 }; + const newer: Commit = { ...commit, id: "b".repeat(40), parents: [older.id], timeMs: 2 }; + const changes = [ + ...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"), + ...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"), + ...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"), + ...toLogChanges([{ path: "deleted.ts", kind: "deleted", oldPath: null }], newer, "/repo"), + ]; + const paths = ["edited.ts", "new.ts", "old.ts"]; + expect(canCreatePatchFromLogChanges(changes)).toBe(true); + expect(logPatchRanges(changes)).toEqual([ + { repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, + { repo: "/repo", before: older.id, after: newer.id, paths }, + { repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["deleted.ts"] }, + ]); + expect(logPatchRanges(changes, true)).toEqual([ + { repo: "/repo", before: older.id, after: EMPTY_TREE, paths: ["added.ts"] }, + { repo: "/repo", before: newer.id, after: older.id, paths }, + { repo: "/repo", before: EMPTY_TREE, after: older.id, paths: ["deleted.ts"] }, + ]); + + const other = { ...changes[1]!, repo: "/other" }; + useVcs.setState({ roots: ["/repo", "/other"] }); + expect(canCreatePatchFromLogChanges([changes[0]!, other])).toBe(false); + expect(logPatchRanges([changes[0]!, other])).toEqual([]); + const ambiguous = { ...changes[0]!, repo: null }; + expect(canCreatePatchFromLogChanges([ambiguous])).toBe(false); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, readOnly: true }])).toBe(true); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, repo: "/external", readOnly: true }])).toBe(false); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, oldPath: 42 as unknown as string }])).toBe(false); + expect(canCreatePatchFromLogChanges([{ ...changes[0]!, before: newer.id, after: newer.id }])).toBe(false); + expect(canCreatePatchFromLogChanges([])).toBe(false); + } finally { + useVcs.setState(previous); + } + }); + + it("enables changed-file patch actions and menu rows only for an applicable selection", () => { + const previous = useVcs.getState(); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo", "/other"] }); + const files = toLogChanges( + [ + { path: "a.ts", kind: "modified", oldPath: null }, + { path: "b.ts", kind: "modified", oldPath: null }, + ], + commit, + "/repo", + ); + const dispose = registerLogPaneActions(); + try { + for (const id of ["vcs.log.changes.createPatch", "vcs.log.changes.copyPatch"]) { + const action = getAction(id)!; + expect(action.enabled!({ ctx: {}, arg: [] })).toBe(false); + expect(action.enabled!({ ctx: {}, arg: files })).toBe(true); + expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/other" }] })).toBe(true); + expect(action.enabled!({ ctx: {}, arg: [{ ...files[0]!, repo: "/external" }] })).toBe(false); + const item = (changes: ReturnType) => + changesMenu(changes).find((entry) => "action" in entry && entry.action === id); + expect(item(files)).toMatchObject({ arg: files, disabled: false }); + expect(item([])).toMatchObject({ disabled: true }); + expect(item([{ ...files[0]!, repo: "/external" }])).toMatchObject({ disabled: true }); + } + } finally { + dispose(); + useVcs.setState(previous); + } + }); + it("asks for one numstat per revision pair and matches a rename by either name", () => { const files = toLogChanges( [ @@ -265,6 +339,8 @@ describe("rename label", () => { describe("changed files pane", () => { it("shows the files flat or by directory and shares the selection with its actions", async () => { + const previous = useVcs.getState(); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] }); vcsCommitFiles.mockResolvedValue({ status: "ok", data: [ @@ -275,10 +351,16 @@ describe("changed files pane", () => { useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id] }); const { unmount } = render(); expect(await screen.findByText("src")).toBeInTheDocument(); + const createPatch = screen.getByRole("button", { name: "Create Patch…" }); + const copyPatch = screen.getByRole("button", { name: "Copy as Patch to Clipboard" }); + expect(createPatch).toBeDisabled(); + expect(copyPatch).toBeDisabled(); fireEvent.mouseDown(screen.getByText("a.ts")); expect(useLogChanges.getState().selected.map((c) => c.path)).toEqual(["src/a.ts"]); expect(useLogChanges.getState().commits).toEqual([commit]); expect(screen.getByRole("button", { name: "Show Diff" })).toBeEnabled(); + expect(createPatch).toBeEnabled(); + expect(copyPatch).toBeEnabled(); useLogOptions.setState({ groupByDirectory: false }); expect(await screen.findByText("b.ts")).toBeInTheDocument(); @@ -286,6 +368,7 @@ describe("changed files pane", () => { expect(screen.getAllByText("src")).toHaveLength(2); unmount(); expect(useLogChanges.getState().selected).toEqual([]); + useVcs.setState(previous); }); it("shows added and deleted lines when the log option is on", async () => { diff --git a/src/features/vcs/__tests__/logPatch.test.ts b/src/features/vcs/__tests__/logPatch.test.ts new file mode 100644 index 000000000..c160ef07a --- /dev/null +++ b/src/features/vcs/__tests__/logPatch.test.ts @@ -0,0 +1,118 @@ +import type { Commit, PatchSource } from "@/bindings"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + createPatch: vi.fn(), + writeClipboardText: vi.fn(), + openDialog: vi.fn(), + notify: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + commands: { + ...real.commands, + vcsCreatePatch: (repo: string | null, source: PatchSource, base: string | null) => + mocks.createPatch(repo, source, base), + }, + }; +}); +vi.mock("@/platform/clipboard", async (importOriginal) => ({ + ...(await importOriginal()), + writeClipboardText: mocks.writeClipboardText, +})); +vi.mock("../dialogs", async (importOriginal) => ({ + ...(await importOriginal()), + openDialog: mocks.openDialog, +})); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + notifications: () => ({ notify: mocks.notify }), +})); + +import { EMPTY_TREE, toLogChanges } from "../logChanges"; +import { copyLogChangesAsPatch } from "../patches"; +import { useVcs } from "../store"; + +const commit = (id: string, parents: string[], timeMs: number): Commit => ({ + id: id.repeat(40), + shortId: id.repeat(8), + parents, + author: "A", + email: "a@example.com", + timeMs, + summary: `Commit ${id}`, + message: `Commit ${id}`, + refs: [], +}); + +const originalVcs = useVcs.getState(); + +beforeEach(() => { + mocks.createPatch.mockReset(); + mocks.writeClipboardText.mockReset(); + mocks.openDialog.mockReset(); + mocks.notify.mockReset(); + mocks.writeClipboardText.mockResolvedValue(undefined); + useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"] }); +}); + +afterEach(() => useVcs.setState(originalVcs)); + +describe("Git Log changed-file patches", () => { + it("copies exactly the selected revision/path ranges, with both names of a rename", async () => { + const older = commit("a", ["9".repeat(40)], 1); + const newer = commit("b", [older.id], 2); + const changes = [ + ...toLogChanges([{ path: "added.ts", kind: "added", oldPath: null }], older, "/repo"), + ...toLogChanges([{ path: "edited.ts", kind: "modified", oldPath: null }], newer, "/repo"), + ...toLogChanges([{ path: "new.ts", kind: "renamed", oldPath: "old.ts" }], newer, "/repo"), + ]; + mocks.createPatch.mockImplementation(async (_repo: string, source: PatchSource) => ({ + status: "ok" as const, + data: source.from === "revisions" ? `patch ${source.before} ${source.after} ${source.paths.join(",")}\n` : "", + })); + await copyLogChangesAsPatch(changes); + + expect(mocks.createPatch.mock.calls).toEqual([ + ["/repo", { from: "revisions", before: EMPTY_TREE, after: older.id, paths: ["added.ts"] }, null], + [ + "/repo", + { + from: "revisions", + before: older.id, + after: newer.id, + paths: ["edited.ts", "new.ts", "old.ts"], + }, + null, + ], + ]); + expect(mocks.writeClipboardText).toHaveBeenCalledExactlyOnceWith( + `patch ${EMPTY_TREE} ${older.id} added.ts\npatch ${older.id} ${newer.id} edited.ts,new.ts,old.ts\n`, + ); + expect(mocks.openDialog).not.toHaveBeenCalled(); + }); + + it("does not touch the clipboard for empty, mixed-repository or external read-only selections", async () => { + const c = commit("c", ["9".repeat(40)], 1); + const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo"); + await copyLogChangesAsPatch([]); + await copyLogChangesAsPatch([files[0]!, { ...files[0]!, repo: "/other" }]); + await copyLogChangesAsPatch([{ ...files[0]!, repo: "/external", readOnly: true }]); + expect(mocks.createPatch).not.toHaveBeenCalled(); + expect(mocks.writeClipboardText).not.toHaveBeenCalled(); + }); + + it("leaves the clipboard untouched when Git returns an empty patch", async () => { + const c = commit("c", ["9".repeat(40)], 1); + const files = toLogChanges([{ path: "a.ts", kind: "modified", oldPath: null }], c, "/repo"); + mocks.createPatch.mockResolvedValue({ status: "ok", data: "" }); + await copyLogChangesAsPatch(files); + expect(mocks.writeClipboardText).not.toHaveBeenCalled(); + expect(mocks.notify).toHaveBeenCalledWith( + expect.objectContaining({ group: "vcs", level: "info", title: "No changes to create a patch from" }), + ); + }); +}); diff --git a/src/features/vcs/log/CommitDetails.tsx b/src/features/vcs/log/CommitDetails.tsx index 3e4c7910d..11bd04ea8 100644 --- a/src/features/vcs/log/CommitDetails.tsx +++ b/src/features/vcs/log/CommitDetails.tsx @@ -40,6 +40,7 @@ import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree"; import styles from "../GitLog.module.css"; import { canApplySelectedChanges, + canCreatePatchFromLogChanges, canOpenRepositoryVersion, absolutePath, changesArg, @@ -412,6 +413,22 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi actionArg={chosenChanges} disabled={!chosenChanges.length} /> + + { return assignLineStats(files, loaded); } +/** One repository's selected historical files between the same two revisions. */ +export interface LogPatchRange { + repo: string; + before: string; + after: string; + paths: string[]; +} + +/** + * The repository a historical patch can safely use. A missing row repository is + * unambiguous only when the project has one root; otherwise callers must retain it. + */ +export function logPatchRepository(changes: readonly LogChange[]): string | null { + if (!changes.length) return null; + const state = useVcs.getState(); + const fallback = state.roots.length === 1 ? state.roots[0]! : state.roots.length ? null : (state.repo ?? state.root); + const repo = changes[0]!.repo ?? fallback; + if (!repo || changes.some((change) => (change.repo ?? fallback) !== repo)) return null; + return state.roots.length && !state.roots.includes(repo) ? null : repo; +} + +/** Create Patch is an export: empty, malformed, read-only external and mixed-repository selections cannot use it. */ +export function canCreatePatchFromLogChanges(changes: readonly LogChange[]): boolean { + if (!changes.length || !logPatchRepository(changes)) return false; + return ( + changes.every( + (change) => + typeof change.path === "string" && + change.path.length > 0 && + (change.oldPath === null || (typeof change.oldPath === "string" && change.oldPath.length > 0)) && + (change.before === null || (typeof change.before === "string" && change.before.length > 0)) && + (change.after === null || (typeof change.after === "string" && change.after.length > 0)) && + (change.before !== null || change.after !== null), + ) && changes.some((change) => (change.before ?? EMPTY_TREE) !== (change.after ?? EMPTY_TREE)) + ); +} + +/** + * Path-filtered revision diffs for exactly the selected rows. Added and deleted + * files use Git's empty tree on their missing side; renames include both names. + * Reversing swaps each range's endpoints, including the empty tree. + */ +export function logPatchRanges(changes: readonly LogChange[], reverse = false): LogPatchRange[] { + if (!canCreatePatchFromLogChanges(changes)) return []; + const repo = logPatchRepository(changes)!; + const ranges = new Map(); + for (const change of changes) { + const before = (reverse ? change.after : change.before) ?? EMPTY_TREE; + const after = (reverse ? change.before : change.after) ?? EMPTY_TREE; + if (before === after) continue; + const key = `${before}\0${after}`; + let range = ranges.get(key); + if (!range) ranges.set(key, (range = { repo, before, after, paths: [] })); + for (const path of change.oldPath ? [change.path, change.oldPath] : [change.path]) { + if (path && !range.paths.includes(path)) range.paths.push(path); + } + } + return [...ranges.values()]; +} + /** Files without directory grouping: by name, each node's path shown next to it. */ export function flatFileNodes(files: readonly F[], relPath: (f: F) => string): FileTreeNode[] { return files diff --git a/src/features/vcs/logPaneActions.ts b/src/features/vcs/logPaneActions.ts index 93e022245..312f8f8fc 100644 --- a/src/features/vcs/logPaneActions.ts +++ b/src/features/vcs/logPaneActions.ts @@ -18,6 +18,7 @@ import { import { isFavoriteBranch } from "./branches"; import { applySelectedChanges, + canCreatePatchFromLogChanges, canOpenRepositoryVersion, changesArg, compareChangesWithLocal, @@ -32,6 +33,7 @@ import { logOptions } from "./logOptions"; import { goToRef, selectedCommits, toggleCherryHighlight, updateLogOptions, useGitLog } from "./logStore"; import { commitKey, commitRepo } from "./multiRoot"; import { dropSelectedChanges, extractSelectedChanges } from "./rebase"; +import { copyLogChangesAsPatch, showCreatePatchForLogChanges } from "./patches"; import { openRevisionFile } from "./revisionInput"; import { currentRepoRoot, focusRepo } from "./store"; import { showCompareBranches, type BranchComparisonTarget, type BranchComparisonData } from "./CompareBranches"; @@ -301,6 +303,28 @@ export function registerLogPaneActions(): () => void { } }, }, + { + id: "vcs.log.changes.createPatch", + title: "Create Patch…", + category: "Git Log", + icon: "patch", + when: LOG, + hidden: true, + keyWhen: "vcsLogChangesFocus", + enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)), + run: ({ arg }) => showCreatePatchForLogChanges(changesArg(arg), useLogChanges.getState().commits), + }, + { + id: "vcs.log.changes.copyPatch", + title: "Copy as Patch to Clipboard", + category: "Git Log", + icon: "copy", + when: LOG, + hidden: true, + keyWhen: "vcsLogChangesFocus", + enabled: ({ arg }) => canCreatePatchFromLogChanges(changesArg(arg)), + run: ({ arg }) => copyLogChangesAsPatch(changesArg(arg)), + }, { id: "vcs.log.changes.getFromRevision", title: "Get from Revision", diff --git a/src/features/vcs/patches.tsx b/src/features/vcs/patches.tsx index 19262abd9..a72b0d2cd 100644 --- a/src/features/vcs/patches.tsx +++ b/src/features/vcs/patches.tsx @@ -1,5 +1,6 @@ import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard"; import { commitRepo } from "./multiRoot"; +import { canCreatePatchFromLogChanges, logPatchRanges, logPatchRepository, type LogChange } from "./logChanges"; /** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import type { @@ -68,15 +69,20 @@ import { useDiffSource } from "./diffSource"; export type PatchOrigin = | { kind: "changes"; files: FileStatus[]; staging?: readonly StagingPatchEntry[] } | { kind: "commits"; commits: Commit[] } + | { kind: "logChanges"; changes: LogChange[]; commits: Commit[] } | { kind: "shelf"; entry: ShelvedChangeList; path?: string }; /** File name IDEA suggests: the change list or commit subject, sanitised. */ export function suggestedPatchName(origin: PatchOrigin, listName: string): string { const base = - origin.kind === "commits" + origin.kind === "commits" || origin.kind === "logChanges" ? origin.commits.length === 1 ? origin.commits[0]!.summary - : `${origin.commits.length} commits` + : origin.commits.length > 1 + ? `${origin.commits.length} commits` + : origin.kind === "logChanges" + ? `${origin.changes.length} files` + : "0 commits" : origin.kind === "shelf" ? origin.entry.name : listName; @@ -160,6 +166,38 @@ export function showCreatePatchForCommits(commits: Commit[]) { openDialog((close) => ); } +async function createLogChangesPatch(changes: readonly LogChange[], reverse: boolean, base: string | null) { + const patches = await Promise.all( + logPatchRanges(changes, reverse).map(({ repo, before, after, paths }) => + call(commands.vcsCreatePatch(repo, { from: "revisions", before, after, paths }, base)), + ), + ); + return patches.join(""); +} + +export function showCreatePatchForLogChanges(changes: LogChange[], commits: Commit[]) { + if (!canCreatePatchFromLogChanges(changes)) return; + openDialog((close) => ); +} + +/** Copy the selected historical files as a patch directly, without the Create Patch dialog. */ +export async function copyLogChangesAsPatch(changes: readonly LogChange[]) { + if (!canCreatePatchFromLogChanges(changes)) return; + await runOp( + tx("Create patch"), + async () => { + const patch = await createLogChangesPatch(changes, false, null); + if (!patch) { + noPatchChanges(); + return false; + } + await writeClipboardText(patch); + return true; + }, + { success: (copied) => (copied ? "Patch copied to the clipboard" : ""), refresh: false }, + ); +} + export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string) { openDialog((close) => ); } @@ -220,7 +258,11 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose: const root = useVcs((s) => s.root) ?? ""; const roots = useVcs((s) => s.roots); const [repo] = useState(() => - origin.kind === "commits" ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) : currentRepoRoot(), + origin.kind === "commits" + ? (commitRepo(origin.commits[0]!) ?? currentRepoRoot()) + : origin.kind === "logChanges" + ? (logPatchRepository(origin.changes) ?? currentRepoRoot()) + : currentRepoRoot(), ); const listName = useChangelists((s) => activeList(s.state).name); const [selected, setSelected] = useState( @@ -254,7 +296,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose: setPending(true); setError(""); const source: PatchSource | null = - origin.kind === "shelf" + origin.kind === "shelf" || origin.kind === "logChanges" ? null : origin.kind === "changes" ? localPatchSource(origin, selected, reverse) @@ -273,7 +315,9 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose: ? await call( commands.vcsShelfPatch(origin.entry.id, origin.path ?? null, baseInput === null ? null : directory), ) - : await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory)); + : origin.kind === "logChanges" + ? await createLogChangesPatch(origin.changes, reverse, directory) + : await call(commands.vcsCreatePatch(origin.kind === "commits" ? repo : null, source!, directory)); if (!patch) { noPatchChanges(); return false; diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts index 510533d4a..332a5978c 100644 --- a/src/platform/keymaps/ideaParity.test.ts +++ b/src/platform/keymaps/ideaParity.test.ts @@ -122,6 +122,8 @@ describe("IDEA keymap parity", () => { // Vcs.Log.GoToRef: Find in the Git Log table. ["vcs.log.goToRef", ["Meta+F"], ["Ctrl+F"]], ["vcs.log.maximizeCommitMessage", [], []], + ["vcs.log.changes.createPatch", [], []], + ["vcs.log.changes.copyPatch", [], []], ["vcs.log.refresh", ["Meta+R"], ["Ctrl+F5"]], ["vcs.log.focusTextFilter", ["Ctrl+L"], ["Ctrl+L"]], // Back / Forward also carry the mouse side buttons (``). diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 981510c72..02000be9e 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -389,6 +389,8 @@ export const intellijMacos: Record = { "vcs.addToVcs": ["Meta+Alt+A"], "vcs.showDiff": ["Meta+D"], "vcs.log.changes.showDiff": ["Meta+D"], + "vcs.log.changes.createPatch": [], + "vcs.log.changes.copyPatch": [], "vcs.showDiffInNewWindow": [], "vcs.nextChange": ["Ctrl+Alt+Shift+Down"], "vcs.prevChange": ["Ctrl+Alt+Shift+Up"], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index a9c4f02b6..b3db88f98 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -383,6 +383,8 @@ export const intellijWindows: Record = { "vcs.addToVcs": ["Ctrl+Alt+A"], "vcs.showDiff": ["Ctrl+D"], "vcs.log.changes.showDiff": ["Ctrl+D"], + "vcs.log.changes.createPatch": [], + "vcs.log.changes.copyPatch": [], "vcs.showDiffInNewWindow": [], "vcs.nextChange": ["Ctrl+Alt+Shift+Down"], "vcs.prevChange": ["Ctrl+Alt+Shift+Up"], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index cabe47ee6..bd735a2a1 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -402,6 +402,8 @@ export const vscodeMacos: Record = { "vcs.addToVcs": [], "vcs.showDiff": [], "vcs.log.changes.showDiff": [], + "vcs.log.changes.createPatch": [], + "vcs.log.changes.copyPatch": [], "vcs.showDiffInNewWindow": [], "vcs.nextChange": ["Alt+F5"], "vcs.prevChange": ["Alt+Shift+F5"], From ee9b50179e136a687ae78371eb027d7fb7789f3b Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Mon, 30 Nov 2026 21:15:11 +0900 Subject: [PATCH 39/66] feat(welcome): import recent projects and groups from a JetBrains IDE (#6979) Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too. Closes #6970 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- Cargo.lock | 1 + crates/ide-host/src/menu.rs | 1 + crates/ide-workspace/Cargo.toml | 1 + crates/ide-workspace/src/recent.rs | 349 +++++++++++++++++- src-tauri/src/commands/app.rs | 31 ++ src-tauri/src/menu.rs | 1 + src-tauri/tests/commands.snap | 1 + src/bindings.ts | 15 + .../__tests__/importFromJetBrainsIde.test.tsx | 62 +++- .../jetbrainsSettingsImport.test.tsx | 30 ++ .../jetbrainsTemplatesImport.test.tsx | 1 + src/features/app/jetbrainsSettings.tsx | 35 +- src/features/app/projectActions.ts | 69 +++- src/features/welcome/ProjectsPage.tsx | 7 + src/platform/locales/en.json | 1 + src/platform/locales/text/en.json | 8 + src/platform/locales/text/zh.json | 7 + src/platform/locales/zh.json | 1 + 18 files changed, 594 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b19cd0c0..0e01cf43a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5116,6 +5116,7 @@ dependencies = [ "ide-text", "ide-vfs", "parking_lot 0.12.5", + "quick-xml 0.42.0", "semver", "serde", "serde_json", diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index 65eeca548..d80bb212c 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec { act("file.exportSettings", "Export Settings…"), act("file.importSettings", "Import Settings…"), act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"), + act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"), act("file.syncSettings", "Sync Settings Now"), ], ), diff --git a/crates/ide-workspace/Cargo.toml b/crates/ide-workspace/Cargo.toml index f3e8d275e..f4d324b07 100644 --- a/crates/ide-workspace/Cargo.toml +++ b/crates/ide-workspace/Cargo.toml @@ -24,6 +24,7 @@ globset.workspace = true uuid.workspace = true zip.workspace = true encoding_rs.workspace = true +quick-xml = "0.42" [target.'cfg(windows)'.dependencies] winreg = "0.56" diff --git a/crates/ide-workspace/src/recent.rs b/crates/ide-workspace/src/recent.rs index 7db02c3cd..5a027f892 100644 --- a/crates/ide-workspace/src/recent.rs +++ b/crates/ide-workspace/src/recent.rs @@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool { path.is_absolute() && !text.contains("://") && !wsl && !path.exists() } +fn folder_name(path: &Path) -> String { + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string()) +} + +/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct JetBrainsRecentImport { + /// Projects added to the recent projects. + pub imported: u32, + /// Projects left out because their folder no longer exists. + pub missing: u32, + /// Project groups added. + pub groups: u32, +} + +/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`. +#[derive(Debug, Default, PartialEq)] +struct JetBrainsRecent { + path: String, + name: Option, + opened_at_ms: f64, + /// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it. + hidden: bool, +} + +#[derive(Debug, Default, PartialEq)] +struct JetBrainsGroup { + name: String, + paths: Vec, + expanded: bool, +} + +/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and +/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`). +fn parse_jetbrains_recent(xml: &str) -> (Vec, Vec) { + use quick_xml::{Reader, XmlVersion, events::Event}; + let mut reader = Reader::from_str(xml); + let (mut projects, mut groups) = (Vec::new(), Vec::new()); + let mut project: Option = None; + let mut group: Option = None; + loop { + let (tag, empty) = match reader.read_event() { + Ok(Event::Start(tag)) => (tag, false), + Ok(Event::Empty(tag)) => (tag, true), + Ok(Event::End(tag)) => { + match tag.local_name().as_ref() { + "entry" => projects.extend(project.take()), + "ProjectGroup" => groups.extend(group.take()), + _ => {} + } + continue; + } + Ok(Event::Eof) | Err(_) => break, + _ => continue, + }; + let attr = |key: &str| { + tag.attributes() + .flatten() + .find(|a| a.key.as_ref() == key) + .and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned())) + }; + match tag.local_name().as_ref() { + "entry" if !empty && group.is_none() => { + project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() }); + } + "RecentProjectMetaInfo" => { + if let Some(p) = &mut project { + p.hidden = attr("hidden").as_deref() == Some("true"); + } + } + "ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()), + "option" => { + let (name, value) = (attr("name"), attr("value")); + if let Some(g) = &mut group { + match (name.as_deref(), value) { + (Some("name"), Some(v)) => g.name = v, + (Some("expanded"), Some(v)) => g.expanded = v == "true", + // `