Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

41.6 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { DEFAULT_SSH_CONFIG } from "@/platform/remoteSettings";
import { commands, type Settings } from "@/platform/ipc";

const settingsSet = vi.fn();
const settingsGet = vi.fn();
const settingsGetGlobal = vi.fn();

vi.mock("@/platform/ipc", async (importOriginal) => {
  const real = await importOriginal<typeof import("@/platform/ipc")>();
  return {
    ...real,
    isTauri: () => true,
    commands: {
      ...real.commands,
      settingsSet: (...a: unknown[]) => settingsSet(...a),
      settingsGet: () => settingsGet(),
      settingsGetGlobal: () => settingsGetGlobal(),
    },
  };
});

import { registerAction, executeAction } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { useKeymap } from "@/platform/keymap";
import { ContextMenuHost, hideContextMenu, useContextMenuStore } from "@/ui";
import { PageContext, useSetting } from "../components/context";
import { DEFAULT_SETTINGS, setAt } from "../model/schema";
import { openSettings, stage, useSettingsDialog } from "../model/staging";
import { SettingsDialog } from "../dialog/SettingsDialog";
import { ProjectStructureDialog } from "../languages/ProjectStructurePage";
import { SettingsWindow } from "../window/SettingsWindow";
import dialogStyles from "../dialog/SettingsDialog.module.css";
import { activate } from "..";
import { MessagesHost } from "@/workbench/messages";

let current: Settings;
let dispose: () => void = () => {};

beforeEach(() => {
  current = structuredClone(DEFAULT_SETTINGS) as Settings;
  settingsSet.mockReset().mockImplementation(async (_scope: string, key: string, json: string) => {
    current = setAt(current, key, JSON.parse(json));
    return { status: "ok", data: current };
  });
  settingsGet.mockReset().mockImplementation(async () => current);
  settingsGetGlobal.mockReset().mockImplementation(async () => current);
  useProject.setState({ settings: current, project: null });
  dispose = activate();
});

afterEach(() => {
  act(() => useSettingsDialog.setState({ open: false, projectStructureOpen: false }));
  act(hideContextMenu);
  dispose();
});

async function openDialog(page?: string) {
  render(
    <>
      <SettingsDialog />
      <MessagesHost />
    </>,
  );
  await act(async () => {
    await executeAction("file.settings", page);
  });
  return screen.getByRole("dialog", { name: "Settings" });
}

describe("Settings dialog", () => {
  it("offers only new window, current window and ask, including old attach settings", async () => {
    current = setAt(current, "general.openProjectIn", "attach");
    const dialog = await openDialog("general");
    const group = within(dialog).getByRole("radiogroup", { name: "Open project in" });
    expect(within(group).getAllByRole("radio")).toHaveLength(3);
    expect(within(group).getByRole("radio", { name: "Ask" })).toBeChecked();
    expect(within(group).queryByRole("radio", { name: "Attach" })).not.toBeInTheDocument();
  });

  it("stages properties conversion through its action and applies the checkbox", async () => {
    const dialog = await openDialog("editor.fileEncodings");
    const checkbox = within(dialog).getByRole("checkbox", { name: "Transparent native-to-ascii conversion" });
    expect(checkbox).not.toBeChecked();
    await act(async () => fireEvent.click(checkbox));
    expect(checkbox).toBeChecked();
    expect(settingsSet).not.toHaveBeenCalled();
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet).toHaveBeenCalledWith("global", "editor.encodings.nativeToAscii", "true");
  });

  it("toggles properties conversion through its stable action", async () => {
    await executeAction("editor.encodings.toggleNativeToAscii");
    expect(settingsSet).toHaveBeenCalledWith("global", "editor.encodings.nativeToAscii", "true");
    await executeAction("editor.encodings.toggleNativeToAscii");
    expect(settingsSet).toHaveBeenLastCalledWith("global", "editor.encodings.nativeToAscii", "false");
  });

  it("edits CMake profiles in project settings and persists them on Apply", async () => {
    useProject.setState({ project: { root: "/project" } as never });
    const dialog = await openDialog("build.cmake");
    expect(within(dialog).getByRole("option", { name: "Debug" })).toBeInTheDocument();
    fireEvent.click(
      within(within(dialog).getByRole("toolbar", { name: "CMake profile actions" })).getByRole("button", {
        name: "Add",
      }),
    );
    fireEvent.change(within(dialog).getByLabelText("Name"), { target: { value: "Release" } });
    fireEvent.change(within(dialog).getByLabelText("Build type"), { target: { value: "Release" } });
    fireEvent.change(within(dialog).getByLabelText("Generator"), { target: { value: "Ninja" } });
    fireEvent.change(within(dialog).getByLabelText("Build arguments"), { target: { value: "-j 8" } });
    expect(settingsSet).not.toHaveBeenCalled();
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    const write = settingsSet.mock.calls.find((c) => c[1] === "cmake.profiles")!;
    expect(write[0]).toBe("project");
    expect(JSON.parse(write[2])).toEqual([
      expect.objectContaining({ name: "Debug", buildType: "Debug" }),
      expect.objectContaining({ name: "Release", buildType: "Release", generator: "Ninja", buildArgs: ["-j", "8"] }),
    ]);
  });

  it("finds Gradle JVM and applies project Gradle settings", async () => {
    useProject.setState({ project: { root: "/project" } as never });
    const dialog = await openDialog("build.gradle");
    fireEvent.change(within(dialog).getByLabelText("Search settings"), { target: { value: "Gradle JVM" } });
    expect(within(dialog).getByRole("tree", { name: "Settings pages" }).textContent).toContain("Gradle");
    expect(within(dialog).getByLabelText("Gradle JVM")).toBeInTheDocument();
    await act(async () => stage("build.gradle", "project", "languages.java.gradle.jvm", "/jdk21"));
    await act(async () => stage("build.gradle", "project", "languages.java.gradle.distribution", "local"));
    expect(within(dialog).getByPlaceholderText("Gradle installation directory")).toBeInTheDocument();
    await act(async () => stage("build.gradle", "project", "languages.java.gradle.home", "/gradle"));
    await act(async () => stage("build.gradle", "project", "languages.java.gradle.userHome", "/gradle-cache"));
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet.mock.calls).toEqual(
      expect.arrayContaining([
        ["project", "languages.java.gradle.jvm", '"/jdk21"'],
        ["project", "languages.java.gradle.distribution", '"local"'],
        ["project", "languages.java.gradle.home", '"/gradle"'],
        ["project", "languages.java.gradle.userHome", '"/gradle-cache"'],
      ]),
    );
  });

  it("persists Maven toolchains and profiles in project settings", async () => {
    useProject.setState({ project: { root: "/project" } as never });
    const dialog = await openDialog("build.maven");
    fireEvent.change(within(dialog).getByLabelText("Toolchains file"), {
      target: { value: "config files/toolchains.xml" },
    });
    fireEvent.change(within(dialog).getByLabelText("Active profiles"), { target: { value: "a, b,!c" } });
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet.mock.calls).toEqual(
      expect.arrayContaining([
        ["project", "languages.java.maven.toolchains", '"config files/toolchains.xml"'],
        ["project", "languages.java.maven.activeProfiles", '"a, b,!c"'],
      ]),
    );
  });

  it("finds the Maven active profiles setting", async () => {
    useProject.setState({ project: { root: "/project" } as never });
    const dialog = await openDialog("build.maven");
    fireEvent.change(within(dialog).getByLabelText("Search settings"), { target: { value: "Active profiles" } });
    expect(within(dialog).getByLabelText("Active profiles")).toBeInTheDocument();
  });

  it("finds the Maven toolchains setting", async () => {
    useProject.setState({ project: { root: "/project" } as never });
    const dialog = await openDialog("build.maven");
    fireEvent.change(within(dialog).getByLabelText("Search settings"), { target: { value: "Toolchains" } });
    expect(within(dialog).getByLabelText("Toolchains file")).toBeInTheDocument();
  });

  it("searches pages and highlights matching option labels", async () => {
    const dialog = await openDialog("appearance");
    fireEvent.change(within(dialog).getByLabelText("Search settings"), { target: { value: "soft wrap" } });
    const tree = within(dialog).getByRole("tree", { name: "Settings pages" });
    expect(within(tree).getByText("General")).toBeInTheDocument();
    expect(within(tree).queryByText("Keymap")).toBeNull();
    // The matching page is selected and its option label is highlighted.
    const option = within(dialog).getByRole("checkbox", { name: /Soft-wrap files/ });
    expect(option.closest("[data-search-match]")).not.toBeNull();
    expect(dialog.querySelectorAll("mark").length).toBeGreaterThan(0);
  });

  it("Esc in the search field clears the filter first; ↓ selects the next page keeping the focus", async () => {
    const dialog = await openDialog("appearance");
    const search = within(dialog).getByLabelText("Search settings");
    fireEvent.change(search, { target: { value: "soft wrap" } });
    fireEvent.keyDown(search, { key: "Escape" });
    expect((search as HTMLInputElement).value).toBe("");
    expect(screen.getByRole("dialog", { name: "Settings" })).toBeInTheDocument();
    const before = useSettingsDialog.getState().pageId;
    search.focus();
    fireEvent.keyDown(search, { key: "ArrowDown" });
    expect(useSettingsDialog.getState().pageId).not.toBe(before);
    expect(document.activeElement).toBe(search);
  });

  it("stages edits and writes them on Apply", async () => {
    const dialog = await openDialog("editor.general");
    fireEvent.click(within(dialog).getByRole("checkbox", { name: /Soft-wrap files/ }));
    fireEvent.click(within(dialog).getByRole("checkbox", { name: /Reformat code on save/ }));
    expect(settingsSet).not.toHaveBeenCalled();
    await act(async () => {
      fireEvent.click(within(dialog).getByRole("button", { name: "Apply" }));
    });
    expect(settingsSet.mock.calls).toEqual([
      ["global", "editor.formatOnSave", "true"],
      ["global", "editor.softWrap", "false"],
    ]);
    expect(settingsGet).toHaveBeenCalled();
    expect(useProject.getState().settings?.editor?.softWrap).toBe(false);
    expect(within(dialog).getByRole("button", { name: "Apply" })).toBeDisabled();
  });

  it("stages manual editor and proportional CJK fallback names and applies them", async () => {
    const dialog = await openDialog("editor.font");
    fireEvent.change(within(dialog).getByRole("combobox", { name: "Font" }), { target: { value: "Maple Mono NF" } });
    fireEvent.change(within(dialog).getByRole("combobox", { name: "Fallback font" }), {
      target: { value: "思源宋体" },
    });
    expect(settingsSet).not.toHaveBeenCalled();
    expect(within(dialog).getByLabelText("Font preview").style.fontFamily).toContain("思源宋体");
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet.mock.calls).toEqual([
      ["global", "editor.fallbackFont", '"思源宋体"'],
      ["global", "editor.fontFamily", '"Maple Mono NF"'],
    ]);
  });

  it("cancels manual font edits without changing saved preferences", async () => {
    const dialog = await openDialog("editor.font");
    fireEvent.change(within(dialog).getByRole("combobox", { name: "Font" }), { target: { value: "Unsaved Font" } });
    fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
    expect(settingsSet).not.toHaveBeenCalled();
    expect(useSettingsDialog.getState().open).toBe(false);
    expect(useProject.getState().settings?.editor?.fontFamily).toBe("JetBrains Mono");
  });

  it("keeps global and project font edits separate when switching scope", async () => {
    useSettingsDialog.setState({ scopes: {} });
    const global = setAt(structuredClone(DEFAULT_SETTINGS) as Settings, "editor.fontFamily", "Global Font");
    current = setAt(global, "editor.fontFamily", "Project Font");
    settingsGetGlobal.mockResolvedValue(global);
    useProject.setState({
      settings: current,
      project: { root: "/synthetic", name: "synthetic", settings: current } as never,
    });
    const dialog = await openDialog("editor.font");
    const font = () => within(dialog).getByRole("combobox", { name: "Font" });
    fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
    expect(font()).toHaveValue("Project Font");
    fireEvent.change(font(), { target: { value: "Project Maple" } });
    fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
    expect(font()).toHaveValue("Global Font");
    fireEvent.change(font(), { target: { value: "Global Maple" } });
    fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
    expect(font()).toHaveValue("Project Maple");
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet.mock.calls).toEqual(
      expect.arrayContaining([
        ["project", "editor.fontFamily", '"Project Maple"'],
        ["global", "editor.fontFamily", '"Global Maple"'],
      ]),
    );
  });

  it("Typography Settings weights preview live and apply as editor settings", async () => {
    const dialog = await openDialog("editor.font");
    expect(within(dialog).getByRole("button", { name: "Main font weight" })).toHaveTextContent("Regular");
    expect(within(dialog).getByRole("button", { name: "Bold font weight" })).toHaveTextContent("Bold");
    act(() => {
      stage("editor.font", "global", "editor.fontWeight", 300);
      stage("editor.font", "global", "editor.boldFontWeight", 600);
    });
    expect(within(dialog).getByRole("button", { name: "Main font weight" })).toHaveTextContent("Light");
    const preview = within(dialog).getByLabelText("Font preview");
    expect(preview.style.getPropertyValue("--fw-code")).toBe("300");
    expect(preview.style.getPropertyValue("--fw-code-bold")).toBe("600");
    await act(async () => {
      fireEvent.click(within(dialog).getByRole("button", { name: "Apply" }));
    });
    expect(settingsSet.mock.calls).toEqual([
      ["global", "editor.boldFontWeight", "600"],
      ["global", "editor.fontWeight", "300"],
    ]);
  });

  it("enables, saves and clears the custom UI fallback font", async () => {
    const dialog = await openDialog("appearance");
    const fallback = within(dialog).getByRole("combobox", { name: "UI fallback font" });
    const custom = within(dialog).getByRole("checkbox", { name: "Use custom font:" });
    expect(fallback).toBeDisabled();
    fireEvent.click(custom);
    expect(fallback).toBeEnabled();
    fireEvent.change(fallback, { target: { value: "Songti SC" } });
    expect(settingsSet).not.toHaveBeenCalled();
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet).toHaveBeenCalledWith("global", "appearance.uiFontFallback", JSON.stringify("Songti SC"));
    fireEvent.change(fallback, { target: { value: "" } });
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet).toHaveBeenCalledWith("global", "appearance.uiFontFallback", JSON.stringify(""));
    fireEvent.click(custom);
    expect(fallback).toBeDisabled();
  });

  it("edits and saves independent custom font weights", async () => {
    const dialog = await openDialog("editor.font");
    for (const [label, value] of [
      ["Main font weight", "449"],
      ["Bold font weight", "650"],
    ]) {
      fireEvent.click(within(dialog).getByRole("button", { name: label }));
      fireEvent.click(screen.getByRole("option", { name: "Custom" }));
      fireEvent.change(within(dialog).getByLabelText(`${label} custom value`), { target: { value } });
    }
    const preview = within(dialog).getByLabelText("Font preview");
    expect(preview.style.getPropertyValue("--fw-code")).toBe("450");
    expect(preview.style.getPropertyValue("--fw-code-bold")).toBe("650");
    await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
    expect(settingsSet.mock.calls).toEqual([
      ["global", "editor.boldFontWeight", "650"],
      ["global", "editor.fontWeight", "450"],
    ]);
  });

  it("enables Apply and Reset for a secret-only edit, and Reset discards it", async () => {
    current = setAt(current, "ssh.configs", [{ ...DEFAULT_SSH_CONFIG, id: "ssh-dialog", auth: "password" }]);
    useProject.setState({ settings: current });
    const needsSecret = vi.spyOn(commands, "sshNeedsSecret").mockResolvedValue({ status: "ok", data: true });
    const setSecret = vi.spyOn(commands, "sshSetSecret").mockResolvedValue();
    try {
      const dialog = await openDialog("tools.sshConfigurations");
      const apply = within(dialog).getByRole("button", { name: "Apply" });
      expect(apply).toBeDisabled();
      fireEvent.change(within(dialog).getByLabelText("Password"), { target: { value: crypto.randomUUID() } });
      expect(apply).toBeEnabled();
      fireEvent.click(within(dialog).getByRole("button", { name: "Reset" }));
      expect(within(dialog).getByLabelText("Password")).toHaveValue("");
      expect(apply).toBeDisabled();
      expect(setSecret).not.toHaveBeenCalled();
      expect(settingsSet).not.toHaveBeenCalled();
    } finally {
      needsSecret.mockRestore();
      setSecret.mockRestore();
    }
  });

  it("Cancel discards staged edits", async () => {
    const dialog = await openDialog("editor.codeStyle.other");
    fireEvent.change(within(dialog).getByLabelText("Tab size"), { target: { value: "2" } });
    expect(Object.keys(useSettingsDialog.getState().staged)).toEqual(["global|editor.tabSize"]);
    fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
    expect(settingsSet).not.toHaveBeenCalled();
    expect(useSettingsDialog.getState().open).toBe(false);
  });

  it("records a shortcut, shows conflicts and applies it to the keymap on OK", async () => {
    registerAction({
      id: "code.duplicateLine",
      title: "Duplicate Line",
      category: "Code",
      when: "editorFocus",
      run: () => {},
    });
    registerAction({ id: "t.mine", title: "My Action", category: "Code", when: "editorFocus", run: () => {} });
    const dialog = await openDialog("keymap");
    render(<ContextMenuHost />);
    const row = within(dialog).getByText("My Action");
    fireEvent.doubleClick(row);
    fireEvent.click(await screen.findByRole("menuitem", { name: "Add Keyboard Shortcut" }));
    const recorder = await screen.findByRole("dialog", { name: /Keyboard Shortcut: My Action/ });
    const first = within(recorder).getByRole("textbox", { name: "First stroke" });
    fireEvent.keyDown(first, { code: "KeyD", key: "d", metaKey: true });
    expect(within(recorder).getByText("Duplicate Line")).toBeInTheDocument();
    fireEvent.click(within(recorder).getByRole("button", { name: "OK" }));
    const warning = await screen.findByRole("dialog", { name: "Warning" });
    expect(within(warning).getByText(/already assigned to other actions/)).toBeInTheDocument();
    await act(async () => {
      fireEvent.click(within(warning).getByRole("button", { name: "Leave" }));
    });
    expect(useSettingsDialog.getState().staged["global|keymapOverrides"]?.value).toEqual({ "t.mine": ["Meta+D"] });
    await act(async () => {
      fireEvent.click(within(dialog).getByRole("button", { name: "OK" }));
    });
    expect(settingsSet).toHaveBeenCalledWith("global", "keymapOverrides", '{"t.mine":["Meta+D"]}');
    expect(useKeymap.getState().overrides).toEqual({ "t.mine": ["Meta+D"] });
    expect(useSettingsDialog.getState().open).toBe(false);
  });

  it.each(["double-click", "Enter"])(
    "opens the shortcut menu on %s and clears mouse recording mode",
    async (activation) => {
      render(<ContextMenuHost />);
      registerAction({ id: "t.activate", title: "Activation Target", category: "Code", run: () => {} });
      const dialog = await openDialog("keymap");
      const row = within(dialog).getByText("Activation Target").closest('[role="treeitem"]')!;
      const tree = within(dialog).getByRole("tree", { name: "Actions" });
      const rect = vi.spyOn(row, "getBoundingClientRect").mockReturnValue({
        left: 100,
        bottom: 150,
        top: 126,
        right: 500,
        width: 400,
        height: 24,
        x: 100,
        y: 126,
        toJSON: () => ({}),
      });
      const activateRow = () => {
        fireEvent.mouseDown(row, { button: 0 });
        if (activation === "double-click") fireEvent.doubleClick(row, { clientX: 220, clientY: 138 });
        else fireEvent.keyDown(tree, { key: "Enter" });
      };
      activateRow();
      expect(useContextMenuStore.getState().menu).toMatchObject(
        activation === "double-click" ? { x: 220, y: 138 } : { x: 100, y: 150 },
      );
      expect(screen.queryByRole("dialog", { name: /Shortcut: Activation Target/ })).not.toBeInTheDocument();
      const keyboard = await screen.findByRole("menuitem", { name: "Add Keyboard Shortcut" });
      expect(keyboard).toHaveFocus();
      fireEvent.keyDown(keyboard, { key: "ArrowDown" });
      const mouse = screen.getByRole("menuitem", { name: "Add Mouse Shortcut" });
      expect(mouse).toHaveFocus();
      fireEvent.keyDown(mouse, { key: "Enter" });
      const recorder = await screen.findByRole("dialog", { name: "Mouse Shortcut: Activation Target" });
      fireEvent.mouseDown(within(recorder).getByRole("textbox", { name: "Mouse shortcut" }), {
        button: 0,
        altKey: true,
      });
      fireEvent.click(within(recorder).getByRole("button", { name: "OK" }));
      const overrides = useSettingsDialog.getState().staged["global|keymapOverrides"]?.value;
      expect(overrides).toEqual({ "t.activate": ["Alt+Button1"] });
      activateRow();
      fireEvent.click(await screen.findByRole("menuitem", { name: "Add Keyboard Shortcut" }));
      const keys = await screen.findByRole("dialog", { name: "Keyboard Shortcut: Activation Target" });
      expect(within(keys).getByRole("textbox", { name: "First stroke" })).toBeInTheDocument();
      fireEvent.click(within(keys).getByRole("button", { name: "Cancel" }));
      fireEvent.contextMenu(row);
      fireEvent.click(await screen.findByRole("menuitem", { name: "Add Mouse Shortcut" }));
      fireEvent.click(
        within(await screen.findByRole("dialog", { name: "Mouse Shortcut: Activation Target" })).getByRole("button", {
          name: "Cancel",
        }),
      );
      fireEvent.click(within(dialog).getByRole("button", { name: "Add Keyboard Shortcut" }));
      expect(await screen.findByRole("dialog", { name: "Keyboard Shortcut: Activation Target" })).toBeInTheDocument();
      rect.mockRestore();
    },
  );

  it("duplicates the keymap from the gear menu and edits the copy", async () => {
    render(<ContextMenuHost />);
    registerAction({ id: "t.dup", title: "Dup Target", category: "Code", run: () => {} });
    const dialog = await openDialog("keymap");
    fireEvent.click(within(dialog).getByRole("button", { name: "Show Scheme Actions" }));
    fireEvent.click(await screen.findByText("Duplicate…"));
    const named = await screen.findByRole("dialog", { name: "Duplicate Keymap" });
    expect(within(named).getByRole("textbox")).toHaveValue("macOS copy");
    fireEvent.click(within(named).getByRole("button", { name: "OK" }));
    const staged = useSettingsDialog.getState().staged;
    expect(staged["global|keymap"]?.value).toBe("custom.macos-copy");
    expect(staged["global|customKeymaps"]?.value).toEqual({
      "custom.macos-copy": { name: "macOS copy", parent: "intellij-macos", overrides: {} },
    });
    fireEvent.doubleClick(within(dialog).getByText("Dup Target"));
    fireEvent.click(await screen.findByRole("menuitem", { name: "Add Keyboard Shortcut" }));
    const recorder = await screen.findByRole("dialog", { name: /Keyboard Shortcut: Dup Target/ });
    fireEvent.keyDown(within(recorder).getByRole("textbox", { name: "First stroke" }), {
      code: "F9",
      key: "F9",
      shiftKey: true,
      altKey: true,
      metaKey: true,
      ctrlKey: true,
    });
    fireEvent.click(within(recorder).getByRole("button", { name: "OK" }));
    const after = useSettingsDialog.getState().staged;
    expect(after["global|customKeymaps"]?.value).toEqual({
      "custom.macos-copy": {
        name: "macOS copy",
        parent: "intellij-macos",
        overrides: { "t.dup": ["Ctrl+Alt+Shift+Meta+F9"] },
      },
    });
    expect(after["global|keymapOverrides"]).toBeUndefined();
    await act(async () => {
      fireEvent.click(within(dialog).getByRole("button", { name: "OK" }));
    });
    expect(useKeymap.getState().preset).toBe("intellij-macos");
    expect(useKeymap.getState().overrides).toEqual({ "t.dup": ["Ctrl+Alt+Shift+Meta+F9"] });
  });

  describe("toolchain settings with a project open", () => {
    let global: Settings;
    beforeEach(() => {
      // Global layer: -Xmx1g; the project overrides it with -Xmx4g.
      global = setAt(structuredClone(DEFAULT_SETTINGS) as Settings, "languages.java.jdtlsVmArgs", "-Xmx1g");
      current = setAt(global, "languages.java.jdtlsVmArgs", "-Xmx4g");
      settingsGetGlobal.mockImplementation(async () => global);
      useProject.setState({
        settings: current,
        project: { root: "/p", name: "p", settings: current } as never,
      });
    });

    it("edit the project first; Global shows and writes the global layer", async () => {
      const dialog = await openDialog("languages.java");
      expect(within(dialog).getByRole("radio", { name: "This project" })).toHaveAttribute("aria-checked", "true");
      expect(within(dialog).getByLabelText("JVM options")).toHaveValue("-Xmx4g");

      fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
      expect(within(dialog).getByLabelText("JVM options")).toHaveValue("-Xmx1g");
      expect(within(dialog).getByText(/used by new projects/)).toBeInTheDocument();

      fireEvent.change(within(dialog).getByLabelText("JVM options"), { target: { value: "-Xmx2g" } });
      await act(async () => {
        fireEvent.click(within(dialog).getByRole("button", { name: "Apply" }));
      });
      expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsVmArgs", '"-Xmx2g"']]);
    });

    it("stages shared JDT LS in the project and writes it on Apply", async () => {
      const dialog = await openDialog("languages.java");
      fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
      const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
      expect(checkbox).not.toBeChecked();
      fireEvent.click(checkbox);
      expect(checkbox).toBeChecked();
      expect(settingsSet).not.toHaveBeenCalled();
      await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
      expect(settingsSet.mock.calls).toEqual([["project", "languages.java.jdtlsShared", "true"]]);
    });

    it("keeps the global shared JDT LS preference separate from the project's override", async () => {
      global = setAt(global, "languages.java.jdtlsShared", true);
      current = setAt(global, "languages.java.jdtlsShared", false);
      useProject.setState({ settings: current });
      const dialog = await openDialog("languages.java");
      fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
      expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).not.toBeChecked();
      fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
      const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
      expect(checkbox).toBeChecked();
      fireEvent.click(checkbox);
      await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
      expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "false"]]);
    });

    it("discards a shared JDT LS toggle on Cancel", async () => {
      const dialog = await openDialog("languages.java");
      fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
      fireEvent.click(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" }));
      fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
      expect(settingsSet).not.toHaveBeenCalled();
      expect(current.languages?.java?.jdtlsShared).toBe(false);
    });

    it("disables shared JDT LS only in a native Workspace's project scope", async () => {
      useProject.setState((s) => ({
        project: { ...s.project!, workspace: { version: 1, name: "Workspace", projects: ["/p/member"] } },
      }));
      const dialog = await openDialog("languages.java");
      fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
      expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).toBeDisabled();
      expect(within(dialog).getByText(/Open a workspace member as a project/)).toBeInTheDocument();
      fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
      const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
      expect(checkbox).toBeEnabled();
      fireEvent.click(checkbox);
      await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
      expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "true"]]);
    });

    it("disables sharing for a Java language server target only in project scope", async () => {
      current = setAt(current, "languageServerTargets", { java: { target: "docker:java", server: "jdtls" } });
      useProject.setState({ settings: current });
      const dialog = await openDialog("languages.java");
      fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
      const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
      expect(checkbox).toBeDisabled();
      expect(within(dialog).getByText(/Select Local machine for the Java language server/)).toBeInTheDocument();
      fireEvent.click(within(dialog).getByRole("radio", { name: "Global" }));
      expect(checkbox).toBeEnabled();
      fireEvent.click(checkbox);
      await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
      expect(settingsSet.mock.calls).toEqual([["global", "languages.java.jdtlsShared", "true"]]);
    });

    it.each([{ java: { target: "", server: "jdtls" } }, { python: { target: "docker:python" } }])(
      "keeps sharing available when Java runs locally: %j",
      async (targets) => {
        current = setAt(current, "languageServerTargets", targets);
        useProject.setState({ settings: current });
        const dialog = await openDialog("languages.java");
        fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
        expect(within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" })).toBeEnabled();
      },
    );

    it("uses a staged project Java language server target before Apply", async () => {
      const dialog = await openDialog("languages.java");
      fireEvent.click(within(dialog).getByRole("radio", { name: "This project" }));
      const checkbox = within(dialog).getByRole("checkbox", { name: "Share JDT LS across builds" });
      expect(checkbox).toBeEnabled();
      act(() => stage("languages.servers", "project", "languageServerTargets.java.target", "docker:java"));
      expect(checkbox).toBeDisabled();
      expect(settingsSet).not.toHaveBeenCalled();
    });

    it("Settings for New Projects edits the global layer on every page", async () => {
      render(<SettingsDialog />);
      await act(async () => {
        await executeAction("file.newProjectsSettings");
      });
      const dialog = screen.getByRole("dialog", { name: "Settings for New Projects" });
      expect(within(dialog).queryByRole("radiogroup", { name: "Settings scope" })).toBeNull();
      expect(within(dialog).getByLabelText("JVM options")).toHaveValue("-Xmx1g");
      expect(within(dialog).getByLabelText("Language server JDK")).toBeInTheDocument();
      expect(within(dialog).getByText(/used by new projects/)).toBeInTheDocument();
    });
  });

  it("keeps object settings stable when child keys are staged (HTTP Proxy)", async () => {
    const seen: Array<{ mode: string; host: string }> = [];
    function Probe() {
      const [proxy] = useSetting<{ mode: string; host: string }>("proxy", "global");
      seen.push(proxy);
      return <output data-testid="proxy">{`${proxy.mode}:${proxy.host}`}</output>;
    }
    openSettings("general.httpProxy");
    const view = render(
      <PageContext.Provider value={{ pageId: "general.httpProxy", scope: "global" }}>
        <Probe />
      </PageContext.Provider>,
    );
    expect(screen.getByTestId("proxy")).toHaveTextContent("auto:");
    act(() => {
      stage("general.httpProxy", "global", "proxy.mode", "manual");
      stage("general.httpProxy", "global", "proxy.host", "127.0.0.1");
    });
    expect(screen.getByTestId("proxy")).toHaveTextContent("manual:127.0.0.1");
    expect(seen.at(-1)).toMatchObject({ mode: "manual", host: "127.0.0.1" });
    view.unmount();

    const dialog = await openDialog("general.httpProxy");
    fireEvent.click(within(dialog).getByRole("radio", { name: "Manual proxy configuration" }));
    expect(within(dialog).getByRole("radio", { name: "Manual proxy configuration" })).toBeChecked();
    fireEvent.change(within(dialog).getByLabelText("Host name"), { target: { value: "127.0.0.1" } });
    expect(within(dialog).getByLabelText("Host name")).toHaveValue("127.0.0.1");
    fireEvent.click(within(dialog).getByRole("radio", { name: "No proxy" }));
    expect(within(dialog).getByRole("radio", { name: "No proxy" })).toBeChecked();
  });

  it("survives invalid settings values", async () => {
    act(() =>
      useProject.setState({
        settings: { appearance: { theme: 42, uiFontSize: "x" }, keymapOverrides: { a: "b" } } as unknown as Settings,
      }),
    );
    const dialog = await openDialog("appearance");
    expect(within(dialog).getByRole("button", { name: "Theme" })).toHaveTextContent("Islands Light");
    expect(within(dialog).getByLabelText("UI font size")).toHaveValue("13");
  });

  it("opens Project Structure as its own standalone IDEA-style dialog instead of Settings", async () => {
    useProject.setState({ project: { name: "demo", root: "/project" } as never });
    render(
      <>
        <SettingsDialog />
        <ProjectStructureDialog />
        <MessagesHost />
      </>,
    );
    await act(async () => {
      await executeAction("file.projectStructure");
    });
    expect(useSettingsDialog.getState().open).toBe(false);
    expect(useSettingsDialog.getState().projectStructureOpen).toBe(true);
    const psDialog = screen.getByRole("dialog", { name: "Project Structure" });
    const nav = within(psDialog).getByRole("navigation", { name: "Project Structure sections" });
    expect(within(nav).getByText("Project Settings")).toBeInTheDocument();
    expect(within(nav).getByText("Platform Settings")).toBeInTheDocument();
    expect(within(nav).getByRole("button", { name: "Project" })).toHaveAttribute("aria-current", "page");
    await act(async () => {
      fireEvent.click(within(nav).getByRole("button", { name: "Modules" }));
    });
    expect(within(nav).getByRole("button", { name: "Modules" })).toHaveAttribute("aria-current", "page");
    expect(within(psDialog).getByRole("tab", { name: "Sources" })).toBeInTheDocument();
    expect(within(psDialog).getByRole("tab", { name: "Paths" })).toBeInTheDocument();
    expect(within(psDialog).getByRole("tab", { name: "Dependencies" })).toBeInTheDocument();
  });

  it("preserves pending Project Structure edits when its shortcut is invoked again", async () => {
    useProject.setState({ project: { name: "demo", root: "/project" } as never });
    render(<ProjectStructureDialog />);
    await act(async () => executeAction("file.projectStructure"));
    fireEvent.change(screen.getByLabelText("Compiler output"), { target: { value: "out/classes" } });
    await act(async () => executeAction("file.projectStructure"));
    expect(screen.getByLabelText("Compiler output")).toHaveValue("out/classes");
    await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
    expect(settingsSet).toHaveBeenCalledWith("project", "projectStructure.compilerOutput", '"out/classes"');
  });

  it("disables Project Structure controls whose settings have no execution support", async () => {
    useProject.setState({ project: { name: "demo", root: "/project" } as never });
    render(<ProjectStructureDialog />);
    await act(async () => executeAction("file.projectStructure", "modules"));
    fireEvent.click(screen.getByRole("tab", { name: "Paths" }));
    expect(screen.getByLabelText("Test output path")).toBeDisabled();
    fireEvent.click(screen.getByRole("tab", { name: "Dependencies" }));
    expect(screen.getByRole("button", { name: "Add Library" })).toBeDisabled();
    expect(screen.getByRole("button", { name: "Add Module Dependency" })).toBeDisabled();
    fireEvent.click(screen.getByRole("button", { name: "Artifacts" }));
    expect(screen.getByRole("button", { name: "JAR" })).toBeDisabled();
    expect(screen.getByRole("button", { name: "WAR" })).toBeDisabled();
  });

  it("shows the selected module's source tree", async () => {
    current = setAt(current, "projectStructure.modules", {
      service: { jdk: "", languageLevel: "", compilerOutput: "", testCompilerOutput: "", dependencies: [] },
    });
    useProject.setState({ settings: current, project: { name: "demo", root: "/project" } as never });
    render(<ProjectStructureDialog />);
    await act(async () => executeAction("file.projectStructure", "modules"));
    fireEvent.click(screen.getByRole("button", { name: /service\s*custom/ }));
    const tree = screen.getByRole("tree", { name: "Content root" });
    expect(within(tree).getByRole("treeitem")).toHaveTextContent("service");
    expect(within(tree).queryByText("demo")).toBeNull();
    fireEvent.click(screen.getByRole("tab", { name: "Paths" }));
    expect(screen.getByLabelText("Module language level")).toBeDisabled();
    expect(screen.getByLabelText("Output path")).toBeDisabled();
  });
});

describe("native Settings window root", () => {
  it("marks the window edge on Linux, whose frameless windows get no compositor shadow", () => {
    const saved = usePlatform.getState();
    usePlatform.setState({ os: "linux" });
    let view = render(<SettingsWindow />);
    let root = document.querySelector(`.${dialogStyles.window}`);
    expect(root).toHaveClass(dialogStyles.windowEdge!);
    view.unmount();
    usePlatform.setState({ os: "windows" });
    view = render(<SettingsWindow />);
    root = document.querySelector(`.${dialogStyles.window}`);
    expect(root).not.toHaveClass(dialogStyles.windowEdge!);
    view.unmount();
    usePlatform.setState(saved);
  });
});

describe("native Settings window background", () => {
  it.each([
    ["a hex frame", "#26282c", "", "#26282c"],
    ["an hsl() frame", "hsl(220, 13%, 15%)", "rgb(33, 37, 43)", "#21252b"],
    [
      "a translucent color-mix() frame",
      "color-mix(in srgb, #8040bf 80%, transparent)",
      "color(srgb 0.5 0.25 0.75 / 0.8)",
      "#8040bfcc",
    ],
  ])("sends %s as hex, the colour format the window command parses", async (_name, token, resolved, hex) => {
    const native = vi.spyOn(commands, "windowOpenSettings").mockResolvedValue({ status: "ok", data: null });
    const computed = vi
      .spyOn(globalThis, "getComputedStyle")
      .mockReturnValue({ getPropertyValue: () => token, color: resolved } as unknown as CSSStyleDeclaration);
    try {
      await executeAction("file.settings", "appearance");
      expect(native).toHaveBeenCalledWith("appearance", false, hex);
      expect(useSettingsDialog.getState().open).toBe(false);
    } finally {
      computed.mockRestore();
      native.mockRestore();
    }
  });
});

it("uses the attached primary name for run-target paths", async () => {
  useProject.setState({ project: { name: "primary", displayName: "primary, other", root: "/primary" } as never });
  await openDialog("build.runTargets");
  fireEvent.click(
    within(screen.getByRole("toolbar", { name: "Run targets actions" })).getByRole("button", { name: "Add" }),
  );
  expect(screen.getByPlaceholderText("~/primary")).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Type" }));
  fireEvent.click(screen.getByRole("option", { name: "Docker" }));
  expect(screen.getByPlaceholderText("/workspaces/primary")).toBeInTheDocument();
});

it("uses the primary name for module labels and artifact defaults", async () => {
  useProject.setState({ project: { name: "primary", displayName: "primary, other", root: "/primary" } as never });
  render(<ProjectStructureDialog />);
  await act(async () => executeAction("file.projectStructure", "modules"));
  expect(screen.getByRole("button", { name: /primary\s*custom/ })).toBeInTheDocument();
  expect(screen.getByRole("tree", { name: "Content root" })).toHaveTextContent("primary");
  fireEvent.click(screen.getByRole("button", { name: "Artifacts" }));
  // Packaging is pending, but its default generator must still use the primary name.
  screen.getByRole("button", { name: "JAR" }).closest("fieldset")!.removeAttribute("disabled");
  fireEvent.click(screen.getByRole("button", { name: "JAR" }));
  expect(screen.getByLabelText("Name")).toHaveValue("primary:jar");
  expect(screen.getByLabelText("Output directory")).toHaveValue("out/artifacts/primary_jar");
});