mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
perf(intentions): show the ⌥↵ list at once, not after the server answers (#4429)
⌥↵ opened the list only after the language server answered. It now opens after 100 ms with the rows found locally and a spinner ("Computing…" when empty), and fills in when the actions arrive; a faster answer paints once. The caret line's error quick fixes are requested in parallel with the caret's actions, a late answer doesn't reopen a dismissed list, and a stale answer after an edit is dropped.
Co-authored-by: muutot <92625353+muutot@users.noreply.github.com>
This commit is contained in:
@@ -479,6 +479,67 @@ test("diagnostics underline the range and ⌥⏎ applies the preferred quick fix
|
||||
expect(applied).toMatchObject({ action: { title: "Import 'com.acme.orders.model.Order'" } });
|
||||
});
|
||||
|
||||
test("⌥⏎ opens the list before a slow server answers, then fills it", async ({ workbench: page }) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(
|
||||
({ file, bad }) => {
|
||||
const action = {
|
||||
title: "Import 'com.acme.orders.model.Order'",
|
||||
kind: "quickfix",
|
||||
isPreferred: true,
|
||||
disabledReason: null,
|
||||
edit: {
|
||||
files: [
|
||||
{
|
||||
kind: "edit",
|
||||
path: file,
|
||||
edits: [
|
||||
{
|
||||
range: { start: { line: 4, col: 0 }, end: { line: 4, col: 0 } },
|
||||
new_text: "import com.acme.orders.model.Order\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
command: null,
|
||||
data: null,
|
||||
server: "kotlin",
|
||||
};
|
||||
// The server's answer is held until the test releases it, so "the popup is up while the
|
||||
// server is still thinking" is a fact and not a race against a timer.
|
||||
window.__releaseActions = null;
|
||||
window.__ipc.handlers.lsp_code_actions = () =>
|
||||
new Promise((resolve) => {
|
||||
window.__releaseActions = () => resolve([action]);
|
||||
});
|
||||
window.__ipc.handlers.lsp_execute_code_action = () => [];
|
||||
window.__ipc.emit({
|
||||
type: "diagnostics",
|
||||
path: file,
|
||||
source: "kotlin",
|
||||
items: [
|
||||
{ range: bad, severity: "error", message: "Unresolved reference: Order", source: "kotlin", code: null },
|
||||
],
|
||||
});
|
||||
},
|
||||
{ file: FILE, bad: range(20, 19, 24) },
|
||||
);
|
||||
await caretAt(editor, page, "val order: Order", "Order ");
|
||||
const popup = page.getByTestId("list-popup");
|
||||
await page.keyboard.press("Alt+Enter");
|
||||
await expect(popup).toBeVisible();
|
||||
await expect(popup).toHaveAttribute("aria-busy", "true");
|
||||
expect(await ipcCalls(page, "lsp_code_actions")).toHaveLength(1);
|
||||
// Only now does the server answer.
|
||||
await page.evaluate(() => window.__releaseActions?.());
|
||||
const fix = page.getByRole("option", { name: /Import 'com\.acme\.orders\.model\.Order'/ });
|
||||
await expect(fix).toBeVisible();
|
||||
await expect(popup).not.toHaveAttribute("aria-busy", "true");
|
||||
await fix.click();
|
||||
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("lazy plugin actions resolve only when invoked, never for their intention preview", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface IpcStub {
|
||||
declare global {
|
||||
interface Window {
|
||||
__ipc: IpcStub;
|
||||
/** Releases a stubbed answer a test holds back on purpose (see the ⌥⏎ popup test). */
|
||||
__releaseActions?: (() => void) | null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
MenuList,
|
||||
Popup,
|
||||
Select,
|
||||
Spinner,
|
||||
SymbolBadge,
|
||||
fileIconName,
|
||||
fuzzyMatch,
|
||||
@@ -181,6 +182,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
>
|
||||
<div className={styles.listHeader}>
|
||||
<span className={styles.listTitle}>{popup.title}</span>
|
||||
{popup.busy && <Spinner size={12} />}
|
||||
{query && <span className={styles.query}>{query}</span>}
|
||||
{popup.pin && (
|
||||
<IconButton
|
||||
@@ -206,9 +208,15 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
aria-label={popup.title}
|
||||
onActivate={(r) => activate(r.item)}
|
||||
empty={
|
||||
<span className={styles.empty}>
|
||||
<T>Nothing matches</T>
|
||||
</span>
|
||||
popup.busy ? (
|
||||
<span className={styles.empty}>
|
||||
<T>Computing…</T>
|
||||
</span>
|
||||
) : (
|
||||
<span className={styles.empty}>
|
||||
<T>Nothing matches</T>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
renderItem={({ item, match }) => {
|
||||
const n = popup.numbered && !query ? indexOf(item) + 1 : 0;
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
const {
|
||||
actionsForDiagnostic,
|
||||
applyQuickFix,
|
||||
INTENTIONS_POPUP_DELAY_MS,
|
||||
quickFixesAt,
|
||||
applyKindSilently,
|
||||
bulbLine,
|
||||
@@ -49,15 +50,149 @@ const {
|
||||
lightsBulb,
|
||||
listedCodeActions,
|
||||
listedIntentions,
|
||||
showIntentions,
|
||||
withInspectionControls,
|
||||
} = await import("./intentions");
|
||||
const { useLspPopup, closePopup } = await import("./popupStore");
|
||||
const { setFileDiagnostics, toLintDiagnostics } = await import("./diagnostics");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
closePopup();
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("⌥↵ popup timing", () => {
|
||||
const editor = (doc: string, caret: number, path = "/p/a.ts") => {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: { anchor: caret },
|
||||
extensions: [lspDoc.of({ doc: 1, path, language: "typescript", uiMode: null, readOnly: false })],
|
||||
}),
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
};
|
||||
const answer = (data: CodeAction[]) => ({ status: "ok" as const, data });
|
||||
|
||||
it("shows the popup while the server is still answering, then fills it", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = editor("f(1);\n", 0);
|
||||
let resolve!: (v: unknown) => void;
|
||||
lspCodeActions.mockImplementation(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const shown = showIntentions(view);
|
||||
await vi.advanceTimersByTimeAsync(INTENTIONS_POPUP_DELAY_MS);
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup).toMatchObject({ kind: "list", title: "Intentions", busy: true, items: [] });
|
||||
resolve(answer([{ ...resolved, edit: null }]));
|
||||
await shown;
|
||||
expect(useLspPopup.getState().popup).toMatchObject({ kind: "list", busy: false });
|
||||
expect((useLspPopup.getState().popup as { items: { label: string }[] }).items.map((i) => i.label)).toEqual([
|
||||
"Introduce local variable",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows the answer at once when it beats the delay", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = editor("f(1);\n", 0);
|
||||
lspCodeActions.mockResolvedValue(answer([{ ...resolved, edit: null }]));
|
||||
await showIntentions(view);
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup).toMatchObject({ kind: "list", busy: false });
|
||||
// Every row is there before the delay could have shown an empty list.
|
||||
expect((popup as { items: unknown[] }).items).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("asks the line's errors alongside the caret's actions instead of after them", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = editor("val order: Order\n", 4);
|
||||
const error: Diagnostic = {
|
||||
range: { start: { line: 0, col: 11 }, end: { line: 0, col: 16 } },
|
||||
severity: "error",
|
||||
message: "Unresolved reference: Order",
|
||||
source: "kotlin",
|
||||
code: null,
|
||||
};
|
||||
view.dispatch(setDiagnostics(view.state, toLintDiagnostics(view.state.doc, [error])));
|
||||
const fix = { ...resolved, title: "Create class 'Order'", kind: "quickfix", edit: null };
|
||||
lspCodeActions.mockImplementation(async (_doc: number, range: { start: { col: number } }) =>
|
||||
answer(range.start.col === 11 ? [fix] : []),
|
||||
);
|
||||
await showIntentions(view);
|
||||
expect(lspCodeActions).toHaveBeenCalledTimes(2);
|
||||
expect((useLspPopup.getState().popup as { items: { label: string }[] }).items.map((i) => i.label)).toEqual([
|
||||
"Create class 'Order'",
|
||||
]);
|
||||
setFileDiagnostics("/p/a.ts", "kotlin", []);
|
||||
});
|
||||
|
||||
it("drops the busy popup when the request fails and nothing local is offered", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = editor("f(1);\n", 0);
|
||||
let reject!: (e: unknown) => void;
|
||||
lspCodeActions.mockImplementation(
|
||||
() =>
|
||||
new Promise((_, r) => {
|
||||
reject = r;
|
||||
}),
|
||||
);
|
||||
const shown = showIntentions(view);
|
||||
await vi.advanceTimersByTimeAsync(INTENTIONS_POPUP_DELAY_MS);
|
||||
expect((useLspPopup.getState().popup as { busy: boolean }).busy).toBe(true);
|
||||
reject({ kind: "internal", message: "boom" });
|
||||
await shown;
|
||||
expect(useLspPopup.getState().popup).toBeNull();
|
||||
});
|
||||
|
||||
it("closes instead of reopening when the caret's context changed meanwhile", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = editor("f(1);\n", 0);
|
||||
let resolve!: (v: unknown) => void;
|
||||
lspCodeActions.mockImplementation(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const shown = showIntentions(view);
|
||||
await vi.advanceTimersByTimeAsync(INTENTIONS_POPUP_DELAY_MS);
|
||||
expect(useLspPopup.getState().popup).not.toBeNull();
|
||||
view.dispatch({ changes: { from: 0, insert: "g();\n" } });
|
||||
resolve(answer([{ ...resolved, edit: null }]));
|
||||
await shown;
|
||||
expect(useLspPopup.getState().popup).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a popup the user opened while the actions were being computed", async () => {
|
||||
vi.useFakeTimers();
|
||||
const view = editor("f(1);\n", 0);
|
||||
let resolve!: (v: unknown) => void;
|
||||
lspCodeActions.mockImplementation(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const shown = showIntentions(view);
|
||||
await vi.advanceTimersByTimeAsync(INTENTIONS_POPUP_DELAY_MS);
|
||||
const mine = useLspPopup.getState().popup;
|
||||
// Something else (a chooser, another ⌥↵) replaced it.
|
||||
const other = { kind: "list" as const, anchor: { x: 0, y: 0 }, title: "Other", items: [] };
|
||||
useLspPopup.setState((s) => ({ popup: other, seq: s.seq + 1 }));
|
||||
resolve(answer([{ ...resolved, edit: null }]));
|
||||
await shown;
|
||||
expect(useLspPopup.getState().popup).toBe(other);
|
||||
expect(mine).not.toBe(other);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inspection controls in ⌥↵ (issue #42)", () => {
|
||||
|
||||
+114
-49
@@ -22,7 +22,16 @@ import { offsetsToRange } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
import { formatLines } from "./format";
|
||||
import { languageSemantics } from "./semantic";
|
||||
import { caretAnchor, openPopup, type ListPopupItem, type ListPreview } from "./popupStore";
|
||||
import {
|
||||
caretAnchor,
|
||||
closePopup,
|
||||
openPopup,
|
||||
updatePopup,
|
||||
useLspPopup,
|
||||
type ListPopupItem,
|
||||
type ListPreview,
|
||||
type PopupPoint,
|
||||
} from "./popupStore";
|
||||
import { editPreviewLines } from "./workspaceEdit";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
@@ -118,34 +127,39 @@ export function lineErrorsAwayFromCaret(
|
||||
return errors.filter((p) => p.from >= lineFrom && p.from <= lineTo).sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
/** ⌥↵ / lightbulb actions: those at the caret plus, as in IDEA, quick fixes of another error on the line. */
|
||||
/**
|
||||
* ⌥↵ / lightbulb actions: those at the caret plus, as in IDEA, quick fixes of
|
||||
* another error on the line. Both are asked at once: the line's errors are a
|
||||
* separate query the server answers independently, so waiting for the caret's
|
||||
* answer first would double the latency of every ⌥↵ on a broken line.
|
||||
*/
|
||||
async function fetchIntentions(view: EditorView): Promise<CodeAction[]> {
|
||||
const actions = (await fetchActions(view, [])).filter((a) => !a.disabledReason);
|
||||
const doc = docOf(view);
|
||||
const state = view.state;
|
||||
const doc = docOf(view);
|
||||
const sel = state.selection.main;
|
||||
if (!doc || !sel.empty) return actions;
|
||||
const line = state.doc.lineAt(sel.head);
|
||||
const problems: PlacedProblem[] = [];
|
||||
forEachDiagnostic(state, (d, from, to) => problems.push({ from, to, severity: d.severity }));
|
||||
const line = doc && sel.empty ? state.doc.lineAt(sel.head) : null;
|
||||
if (line) forEachDiagnostic(state, (d, from, to) => problems.push({ from, to, severity: d.severity }));
|
||||
const errors = line ? lineErrorsAwayFromCaret(problems, line.from, line.to, sel.head) : [];
|
||||
|
||||
const lineFixes = async (): Promise<CodeAction[]> => {
|
||||
for (const p of errors) {
|
||||
const more = await lspRequest(() =>
|
||||
commands.lspCodeActions(doc!.doc, offsetsToRange(state.doc, p.from, p.to), ["quickfix"]),
|
||||
).catch(() => null);
|
||||
if (more === null || view.state.doc !== state.doc) return [];
|
||||
// Disabled ones and duplicates of the caret's actions are dropped below.
|
||||
if (more.some((a) => isQuickFix(a) && !a.disabledReason)) return more;
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const [main, more] = await Promise.all([fetchActions(view, []), errors.length ? lineFixes() : Promise.resolve([])]);
|
||||
const actions = main.filter((a) => !a.disabledReason);
|
||||
if (view.state.doc !== state.doc) return actions;
|
||||
const titles = new Set(actions.map((a) => a.title));
|
||||
for (const p of lineErrorsAwayFromCaret(problems, line.from, line.to, sel.head)) {
|
||||
let more: CodeAction[];
|
||||
try {
|
||||
more = await lspRequest(() =>
|
||||
commands.lspCodeActions(doc.doc, offsetsToRange(state.doc, p.from, p.to), ["quickfix"]),
|
||||
);
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
if (view.state.doc !== state.doc) break;
|
||||
const fixes = more.filter((a) => isQuickFix(a) && !a.disabledReason && !titles.has(a.title));
|
||||
if (fixes.length) {
|
||||
actions.push(...fixes);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return actions;
|
||||
const extra = more.filter((a) => isQuickFix(a) && !a.disabledReason && !titles.has(a.title));
|
||||
return extra.length ? [...actions, ...extra] : actions;
|
||||
}
|
||||
|
||||
export type EditorQuickFix = CodeAction | { title: string; run: () => void | Promise<void> };
|
||||
@@ -489,40 +503,91 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* How long ⌥↵ waits for the server's actions before showing the popup with a
|
||||
* progress row: the answer that arrives sooner appears at once (no flash), a
|
||||
* slower one no longer leaves the key without any feedback.
|
||||
*/
|
||||
export const INTENTIONS_POPUP_DELAY_MS = 100;
|
||||
|
||||
/** ⌥↵ */
|
||||
export async function showIntentions(view: EditorView) {
|
||||
try {
|
||||
// Local inspections need no language server.
|
||||
const local: ListPopupItem[] = [...spellingIntentions(view), ...contributedIntentions(view)];
|
||||
let actions: CodeAction[] = [];
|
||||
let failure: { error: unknown } | null = null;
|
||||
try {
|
||||
// Like IDEA, only applicable intentions are listed (servers also report disabled refactorings).
|
||||
actions = await fetchIntentions(view);
|
||||
} catch (e) {
|
||||
failure = { error: e };
|
||||
}
|
||||
const state = view.state;
|
||||
// Local inspections need no language server.
|
||||
const local: ListPopupItem[] = [...spellingIntentions(view), ...contributedIntentions(view)];
|
||||
const anchor: PopupPoint = caretAnchor(view, state.selection.main.head);
|
||||
const resolved = new Map<CodeAction, Promise<CodeAction>>();
|
||||
const previews = new Map<string, CodeAction>();
|
||||
const itemsFor = (actions: CodeAction[]) => {
|
||||
const sorted = listedCodeActions(actions);
|
||||
const resolved = new Map<CodeAction, Promise<CodeAction>>();
|
||||
const serverItems = actionItems(view, sorted, resolved);
|
||||
const previews = new Map(serverItems.map((item, i) => [item.id, sorted[i]!]));
|
||||
const items = withInspectionControls(view, listedIntentions(view, [...local, ...serverItems]));
|
||||
serverItems.forEach((item, i) => previews.set(item.id, sorted[i]!));
|
||||
return withInspectionControls(view, listedIntentions(view, [...local, ...serverItems]));
|
||||
};
|
||||
const preview = (item: ListPopupItem, signal: AbortSignal) => {
|
||||
const action = previews.get(item.id);
|
||||
return action ? intentionPreview(view, action, resolved, signal) : Promise.resolve(null);
|
||||
};
|
||||
|
||||
// The popup is ours while `seq` is its sequence number; another popup took its place otherwise.
|
||||
let seq: number | null = null;
|
||||
// Escape (or a click elsewhere) closes it: a late answer must not reopen it.
|
||||
let dismissed = false;
|
||||
const ours = () => {
|
||||
const { popup, seq: current } = useLspPopup.getState();
|
||||
return seq !== null && popup?.kind === "list" && current === seq;
|
||||
};
|
||||
const display = (items: ListPopupItem[], busy: boolean) => {
|
||||
if (dismissed) return;
|
||||
if (ours()) {
|
||||
updatePopup("list", { items, busy });
|
||||
return;
|
||||
}
|
||||
// A popup the user opened meanwhile (another ⌥↵, a chooser) stays: only ours is replaced.
|
||||
if (seq !== null) return;
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor,
|
||||
title: "Intentions",
|
||||
items,
|
||||
busy,
|
||||
preview,
|
||||
onClose: () => {
|
||||
dismissed = true;
|
||||
},
|
||||
});
|
||||
seq = useLspPopup.getState().seq;
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
// IDEA shows the list while it is still being filled; the rows found locally come first.
|
||||
display(itemsFor([]), true);
|
||||
}, INTENTIONS_POPUP_DELAY_MS);
|
||||
|
||||
try {
|
||||
let failure: unknown = null;
|
||||
// Like IDEA, only applicable intentions are listed (servers also report disabled refactorings).
|
||||
const actions = await fetchIntentions(view).catch((e: unknown) => {
|
||||
failure = e;
|
||||
return null;
|
||||
});
|
||||
clearTimeout(timer);
|
||||
const items = actions ? itemsFor(actions) : withInspectionControls(view, listedIntentions(view, local));
|
||||
if (!items.length) {
|
||||
if (failure) throw failure.error;
|
||||
if (ours()) closePopup();
|
||||
if (failure) throw failure;
|
||||
showHint(view, "No intentions available");
|
||||
return;
|
||||
}
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor: caretAnchor(view, view.state.selection.main.head),
|
||||
title: "Intentions",
|
||||
items,
|
||||
preview: (item, signal) => {
|
||||
const action = previews.get(item.id);
|
||||
return action ? intentionPreview(view, action, resolved, signal) : Promise.resolve(null);
|
||||
},
|
||||
});
|
||||
// The list is about the caret's context: an edit while it was being computed makes it stale.
|
||||
if (view.state.doc !== state.doc) {
|
||||
if (ours()) closePopup();
|
||||
return;
|
||||
}
|
||||
display(items, false);
|
||||
} catch (e) {
|
||||
clearTimeout(timer);
|
||||
if (ours()) closePopup();
|
||||
reportLspError(view, e, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,6 +267,7 @@
|
||||
"Heap: {label}": "Heap: {label}",
|
||||
"Writing the heap dump…": "Writing the heap dump…",
|
||||
"Linking objects…": "Linking objects…",
|
||||
"Computing…": "Computing…",
|
||||
"Computing dominators…": "Computing dominators…",
|
||||
"Computing retained sizes…": "Computing retained sizes…",
|
||||
"Finding paths to GC roots…": "Finding paths to GC roots…",
|
||||
|
||||
@@ -238,6 +238,7 @@
|
||||
"Heap: {label}": "堆:{label}",
|
||||
"Writing the heap dump…": "正在写入堆转储…",
|
||||
"Linking objects…": "正在关联对象…",
|
||||
"Computing…": "正在计算…",
|
||||
"Computing dominators…": "正在计算支配树…",
|
||||
"Computing retained sizes…": "正在计算保留大小…",
|
||||
"Finding paths to GC roots…": "正在查找到 GC 根的路径…",
|
||||
|
||||
Reference in New Issue
Block a user