Compare commits

..
Author SHA1 Message Date
l0ng-ai 9415584b54 fix(debugger): align the Python table viewer 2026-11-23 11:01:18 +08:00
30 changed files with 197 additions and 1140 deletions

No files matched your search

+3 -23
View File
@@ -102,44 +102,24 @@ jobs:
name: Rust (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-22.04, windows-latest]
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
- uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
- name: Persistent Cargo target dir
if: runner.environment == 'self-hosted'
shell: bash
run: |
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
if [ "${size:-0}" -gt 40000 ]; then
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- name: Linux deps
if: runner.os == 'Linux'
-71
View File
@@ -1,71 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function show(page: Page, action: string) {
await page.evaluate(async (action) => {
const actions = "/src/platform/actions.ts";
if (!(await (await import(/* @vite-ignore */ actions)).executeAction(action))) throw Error(action);
}, action);
}
test("analysis scope fields align with their radio choices and retain their values", async ({ workbench: page }) => {
await page.evaluate(async () => {
const search = "/src/platform/search.ts";
(await import(/* @vite-ignore */ search)).saveCustomScopes([
{ name: "Frontend", pattern: "file:src//*" },
{ name: "Tests", pattern: "file:tests//*" },
]);
});
await show(page, "analyze.inspectCode");
const dialog = page.getByRole("dialog", { name: "Specify Inspection Scope" });
const scope = dialog.getByRole("group", { name: "Scope" });
const directory = scope.getByRole("textbox", { name: "Directory" });
const custom = scope.getByRole("button", { name: "Custom scope", exact: true });
const radio = scope.getByRole("radio", { name: "Module or directory" });
const label = scope.getByText("Module or directory", { exact: true });
await radio.check();
const path = (await directory.boundingBox())!;
const choice = (await label.boundingBox())!;
expect(path.y + path.height / 2).toBeCloseTo(choice.y + choice.height / 2, 0);
await directory.fill("/dev/acme-api/src");
await expect(custom).toBeDisabled();
await scope.getByRole("radio", { name: "Custom scope", exact: true }).check();
await expect(directory).toBeDisabled();
expect((await custom.boundingBox())!.x).toBeCloseTo(path.x, 0);
await custom.click();
await page.getByRole("option", { name: /^Tests/ }).click();
await expect(custom).toContainText("Tests");
await radio.check();
await expect(directory).toHaveValue("/dev/acme-api/src");
await scope.getByRole("radio", { name: "Custom scope", exact: true }).check();
await expect(custom).toContainText("Tests");
await page.setViewportSize({ width: 400, height: 640 });
const stacked = (await directory.boundingBox())!;
const customBox = (await custom.boundingBox())!;
const radioBox = (await label.boundingBox())!;
const next = (await scope.getByText("Current file", { exact: true }).boundingBox())!;
expect(stacked.y).toBeGreaterThan(radioBox.y + radioBox.height);
expect(stacked.y + stacked.height).toBeLessThan(next.y);
expect(stacked.x).toBeCloseTo(customBox.x, 0);
expect(await scope.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
for (const [action, title] of [
["code.cleanup", "Run Code Cleanup"],
["analyze.locateDuplicates", "Locate Duplicates"],
["find.structural", "Structural Search"],
["find.replaceStructural", "Structural Replace"],
] as const) {
test(`${title} keeps directory options with their scope choice`, async ({ workbench: page }) => {
await show(page, action);
const dialog = page.getByRole("dialog", { name: title });
const scope = dialog.getByRole("group", { name: "Scope" });
const directory = scope.getByRole("textbox", { name: "Directory" });
await expect(directory).toBeDisabled();
await scope.getByRole("radio", { name: "Module or directory" }).check();
await expect(directory).toBeEnabled();
await expect(scope.getByRole("button", { name: "Browse…" })).toBeEnabled();
});
}
-78
View File
@@ -3,7 +3,6 @@
* with its frames and variables, and stepping and resuming go back to the adapter. The adapter is
* stubbed at the IPC layer; `crates/ide-dap/tests` drives real ones.
*/
import type { JvmMemoryResult } from "../src/platform/ipc";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
@@ -115,83 +114,6 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
});
test("Memory gives class filtering the available toolbar width and exposes changed-only filtering", async ({
workbench: page,
}) => {
const rows = [
{ name: "OrderCache", instances: 64, deltaInstances: 12 },
{ name: "OrderRepository", instances: 16, deltaInstances: 0 },
].map((row) => ({ ...row, bytes: row.instances * 16, deltaBytes: null, module: null, ambiguous: false }));
const result: JvmMemoryResult = {
status: "ready",
snapshot: {
rows,
totalInstances: 80,
totalBytes: 1280,
javaVersion: "21",
takenWhileSuspended: true,
hasBaseline: true,
elapsedMs: 5,
source: "debugger",
},
};
await stubDesktop(page);
await page.evaluate(
async ({ result, id }) => {
const caps = { jvmMemory: true, jvmHeap: true };
window.__ipc.handlers.debug_capabilities = () => caps;
window.__ipc.handlers.debug_jvm_memory_classes = () => result;
const debugPath = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugPath);
adoptSession(id, { adapter: "java-debug", name: "Billing Service", status: "paused", caps });
const dockPath = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ dockPath);
layout.moveToolWindow("debug", "bottom");
layout.setToolWindowSize("bottom", 300);
layout.showToolWindow("debug", true);
},
{ result, id: SESSION },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Memory" }).click();
const toolbar = debug.getByRole("toolbar", { name: "Memory", exact: true });
const filter = toolbar.getByRole("textbox", { name: "Filter classes" });
const options = toolbar.getByRole("button", { name: "View Options" });
const grid = debug.getByRole("grid", { name: "Memory", exact: true });
await expect(grid.getByText("OrderRepository", { exact: true })).toBeVisible();
expect((await filter.boundingBox())!.width).toBeGreaterThan((await toolbar.boundingBox())!.width / 2);
await page.evaluate(async () => {
const dockPath = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ dockPath);
layout.moveToolWindow("debug", "right");
layout.setToolWindowSize("right", 330);
});
await expect.poll(async () => (await toolbar.boundingBox())!.width).toBeCloseTo(330, 0);
const bar = (await toolbar.boundingBox())!;
const gear = (await options.boundingBox())!;
const input = (await filter.boundingBox())!;
expect(input.width).toBeGreaterThan(bar.width / 2);
expect(input.x + input.width).toBeLessThan(gear.x);
expect(gear.x + gear.width).toBeLessThanOrEqual(bar.x + bar.width);
await filter.fill("cache");
await expect(grid.getByText("OrderRepository", { exact: true })).toBeHidden();
await toolbar.getByRole("button", { name: "Clear", exact: true }).click();
await expect(grid.getByText("OrderRepository", { exact: true })).toBeVisible();
await options.press("Enter");
const changed = page.getByRole("menuitemcheckbox", { name: "Changed only" });
await expect(changed).not.toBeChecked();
await changed.press("Enter");
await expect(grid.getByText("OrderRepository", { exact: true })).toBeHidden();
await expect(options).toHaveAttribute("aria-pressed", "true");
await expect(options).toBeFocused();
await options.press("Enter");
await expect(changed).toBeChecked();
});
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 580, height: 420 });
await stubDesktop(page);
-81
View File
@@ -1,81 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openEditorTabsSettings(page: Page) {
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("file.settings", "editor.general.editorTabs");
});
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog.getByRole("region", { name: "Closing Policy", exact: true })).toBeVisible();
return dialog;
}
test("Editor Tabs aligns appearance fields and stacks closing choices at both widths", async ({ workbench: page }) => {
const settings = await openEditorTabsSettings(page);
const appearance = settings.getByRole("region", { name: "Appearance", exact: true });
const placement = appearance.getByRole("button", { name: "Tab placement", exact: true });
const closePosition = appearance.getByRole("button", { name: "Close button position", exact: true });
const closing = settings.getByRole("region", { name: "Closing Policy", exact: true });
const limit = closing.getByRole("textbox", { name: "Tab limit", exact: true });
const footer = settings.getByRole("button", { name: "OK", exact: true });
for (const width of [1100, 580]) {
await page.setViewportSize({ width, height: 760 });
const placementBox = (await placement.boundingBox())!;
const closeBox = (await closePosition.boundingBox())!;
expect(Math.abs(placementBox.x - closeBox.x)).toBeLessThanOrEqual(1);
expect(Math.abs(placementBox.width - closeBox.width)).toBeLessThanOrEqual(1);
await expect(placement).toBeInViewport();
await expect(limit).toHaveValue("30");
for (const name of ["When the tab limit is reached", "When the current tab is closed, activate"]) {
const choices = closing.getByRole("radiogroup", { name, exact: true }).getByRole("radio");
const first = (await choices.first().boundingBox())!;
const last = (await choices.last().boundingBox())!;
expect(Math.abs(first.x - last.x)).toBeLessThanOrEqual(1);
expect(last.y).toBeGreaterThan(first.y + first.height);
expect(last.x + last.width).toBeLessThanOrEqual(width);
}
await expect(footer).toBeInViewport();
}
});
test("Editor Tabs keeps row and overflow choices independently selected and keyboard operable", async ({
workbench: page,
}) => {
const settings = await openEditorTabsSettings(page);
const group = settings.getByRole("radiogroup", { name: "Show tabs in", exact: true });
const one = group.getByRole("radio", { name: /^One row/ });
const multiple = group.getByRole("radio", { name: "Multiple rows", exact: true });
const scroll = group.getByRole("radio", { name: "Scroll the tabs panel", exact: true });
const squeeze = group.getByRole("radio", { name: "Squeeze tabs", exact: true });
await expect(one).toBeChecked();
await expect(scroll).toBeChecked();
const oneBox = (await one.boundingBox())!;
const scrollBox = (await scroll.boundingBox())!;
const multipleBox = (await multiple.boundingBox())!;
expect(scrollBox.x).toBeGreaterThan(oneBox.x + 8);
expect(scrollBox.y).toBeGreaterThan(oneBox.y);
expect(Math.abs(multipleBox.x - oneBox.x)).toBeLessThanOrEqual(1);
expect(multipleBox.y).toBeGreaterThan(scrollBox.y);
await scroll.press("ArrowDown");
await expect(squeeze).toBeFocused();
await expect(squeeze).toBeChecked();
await expect(one).toBeChecked();
await one.press("ArrowDown");
await expect(multiple).toBeFocused();
await expect(multiple).toBeChecked();
await expect(squeeze).toBeDisabled();
await expect(squeeze).toBeChecked();
await multiple.press("ArrowUp");
await expect(one).toBeChecked();
await expect(squeeze).toBeEnabled();
await settings.getByRole("button", { name: "OK", exact: true }).click();
const reopened = await openEditorTabsSettings(page);
await expect(reopened.getByRole("radio", { name: /^One row/ })).toBeChecked();
await expect(reopened.getByRole("radio", { name: "Squeeze tabs", exact: true })).toBeChecked();
});
-56
View File
@@ -1,56 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function editMacros(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
if (!(await (await import(/* @vite-ignore */ actions)).executeAction("macro.edit"))) throw Error("Edit Macros");
});
}
test("Edit Macros keeps a balanced, resizable split for names and recorded steps", async ({ workbench: page }) => {
await page.evaluate(async () => {
const model = "/src/features/macros/model.ts";
const { saveMacro } = await import(/* @vite-ignore */ model);
saveMacro("Insert comment", [{ kind: "text", text: "Review this block" }]);
saveMacro("Wrap selection", [
{ kind: "key", key: "Home" },
{ kind: "text", text: "beginProcessingCurrentSelectionImmediately();".repeat(6) },
{ kind: "key", key: "End" },
]);
});
await editMacros(page);
const editor = page.getByRole("dialog", { name: "Edit Macros", exact: true });
const macros = editor.getByRole("listbox", { name: "Macros" });
const steps = editor.getByRole("list", { name: "Recorded steps" });
const options = editor.getByRole("toolbar", { name: "Macros" });
const divider = editor.getByRole("separator", { name: "Macros" });
const [initial, stepsWidth] = await editor.evaluate((dialog) => [
dialog.querySelector('[role="listbox"]')!.getBoundingClientRect().width,
dialog.querySelector("ol")!.getBoundingClientRect().width,
]);
expect(Math.abs(initial - stepsWidth)).toBeLessThanOrEqual(1);
await expect(macros).toBeFocused();
expect((await steps.boundingBox())!.height).toBeGreaterThan(260);
expect((await options.boundingBox())!.y).toBeLessThan((await macros.boundingBox())!.y);
await macros.getByRole("option", { name: "Wrap selection" }).click();
await expect(steps.getByText("Press Home")).toBeVisible();
await divider.press("ArrowRight");
await expect.poll(async () => (await macros.boundingBox())!.width).toBeGreaterThan(initial + 5);
const resized = (await macros.boundingBox())!.width;
await editor.locator("[data-dialog-footer]").getByRole("button", { name: "Close" }).click();
await editMacros(page);
await expect.poll(async () => (await macros.boundingBox())!.width).toBeCloseTo(resized, 0);
await page.setViewportSize({ width: 400, height: 620 });
await macros.getByRole("option", { name: "Wrap selection" }).click();
expect(await steps.evaluate((list) => list.scrollWidth - list.clientWidth)).toBeLessThanOrEqual(1);
await options.getByRole("button", { name: "Rename Macro" }).click();
const rename = page.getByRole("dialog", { name: "Rename Macro", exact: true });
await rename.getByRole("textbox").fill("Wrap text");
await rename.getByRole("button", { name: "Rename", exact: true }).click();
await expect(macros.getByRole("option", { name: "Wrap text" })).toBeVisible();
await expect(steps.getByText("Press Home")).toBeVisible();
});
-74
View File
@@ -1,74 +0,0 @@
import type { MavenModel } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const maven: MavenModel = {
projects: [
{
pom: "pom.xml",
dir: "",
groupId: "dev.acme",
artifactId: "billing",
version: "1.0.0",
packaging: "jar",
displayName: "Billing",
parent: null,
modules: [],
aggregated: false,
plugins: [
{
groupId: "org.apache.maven.plugins",
artifactId: "maven-surefire-plugin",
version: "3.2.5",
prefix: "surefire",
goals: ["test"],
},
],
dependencies: [],
profiles: [],
javaVersion: 21,
command: "mvn",
options: [],
env: {},
},
],
profiles: [],
syncedAt: 1,
stale: false,
syncError: null,
};
test("Maven plugin rows give the name priority over coordinates in narrow docks", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (maven) => {
window.__ipc.handlers.build_model = () => ({ maven, gradle: [] });
const buildModule = "/src/features/build-tools/store.ts";
const { loadModel, setExpanded } = await import(/* @vite-ignore */ buildModule);
await loadModel();
setExpanded("maven", new Set(["mvn:pom.xml", "mvn:pom.xml:plugins"]));
const dockModule = "/src/workbench/toolwindows/store.ts";
const { showToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ dockModule);
showToolWindow("maven", true);
setToolWindowSize("right", 190);
}, maven);
const tree = page.getByRole("tree", { name: "Maven projects" });
const coordinates = "(org.apache.maven.plugins:maven-surefire-plugin:3.2.5)";
const plugin = tree.getByRole("treeitem", { name: `surefire ${coordinates}`, exact: true });
const name = plugin.getByText("surefire", { exact: true });
const metadata = plugin.getByText(coordinates, { exact: true });
await expect(name).toBeVisible();
await expect(metadata).toHaveAttribute("title", coordinates);
const fit = (el: Element) => {
const range = document.createRange();
range.selectNodeContents(el);
return range.getBoundingClientRect().width <= el.getBoundingClientRect().width;
};
expect(await name.evaluate(fit)).toBe(true);
expect(await metadata.evaluate(fit)).toBe(false);
expect(await metadata.evaluate((el) => getComputedStyle(el).color)).not.toBe(
await name.evaluate((el) => getComputedStyle(el).color),
);
await plugin.locator("[data-tree-toggle]").click();
await expect(tree.getByRole("treeitem", { name: "surefire:test", exact: true })).toBeVisible();
});
+1 -8
View File
@@ -29,14 +29,7 @@ test("Find in Files keeps the scope list and pattern editor usable in a narrow w
expect((await list.boundingBox())!.x).toBeLessThan((await name.boundingBox())!.x);
await page.setViewportSize({ width: 460, height: 530 });
// The dialog relays out over a few frames after the resize; measure once it has settled.
let fields = (await pattern.boundingBox())!;
await expect(async () => {
const previous = fields.y;
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
fields = (await pattern.boundingBox())!;
expect(fields.y).toBe(previous);
}).toPass();
const fields = (await pattern.boundingBox())!;
expect(fields.y).toBeGreaterThanOrEqual((await list.boundingBox())!.y + (await list.boundingBox())!.height);
expect(fields.width).toBeGreaterThan(250);
await list.evaluate((el) => (el.scrollTop = el.scrollHeight));
+1 -4
View File
@@ -121,10 +121,7 @@ test("Git Log settings group display and column options with aligned checkboxes"
for (const width of [1000, 520]) {
await page.setViewportSize({ width, height: 760 });
// Read both rows together once the dialog has finished opening and relaid out.
await expect
.poll(async () => Math.abs((await tagNames.boundingBox())!.x - (await hash.boundingBox())!.x))
.toBeLessThan(0.5);
expect((await tagNames.boundingBox())!.x).toBeCloseTo((await hash.boundingBox())!.x, 0);
}
await expect(hash).not.toBeChecked();
-81
View File
@@ -1,81 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openDialog(page: Page, id: "find.structural" | "find.replaceStructural") {
await stubDesktop(page);
await page.evaluate(async (id) => {
window.__ipc.handlers.structural_languages = () => [
{ id: "java", name: "Java" },
{ id: "typescript", name: "TypeScript" },
];
window.__ipc.handlers.structural_validate = () => null;
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction(id);
}, id);
}
test("Structural Search puts language selection beside the taller template editor", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1080, height: 720 });
await openDialog(page, "find.structural");
const dialog = page.getByRole("dialog", { name: "Structural Search" });
const editor = dialog.getByRole("textbox", { name: "Search template" });
const label = dialog.locator("label").filter({ hasText: /^Search template$/ });
const language = dialog.getByRole("button", { name: "Language", exact: true });
await expect(editor).toBeFocused();
await expect(language).toHaveText("Java");
const { x, y, width, height } = (await editor.boundingBox())!;
const caption = (await label.boundingBox())!;
const picker = (await language.boundingBox())!;
expect(Math.abs(caption.y + caption.height / 2 - (picker.y + picker.height / 2))).toBeLessThanOrEqual(1);
expect(Math.abs(caption.x - x)).toBeLessThanOrEqual(1);
expect(Math.abs(picker.x + picker.width - (x + width))).toBeLessThanOrEqual(1);
expect(y - (picker.y + picker.height)).toBeLessThanOrEqual(6);
expect(Math.abs(height - 150)).toBeLessThanOrEqual(1);
await language.click();
await page.getByRole("option", { name: "TypeScript" }).click();
await editor.fill("console.log($value$)");
await expect
.poll(() => ipcCalls(page, "structural_validate"))
.toContainEqual({
query: { language: "typescript", pattern: "console.log($value$)", replacement: null, maxMatches: 0 },
});
await expect(dialog.getByRole("button", { name: "Find", exact: true })).toBeEnabled();
});
test("Structural Replace uses editor typography and fits the template controls in a narrow window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 400, height: 620 });
await openDialog(page, "find.replaceStructural");
const dialog = page.getByRole("dialog", { name: "Structural Replace" });
const search = dialog.getByRole("textbox", { name: "Search template" });
const replacement = dialog.getByRole("textbox", { name: "Replace template" });
await expect(search).toBeFocused();
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { settings, project } = useProject.getState();
const current = settings ?? project?.settings;
if (!current) throw new Error("Expected project settings");
useProject.setState({
settings: { ...current, editor: { ...current.editor, fontFamily: "Consolas", fontSize: 17, lineHeight: 26 } },
});
});
for (const template of [search, replacement]) {
await expect(template).toHaveCSS("font-family", /^Consolas,/);
await expect(template).toHaveCSS("font-size", "17px");
await expect(template).toHaveCSS("line-height", "26px");
const box = (await template.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(400);
expect(Math.abs(box.height - 105)).toBeLessThanOrEqual(1);
}
await expect(dialog.getByRole("radio", { name: "Whole project" })).toBeInViewport();
await replacement.fill("Objects.equals($a$, $b$)");
await expect(replacement).toHaveValue("Objects.equals($a$, $b$)");
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport();
});
-95
View File
@@ -1,95 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
async function setEditorMetrics(page: Page, fontSize: number, lineHeight: number) {
await page.evaluate(
async ({ fontSize, lineHeight }) => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { settings, project } = useProject.getState();
const current = settings ?? project?.settings;
if (!current) throw new Error("Expected project settings");
useProject.setState({ settings: { ...current, editor: { ...current.editor, fontSize, lineHeight } } });
},
{ fontSize, lineHeight },
);
}
async function openResults(page: Page) {
await page.setViewportSize({ width: 1120, height: 720 });
await stubDesktop(page);
await setEditorMetrics(page, 20, 34);
await page.evaluate(async () => {
const lines = Array.from({ length: 1240 }, () => "");
lines[1233] = " record(orderTotal);";
lines[1237] = " return orderTotal;";
window.__ipc.handlers.fs_read_text = () => lines.join("\n");
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("find.showUsageResults", {
symbol: "orderTotal",
locations: [
{
path: "/dev/acme-api/src/orderTotals.ts",
range: { start: { line: 1233, col: 9 }, end: { line: 1233, col: 19 } },
},
{
path: "/dev/acme-api/src/orderTotals.ts",
range: { start: { line: 1237, col: 9 }, end: { line: 1237, col: 19 } },
},
],
});
});
const view = page.getByRole("region", { name: "Find Usages", exact: true });
await view.getByRole("treeitem").filter({ hasText: "1234" }).click();
const preview = view.getByRole("region", { name: "Preview", exact: true });
await expect(preview.locator("mark")).toHaveCount(2);
return { view, preview };
}
test("Find Usages preview follows editor line height and fits long line numbers", async ({ workbench: page }) => {
const { preview } = await openResults(page);
await expect(preview).toHaveCSS("font-size", "20px");
await expect(preview).toHaveCSS("line-height", "34px");
const number = preview.getByText("1234", { exact: true });
const gutter = await number.evaluate((element) => {
const range = document.createRange();
range.selectNodeContents(element);
const text = range.getBoundingClientRect();
const box = element.getBoundingClientRect();
return { textInset: text.left - box.left, width: box.width };
});
expect(gutter.textInset).toBeGreaterThanOrEqual(1);
await expect(number).toBeInViewport({ ratio: 0.98 });
expect((await preview.getByText("999", { exact: true }).boundingBox())!.width).toBeCloseTo(gutter.width, 0);
await page.setViewportSize({ width: 560, height: 720 });
await setEditorMetrics(page, 20, 39);
await expect(preview).toHaveCSS("line-height", "39px");
await expect(number).toBeInViewport({ ratio: 0.98 });
});
test("Find Usages starts with equal panes and keeps a separate saved size for each orientation", async ({
workbench: page,
}) => {
const { view } = await openResults(page);
const divider = view.locator('[id="usages-preview-split"]').getByRole("separator");
await expect(divider).toHaveAttribute("aria-valuenow", "50");
await divider.press("ArrowRight");
await expect(divider).not.toHaveAttribute("aria-valuenow", "50");
const horizontal = (await divider.getAttribute("aria-valuenow"))!;
await page.setViewportSize({ width: 560, height: 720 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(divider).toHaveAttribute("aria-valuenow", "50");
await divider.press("ArrowDown");
await expect(divider).not.toHaveAttribute("aria-valuenow", "50");
const vertical = (await divider.getAttribute("aria-valuenow"))!;
await page.setViewportSize({ width: 1120, height: 720 });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(divider).toHaveAttribute("aria-valuenow", horizontal);
await page.setViewportSize({ width: 560, height: 720 });
await expect(divider).toHaveAttribute("aria-valuenow", vertical);
});
-3
View File
@@ -1,3 +0,0 @@
.env
.env.*
!.env.example
-113
View File
@@ -1,113 +0,0 @@
# Self-Hosted GitHub Actions Runners
Runs _N_ persistent, isolated GitHub Actions runners via Docker Compose on a single Docker named volume (`runner-persist`) without requiring repository admin Personal Access Tokens.
In `.github/workflows/ci.yml`, the Linux leg of `Rust (${{ matrix.os }})` routes to `["self-hosted", "openidea-selfhosted"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, use GitHub-hosted runners.
> **Availability requirement:** GitHub Actions `runs-on` cannot fall back to GitHub-hosted runners when no matching self-hosted runner is online; jobs stay queued until one connects. Set `SELFHOSTED_RUNNERS=true` (**Settings → Secrets and variables → Actions → Variables**) only once the runners are up, and delete it before taking the host down.
## Security Constraints
Because this repository is public and these runners retain persistent build caches and credentials across runs, workflows and runner hosts must follow these rules:
- **Trusted events only:** Route jobs to `openidea-selfhosted` only for `push`, `merge_group`, `workflow_dispatch`, or `pull_request` events where `github.event.pull_request.head.repo.full_name == github.repository`. Fork pull requests must stay on GitHub-hosted runners so untrusted code never reaches persistent caches or runner credentials.
- **Read-only `GITHUB_TOKEN`:** Jobs targeting `openidea-selfhosted` must set `permissions: { contents: read }` (least privilege).
- **No secret-bearing jobs:** Never pass repository or organization `secrets.*` to jobs running on `openidea-selfhosted`.
- **Never feed releases:** Artifacts or outputs from `openidea-selfhosted` runners must never be uploaded for consumption by release or nightly workflows.
- **Container isolation:** Jobs run as the `runner` user (`RUN_AS_ROOT=false`) from a pinned image tag and digest, but the image grants that user passwordless `sudo` (CI needs it for `apt-get`), so a job can become root inside its container. The container is the isolation boundary: never mount `/var/run/docker.sock` or host directories into it, and never run it `--privileged`.
- **Shared build state:** Same-repo pull requests and `main` share each slot's Cargo target directory, so only collaborators you trust with `main`'s build should push branches to this repository.
- **Network isolation:** Run the Docker host on an isolated network segment away from sensitive devices or internal services.
## How It Works
On startup, each container replica acquires an exclusive `flock` on a numeric slot (`1..N`) before dropping privileges to the `runner` user, isolating its persistent state under `/persist/slot-<N>/`:
| Path | Purpose |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `runner-data/` | Saved `.runner` and `.credentials` reused across container restarts (`CONFIGURED_ACTIONS_RUNNER_FILES_DIR`) |
| `work/` | Runner workspace and repository checkouts (`RUNNER_WORKDIR`) |
| `cargo-target/` | Pre-compiled Rust build artifacts (`CARGO_TARGET_DIR`), kept outside checkouts so `actions/checkout` cleanup does not wipe it |
| `cargo/` | Cargo crate registry and git cache (`CARGO_HOME`) |
| `rustup/` | Installed Rust toolchains (`RUSTUP_HOME`) |
| `pnpm-store/` | Content-addressable `pnpm` store on the same filesystem as `work/` for fast hardlinks into `node_modules` |
| `toolcache/` | Tools cached by `actions/setup-*` (`/opt/hostedtoolcache`) |
| `cache/` | General `/home/runner/.cache` directory |
All slots also share `/persist/shared/npm-cache` for downloaded npm tarballs.
## Prerequisites (First-Time Registration Only)
Ask a repository admin to generate **one** 1-hour registration token from:
> **GitHub Repository → Settings → Actions → Runners → New self-hosted runner**
A single registration token can register multiple runner slots within its 1-hour validity window. Once registered, each slot saves its own runner credentials and reconnects across restarts without needing a token again.
## Quick Start
Run all commands from `scripts/selfhost-runner/`:
1. **Initial registration** (registers slots `1..4` and saves credentials):
```bash
RUNNER_TOKEN=<one-time-token> docker compose up -d
```
2. **Normal start, restart, or recreate** (no token needed once slots are registered):
```bash
docker compose up -d
docker compose restart
```
3. **Scale down** (for example `4` → `2`):
```bash
RUNNER_COUNT=2 docker compose up -d
```
Docker Compose does not guarantee which container replicas it removes, so scaling `4` → `2` may leave slots `3` and `4` running rather than `1` and `2`. Stopped slots keep their saved credentials and caches on disk and will be reclaimed on the next restart or scale-up.
4. **Scale up** (for example `4` → `6`):
- If slots `5..6` were previously registered:
```bash
RUNNER_COUNT=6 docker compose up -d
```
- If slots `5..6` have never been registered:
```bash
RUNNER_COUNT=6 RUNNER_TOKEN=<new-token> docker compose up -d
```
## Configuration
You can pass variables on the command line or place them in a local `.env` file in this directory (git-ignored):
| Variable | Default | Description |
| -------------------- | ------------------------------------- | ---------------------------------------------------------------------- |
| `RUNNER_COUNT` | `4` | Number of concurrent runner replicas |
| `RUNNER_NAME_PREFIX` | `openidea-runner` | Runner name prefix; registers as `<prefix>-1`, `<prefix>-2`, … |
| `RUNNER_LABELS` | `openidea-selfhosted` | Comma-separated labels attached to each runner |
| `REPO_URL` | `https://github.com/l0ng-ai/openidea` | Target GitHub repository URL |
| `RUNNER_TOKEN` | _(empty)_ | One-time registration token (required only when registering new slots) |
## Troubleshooting & Tips
- **Offline expiry (> 14 days) or deleted runner:** GitHub automatically removes runners that stay offline for more than 14 days. To clear a stale slot `<N>` and re-register it:
```bash
docker compose run --rm --entrypoint /bin/bash github-runner \
-c "rm -rf /persist/slot-<N>/runner-data/*"
RUNNER_TOKEN=<new-token> docker compose up -d
```
- **Full reset** (wipes all saved runner credentials and cached build artifacts):
```bash
docker compose down -v
```
- **Workflow caching tips:** `CARGO_TARGET_DIR` persists automatically across runs; CI enables incremental compilation on these runners and clears a slot's target directory once it exceeds 40 GB. To also preserve in-repo `node_modules/` across runs without re-linking, pass `clean: false` to `actions/checkout` (otherwise `pnpm install` quickly re-hardlinks packages from `pnpm-store/`).
@@ -1,70 +0,0 @@
# Self-hosted GitHub Actions runners (persistent & scalable).
# See README.md in this directory for setup, security constraints, scaling, and troubleshooting.
services:
github-runner:
image: myoung34/github-runner:2.338.2-ubuntu-jammy@sha256:9944eb7fe15cff8f31ce6389a1cd39f5fb32627f56bdfa8a21fb27e56e99fa1a
restart: unless-stopped
deploy:
replicas: ${RUNNER_COUNT:-4}
environment:
RUNNER_SCOPE: repo
REPO_URL: ${REPO_URL:-https://github.com/l0ng-ai/openidea}
# Only needed the first time a new slot registers; registered slots reuse saved credentials.
RUNNER_TOKEN: ${RUNNER_TOKEN:-}
RUNNER_NAME_PREFIX: ${RUNNER_NAME_PREFIX:-openidea-runner}
LABELS: ${RUNNER_LABELS:-openidea-selfhosted}
DISABLE_AUTOMATIC_DEREGISTRATION: "true"
RUN_AS_ROOT: "false"
# Claim an exclusive numeric slot (1..N) via flock so each replica gets its own
# persistent runner credentials, workspace, Cargo target/home, rustup, pnpm store, and toolcache.
entrypoint:
- /bin/bash
- -ec
- |
mkdir -p /persist/slots /persist/shared/npm-cache /home/runner
SLOT=1
while true; do
exec 99>"/persist/slots/slot-$${SLOT}.lock"
if flock -n 99; then break; fi
SLOT=$$((SLOT + 1))
done
SLOT_DIR="/persist/slot-$${SLOT}"
mkdir -p "$${SLOT_DIR}"/{runner-data,work,cargo,cargo-target,rustup,pnpm-store,cache,toolcache}
if [[ ! -f "$${SLOT_DIR}/runner-data/.runner" && -z "$${RUNNER_TOKEN:-}" ]]; then
echo "ERROR: Slot $${SLOT} ($${RUNNER_NAME_PREFIX:-openidea-runner}-$${SLOT}) is not registered yet; set RUNNER_TOKEN to register it." >&2
exit 1
fi
RUNNER_UID="$$(id -u runner)"
RUNNER_GID="$$(id -g runner)"
if [[ "$$(stat -c '%u' /persist/shared/npm-cache)" != "$${RUNNER_UID}" ]]; then
chown -R "$${RUNNER_UID}:$${RUNNER_GID}" /persist/shared/npm-cache
fi
if [[ "$$(stat -c '%u' "$${SLOT_DIR}")" != "$${RUNNER_UID}" ]]; then
chown -R "$${RUNNER_UID}:$${RUNNER_GID}" "$${SLOT_DIR}"
fi
chown "$${RUNNER_UID}:$${RUNNER_GID}" /persist/shared "$${SLOT_DIR}" "$${SLOT_DIR}"/{runner-data,work,cargo,cargo-target,rustup,pnpm-store,cache,toolcache}
rm -rf /opt/hostedtoolcache /home/runner/.cache
ln -s "$${SLOT_DIR}/toolcache" /opt/hostedtoolcache
ln -s "$${SLOT_DIR}/cache" /home/runner/.cache
chown -h "$${RUNNER_UID}:$${RUNNER_GID}" /opt/hostedtoolcache /home/runner/.cache
export CONFIGURED_ACTIONS_RUNNER_FILES_DIR="$${SLOT_DIR}/runner-data"
export RUNNER_NAME="$${RUNNER_NAME_PREFIX:-openidea-runner}-$${SLOT}"
export RUNNER_WORKDIR="$${SLOT_DIR}/work"
export CARGO_HOME="$${SLOT_DIR}/cargo"
export RUSTUP_HOME="$${SLOT_DIR}/rustup"
export CARGO_TARGET_DIR="$${SLOT_DIR}/cargo-target"
export npm_config_store_dir="$${SLOT_DIR}/pnpm-store"
export npm_config_cache="/persist/shared/npm-cache"
export PATH="$${CARGO_HOME}/bin:$${PATH}"
exec /entrypoint.sh "$$@"
- --
command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]
volumes:
- runner-persist:/persist
volumes:
runner-persist:
+20 -55
View File
@@ -161,51 +161,34 @@
padding: 14px;
}
.scope {
container: analysis-scope / inline-size;
min-inline-size: 0;
display: flex;
flex-direction: column;
gap: var(--space-0-5);
margin: 0;
padding: 0;
border: 0;
}
.scopeOptions {
display: grid;
grid-template-columns: fit-content(45%) minmax(0, 1fr);
align-items: center;
gap: var(--space-0-5) var(--space-2);
}
.fieldLabel {
padding: 0 0 4px;
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.radioRow {
grid-column: 1 / -1;
min-width: 0;
padding-block: var(--space-0-5);
overflow-wrap: anywhere;
}
.scopeWithField {
grid-column: 1;
}
.scopeControl {
grid-column: 2;
display: flex;
align-items: center;
gap: var(--space-2);
padding: 3px 0;
color: var(--fg);
cursor: default;
}
.radioRow input {
margin: 0;
accent-color: var(--accent);
}
.dirRow {
display: flex;
gap: var(--space-1-5);
min-width: 0;
}
.scopeControl > button:last-child {
flex: none;
}
@container analysis-scope (max-width: 336px) {
.scopeOptions {
grid-template-columns: minmax(0, 1fr);
}
.scopeControl {
grid-column: 1;
padding-inline-start: calc(16px + var(--space-2));
margin-block-end: var(--space-1);
}
padding: 4px 0 0 22px;
}
.grow {
flex: 1;
@@ -231,39 +214,21 @@
flex: 1 1 12ch;
min-width: 0;
}
.templateSection {
display: flex;
flex-direction: column;
gap: var(--space-1);
color: var(--fg);
font-size: var(--fs-ui);
}
.templateHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
}
.languageSelect {
max-width: 50%;
min-width: 180px;
}
.template {
width: 100%;
height: clamp(96px, 24vh, 150px);
min-height: 50px;
min-height: 96px;
resize: vertical;
padding: var(--space-1-5) var(--space-2);
padding: 6px 8px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-control);
background: var(--bg-editor);
background: var(--bg-input);
color: var(--fg-editor);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: var(--lh-code);
}
.replaceForm .template {
/* Leave room for the scope and dialog controls when both templates are shown. */
height: clamp(96px, calc(50vh - 205px), 150px);
line-height: 1.5;
}
.template:focus {
outline: none;
+28 -42
View File
@@ -1,6 +1,5 @@
/** Inspect Code, Locate Duplicates and Search / Replace Structurally dialogs. */
import { useEffect, useMemo, useState } from "react";
import clsx from "clsx";
import {
call,
commands,
@@ -11,8 +10,6 @@ import {
type WorkspaceEdit,
} from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { editorPrefs } from "@/platform/editorSettings";
import { monoFontFamily } from "@/platform/fonts";
import { activeProfileId, listProfiles, validateInspections, type ProfileId } from "@/platform/inspections";
import { basename, relativePath, useProject } from "@/platform/project";
import { Button, Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
@@ -322,15 +319,6 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
const [form, setForm] = useState<StructuralForm>(loadStructuralForm);
const [scope, setScope] = useState<ScopeChoice>(() => defaultScope());
const [busy, setBusy] = useState(false);
const settings = useProject((s) => s.settings);
const font = settings?.editor;
const fallback = editorPrefs(settings).fallbackFont;
const templateFont = {
fontFamily:
font?.fontFamily || fallback ? monoFontFamily(font?.fontFamily, fallback, "var(--font-mono)") : undefined,
fontSize: font?.fontSize ?? undefined,
lineHeight: font?.lineHeight != null ? `${font.lineHeight}px` : undefined,
};
const languages = useStructuralLanguages();
// The editor's language when it has a grammar, else the first supported one.
const language =
@@ -369,49 +357,47 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
{ label: "Cancel", role: "cancel" },
]}
>
<div className={clsx(styles.form, replace && styles.replaceForm)}>
<div className={styles.templateSection}>
<div className={styles.templateHeader}>
<label htmlFor="ssr-template">
<T>Search template</T>
</label>
<Select
value={language || null}
options={options}
onChange={(language) => setForm({ ...form, language })}
placeholder={languages ? "No languages" : "Loading…"}
className={styles.languageSelect}
variant="ghost"
aria-label="Language"
/>
</div>
<textarea
id="ssr-template"
className={styles.template}
style={templateFont}
spellCheck={false}
value={form.pattern}
placeholder="$a$.equals($b$)"
onChange={(e) => setForm({ ...form, pattern: e.target.value })}
data-autofocus=""
<div className={styles.form}>
<div className={styles.fieldRow}>
<span>
<T>Language</T>
</span>
<Select
value={language || null}
options={options}
onChange={(language) => setForm({ ...form, language })}
placeholder={languages ? "No languages" : "Loading…"}
className={styles.languageSelect}
aria-label="Language"
/>
{error && <div className={styles.error}>{error}</div>}
</div>
<label className={styles.fieldLabel} htmlFor="ssr-template">
<T>Search template</T>
</label>
<textarea
id="ssr-template"
className={styles.template}
spellCheck={false}
value={form.pattern}
placeholder="$a$.equals($b$)"
onChange={(e) => setForm({ ...form, pattern: e.target.value })}
data-autofocus=""
/>
{error && <div className={styles.error}>{error}</div>}
{replace && (
<div className={styles.templateSection}>
<label htmlFor="ssr-replacement">
<>
<label className={styles.fieldLabel} htmlFor="ssr-replacement">
<T>Replace template</T>
</label>
<textarea
id="ssr-replacement"
className={styles.template}
style={templateFont}
spellCheck={false}
value={form.replacement}
placeholder="Objects.equals($a$, $b$)"
onChange={(e) => setForm({ ...form, replacement: e.target.value })}
/>
</div>
</>
)}
<div className={styles.hint}>
<T>Placeholders:</T> <code>$name$</code> or <code>$NAME</code> <T>match one node,</T> <code>$$$NAME</code>{" "}
+47 -60
View File
@@ -1,12 +1,11 @@
/** Dialog stack of the analysis feature and the shared "Specify Scope" fields. */
import { Fragment, type ReactNode } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { isTauri } from "@/platform/ipc";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
import { Button, IconButton, Input, Radio, Select, T } from "@/ui";
import { Button, IconButton, Input, Select, T } from "@/ui";
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
import styles from "./Analysis.module.css";
@@ -63,69 +62,57 @@ export function ScopeFields({
}) {
const file = currentFile();
const scopes = useCustomScopeList();
const custom = value.custom ?? scopes[0]?.name;
return (
<fieldset className={styles.scope}>
<legend className={styles.fieldLabel}>
<T>Scope</T>
</legend>
<div className={styles.scopeOptions}>
{kinds.map((kind) => {
const selected = value.kind === kind;
return (
<Fragment key={kind}>
<Radio
name={name}
checked={selected}
disabled={kind === "file" && !file}
onChange={() => onChange({ ...value, kind, custom: kind === "custom" ? custom : value.custom })}
label={
kind === "file" && file ? <span>{tx`File '${file.split("/").pop()}'`}</span> : SCOPE_LABELS[kind]
}
className={clsx(styles.radioRow, (kind === "directory" || kind === "custom") && styles.scopeWithField)}
/>
{kind === "directory" && (
<div className={styles.scopeControl}>
<Input
aria-label="Directory"
value={value.directory}
disabled={!selected}
onChange={(e) => onChange({ ...value, directory: e.target.value })}
className={styles.grow}
/>
<Button
disabled={!selected}
onClick={() =>
void browseDirectory(value.directory).then((d) => d && onChange({ ...value, directory: d }))
}
>
<T>Browse…</T>
</Button>
</div>
)}
{kind === "custom" && (
<div className={styles.scopeControl}>
<Select<string>
className={styles.grow}
value={(selected ? value.custom : custom) ?? null}
options={scopes.map((s) => ({ value: s.name, label: s.name, detail: s.pattern }))}
placeholder={scopes.length ? "Choose a scope" : "No custom scopes"}
disabled={!selected}
onChange={(custom) => onChange({ ...value, custom })}
aria-label="Custom scope"
/>
<IconButton
icon="more-horizontal"
title="Edit Scopes…"
disabled={!selected}
onClick={() => void executeAction(EDIT_SCOPES_ACTION, custom ? { select: custom } : undefined)}
/>
</div>
)}
</Fragment>
);
})}
</div>
{kinds.map((kind) => (
<label key={kind} className={styles.radioRow}>
<input
type="radio"
name={name}
checked={value.kind === kind}
disabled={kind === "file" && !file}
onChange={() =>
onChange({ ...value, kind, custom: kind === "custom" ? (value.custom ?? scopes[0]?.name) : value.custom })
}
/>
<span>{kind === "file" && file ? tx`File '${file.split("/").pop()}'` : tx(SCOPE_LABELS[kind])}</span>
</label>
))}
{value.kind === "directory" && (
<div className={styles.dirRow}>
<Input
aria-label="Directory"
value={value.directory}
onChange={(e) => onChange({ ...value, directory: e.target.value })}
className={styles.grow}
/>
<Button
onClick={() => void browseDirectory(value.directory).then((d) => d && onChange({ ...value, directory: d }))}
>
<T>Browse…</T>
</Button>
</div>
)}
{value.kind === "custom" && (
<div className={styles.dirRow}>
<Select<string>
className={styles.grow}
value={value.custom ?? null}
options={scopes.map((s) => ({ value: s.name, label: s.name, detail: s.pattern }))}
placeholder="No custom scopes"
onChange={(custom) => onChange({ ...value, custom })}
aria-label="Custom scope"
/>
<IconButton
icon="more-horizontal"
title="Edit Scopes…"
onClick={() => void executeAction(EDIT_SCOPES_ACTION, value.custom ? { select: value.custom } : undefined)}
/>
</div>
)}
</fieldset>
);
}
+3 -18
View File
@@ -31,7 +31,6 @@ import {
mavenRoots,
nodeIcon,
nodeLabel,
pluginCoordinates,
profileChecked,
withGradleOptions,
gradleHasTestTask,
@@ -311,8 +310,6 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
</span>
);
}
const plugin = node.kind === "plugin" ? node.plugin : null;
const coordinates = plugin && `(${pluginCoordinates(plugin)})`;
const detail =
node.kind === "profiles" && node.projectRoot
? node.projectRoot.split("/").pop()
@@ -324,24 +321,12 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
const skipped =
(mavenSkipTests && node.kind === "phase" && node.phase === "test") ||
(gradleSkipTests && node.kind === "task" && node.task.name === "test");
const label = (
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
{plugin?.prefix ?? nodeLabel(node)}
</span>
);
return (
<span className={styles.row}>
<Icon name={nodeIcon(node)} size={16} className={styles.icon} />
{coordinates ? (
<span className={styles.pluginText}>
{label}
<span className={styles.detail} title={coordinates}>
{coordinates}
</span>
</span>
) : (
label
)}
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
{nodeLabel(node)}
</span>
{detail && <span className={styles.detail}>{detail}</span>}
</span>
);
@@ -96,18 +96,6 @@
overflow: hidden;
text-overflow: ellipsis;
}
.pluginText {
display: flex;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
overflow: hidden;
}
.pluginText > .label {
flex: none;
min-width: 0;
max-width: 100%;
}
.profile {
min-width: 0;
}
+3 -3
View File
@@ -99,8 +99,8 @@ export function dependencyLabel(d: MavenDependency): string {
return parts.join(":");
}
export function pluginCoordinates(p: MavenPlugin): string {
return `${p.groupId}:${p.artifactId}${p.version ? `:${p.version}` : ""}`;
export function pluginLabel(p: MavenPlugin): string {
return `${p.prefix} (${p.groupId}:${p.artifactId}${p.version ? `:${p.version}` : ""})`;
}
/** Profile choices in different workspace members are independent. */
@@ -363,7 +363,7 @@ export function nodeLabel(node: BuildNode): string {
case "plugins":
return tx("Plugins");
case "plugin":
return `${node.plugin.prefix} (${pluginCoordinates(node.plugin)})`;
return pluginLabel(node.plugin);
case "goal":
return `${node.plugin.prefix}:${node.goal}`;
case "dependencies":
@@ -159,7 +159,7 @@
flex-direction: column;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: var(--lh-code);
line-height: 1.45;
}
.sourcePreview .sourceText[role="region"] {
font: inherit;
+2 -13
View File
@@ -406,8 +406,6 @@ export function useUsagesHeaderMenu(): MenuItem[] {
];
}
const DEFAULT_PREVIEW_LAYOUT = { usages: 50, preview: 50 };
function UsagesSplit({ preview, children }: { preview: ReactNode; children: ReactNode }) {
const show = useUsagesOptions((s) => s.preview);
const frame = useRef<HTMLDivElement>(null);
@@ -429,13 +427,12 @@ function UsagesSplit({ preview, children }: { preview: ReactNode; children: Reac
orientation={stacked ? "vertical" : "horizontal"}
id="usages-preview-split"
storageKey={stacked ? "openidea.usages.previewSplit.vertical" : "openidea.usages.previewSplit"}
defaultLayout={DEFAULT_PREVIEW_LAYOUT}
>
<SplitPanel id="usages" minSize={stacked ? "30%" : 160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} className={styles.panel}>
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} defaultSize="45%" className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
@@ -458,21 +455,13 @@ function UsagesPreview({ node }: { node: Node | null }) {
return (group?.usages ?? []).map((u) => ({ line: u.line, ranges: [[u.col, u.endCol] as const] }));
}, [usage, search?.groups]);
return (
<div
className={styles.sourcePreview}
style={{
fontFamily,
fontSize: settings?.fontSize ?? undefined,
lineHeight: settings?.lineHeight != null ? `${settings.lineHeight}px` : undefined,
}}
>
<div className={styles.sourcePreview} style={{ fontFamily, fontSize: settings?.fontSize ?? undefined }}>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
editorLayout
className={styles.sourceText}
/>
</div>
@@ -241,8 +241,7 @@ describe("MemoryView", () => {
expect(screen.getByRole("button", { name: "刷新内存视图" }).getAttribute("data-tooltip")).toBe("刷新内存视图");
const filter = screen.getByRole("textbox", { name: "筛选类" });
expect(filter.getAttribute("placeholder")).toBe("筛选类");
fireEvent.click(screen.getByRole("button", { name: "视图选项" }));
expect(screen.getByRole("menuitemcheckbox", { name: "仅显示有变化的" })).toBeInTheDocument();
expect(screen.getByRole("checkbox", { name: "仅显示有变化的" })).toBeTruthy();
} finally {
await setLocale("en");
}
@@ -300,15 +299,10 @@ describe("MemoryView", () => {
expect(screen.getByText("Cache$Entry")).toBeTruthy();
fireEvent.change(screen.getByRole("textbox", { name: "Filter classes" }), { target: { value: "" } });
const options = screen.getByRole("button", { name: "View Options" });
fireEvent.click(options);
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Changed only", checked: false }));
fireEvent.click(screen.getByRole("checkbox", { name: "Changed only" }));
expect(screen.getByText("Heap$Live")).toBeTruthy();
expect(screen.queryByText("Cache$Entry")).toBeNull();
expect(screen.queryByText("Dup")).toBeNull();
expect(options).toHaveAttribute("aria-pressed", "true");
fireEvent.click(options);
expect(screen.getByRole("menuitemcheckbox", { name: "Changed only", checked: true })).toBeInTheDocument();
});
it("sorts by the clicked column and reports it with aria-sort", async () => {
@@ -18,8 +18,8 @@
}
.filter {
flex: 1;
min-width: 0;
flex: 0 1 240px;
min-width: 80px;
}
.banner,
+8 -30
View File
@@ -1,7 +1,7 @@
/** Memory tab of the Debug tool window: live instance counts per class of the debugged JVM, and heap capture. */
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useMemo } from "react";
import clsx from "clsx";
import { Icon, IconButton, List, Menu, SearchField, T } from "@/ui";
import { Checkbox, Icon, IconButton, Input, List, T } from "@/ui";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import type { JvmClassRow, JvmMemorySnapshot } from "@/platform/ipc";
@@ -112,8 +112,6 @@ export function MemoryView({ session }: { session: DebugSession }) {
const id = session.id;
const entry = useMemory((s) => s.bySession[id]);
const query = entry?.query ?? DEFAULT_QUERY;
const optionsButton = useRef<HTMLButtonElement>(null);
const [optionsOpen, setOptionsOpen] = useState(false);
const result = entry?.result ?? null;
const snapshot = entry?.snapshot ?? null;
const source = snapshot?.source ?? "histogram";
@@ -163,37 +161,17 @@ export function MemoryView({ session }: { session: DebugSession }) {
disabled={entry?.loading || !canRefresh}
/>
<HeapCaptureButton session={session} />
<SearchField
<Input
className={styles.filter}
value={query.filter}
onChange={(filter) => setMemoryQuery(id, { filter })}
onChange={(e) => setMemoryQuery(id, { filter: e.target.value })}
placeholder="Filter classes"
aria-label="Filter classes"
/>
<IconButton
ref={optionsButton}
icon="settings"
title="View Options"
size="small"
iconSize={16}
pressed={query.changedOnly}
aria-haspopup="menu"
aria-expanded={optionsOpen}
onClick={() => setOptionsOpen(!optionsOpen)}
/>
<Menu
open={optionsOpen}
onClose={() => setOptionsOpen(false)}
anchor={optionsButton}
placement="bottom-end"
aria-label="View Options"
items={[
{
label: "Changed only",
checked: query.changedOnly,
run: () => setMemoryQuery(id, { changedOnly: !query.changedOnly }),
},
]}
<Checkbox
checked={query.changedOnly}
onChange={(changedOnly) => setMemoryQuery(id, { changedOnly })}
label="Changed only"
/>
</div>
{backend && (
+32 -50
View File
@@ -3,7 +3,7 @@ import { useState } from "react";
import { create } from "zustand";
import { executeAction, getAction } from "@/platform/actions";
import { t, tx } from "@/platform/i18n";
import { BarButton, Dialog, Icon, IconButton, List, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { BarButton, Button, Dialog, Icon, List, T } from "@/ui";
import { confirm } from "@/workbench/messages";
import { promptInput } from "@/workbench/inputDialogs";
import { deleteMacro, describeStep, renameMacro, useMacros } from "./model";
@@ -80,55 +80,37 @@ function EditMacrosDialog({ onClose }: { onClose: () => void }) {
buttons={[{ label: t("common.close"), role: "cancel" }]}
>
<div className={styles.edit}>
<SplitGroup orientation="horizontal" storageKey="openidea.macros.split" className={styles.panes}>
<SplitPanel id="macro-list" defaultSize="50%" minSize="25%">
<div className={styles.toolbar} role="toolbar" aria-label={tx("Macros")}>
<IconButton
icon="minus"
title="Delete Macro"
size="small"
disabled={!macro}
onClick={() => void remove()}
/>
<IconButton
icon="edit"
title="Rename Macro"
size="small"
disabled={!macro}
onClick={() => void rename()}
/>
</div>
<List
items={saved}
getKey={(m) => m.name}
activeIndex={Math.min(active, saved.length - 1)}
onActiveChange={setActive}
autoFocus
className={styles.list}
aria-label="Macros"
empty={
<div className={styles.empty}>
<T>No saved macros</T>
</div>
}
renderItem={(m) => (
<div className={styles.row} title={m.name}>
{m.name}
</div>
)}
/>
</SplitPanel>
<SplitHandle aria-label={tx("Macros")} />
<SplitPanel id="macro-steps" defaultSize="50%" minSize="25%">
<ol className={styles.steps} aria-label={tx("Recorded steps")}>
{macro?.steps.map((step, i) => (
<li key={i} className={styles.step}>
{describeStep(step, actionTitle)}
</li>
))}
</ol>
</SplitPanel>
</SplitGroup>
<div className={styles.column}>
<List
items={saved}
getKey={(m) => m.name}
activeIndex={Math.min(active, saved.length - 1)}
onActiveChange={setActive}
className={styles.list}
aria-label="Macros"
empty={
<div className={styles.empty}>
<T>No saved macros</T>
</div>
}
renderItem={(m) => <div className={styles.row}>{m.name}</div>}
/>
<div className={styles.buttons}>
<Button disabled={!macro} onClick={() => void rename()}>
<T>Rename…</T>
</Button>
<Button disabled={!macro} onClick={() => void remove()}>
<T>Delete</T>
</Button>
</div>
</div>
<ol className={styles.steps} aria-label={tx("Recorded steps")}>
{macro?.steps.map((step, i) => (
<li key={i} className={styles.step}>
{describeStep(step, actionTitle)}
</li>
))}
</ol>
</div>
</Dialog>
);
+22 -24
View File
@@ -8,27 +8,23 @@
background: var(--danger);
}
.edit {
display: grid;
grid-template-columns: 220px 1fr;
gap: var(--space-3);
height: 300px;
padding: 14px;
}
.column {
display: flex;
flex-direction: column;
height: 300px;
padding: var(--space-3);
}
.panes {
flex: 1;
border: 1px solid var(--border);
border-radius: var(--radius-control);
}
.toolbar {
display: flex;
flex: none;
align-items: center;
gap: var(--space-0-5);
padding: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
gap: var(--space-2);
min-height: 0;
}
.list {
flex: 1;
min-height: 0;
border: 1px solid var(--border);
border-radius: var(--radius-control);
}
.row {
padding: 0 8px;
@@ -36,25 +32,27 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.buttons {
display: flex;
gap: var(--space-1-5);
}
.empty {
padding: 6px 8px;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.steps {
flex: 1;
min-height: 0;
margin: 0;
padding: var(--space-2) var(--space-2) var(--space-2) 28px;
padding: 6px 8px 6px 32px;
overflow: auto;
font-family: var(--font-ui);
font-size: var(--fs-ui);
border: 1px solid var(--border);
border-radius: var(--radius-control);
font-family: var(--font-mono);
font-size: var(--fs-code);
color: var(--fg);
}
.step {
min-height: var(--h-row);
padding-block: var(--space-0-5);
line-height: 1.5;
line-height: 1.6;
white-space: pre-wrap;
overflow-wrap: anywhere;
word-break: break-word;
}
@@ -126,9 +126,6 @@
.stackedRadioBlock {
margin-inline-end: 0;
}
.stackedRadioBlock > .radioLabel {
white-space: normal;
}
.stackedRadios {
max-width: 100%;
}
@@ -139,11 +136,6 @@
.stackedRadioBlock .radioLabel + .stackedRadios {
padding-inline-start: calc(var(--space-4) + var(--space-1));
}
.tabOverflowChoices {
align-items: flex-start;
gap: var(--space-1);
max-width: 100%;
}
.radio {
display: inline-flex;
align-items: center;
+16 -21
View File
@@ -9,7 +9,7 @@ import { useEffect, useId, useState } from "react";
import clsx from "clsx";
import { commands, isTauri } from "@/platform/ipc";
import { Checkbox, Icon, Radio, type IconName } from "@/ui";
import { Row, SearchLabel, Select } from "../../components/Form";
import { SearchLabel, Select } from "../../components/Form";
import { useLabelMatch, useSearchQuery, useSetting } from "../../components/context";
import { labelMatches } from "../../model/pages";
import { editorPage } from "./kit";
@@ -581,7 +581,6 @@ const TABS = editorPage({
t: "radio",
key: `${P}.tabs.closingPolicy`,
label: "When the tab limit is reached",
layout: "stacked",
options: [
{ value: "unchanged", label: "Close non-modified files first" },
{ value: "lru", label: "Close least recently used files" },
@@ -591,7 +590,6 @@ const TABS = editorPage({
t: "radio",
key: `${P}.tabs.activateOnClose`,
label: "When the current tab is closed, activate",
layout: "stacked",
options: [
{ value: "left", label: "The tab on the left" },
{ value: "right", label: "The tab on the right" },
@@ -609,11 +607,10 @@ function TabRows() {
const [overflow, setOverflow] = useSetting<string>(`${P}.tabs.oneRowOverflow`);
const [placement] = useSetting<string>(`${P}.tabs.placement`);
const matched = useLabelMatch("Show tabs in:");
const rowsName = useId();
const overflowName = useId();
const name = useId();
// Vertical (left / right) tabs always scroll in one column.
const disabled = placement === "none" || placement === "left" || placement === "right";
const radio = (name: string, label: string, checked: boolean, onChange: () => void, off = disabled) => (
const radio = (label: string, checked: boolean, onChange: () => void, off = disabled) => (
<label className={clsx(styles.radio, off && styles.dim)}>
<input type="radio" name={name} checked={checked} disabled={off} onChange={onChange} />
<SearchLabel text={label} />
@@ -621,36 +618,30 @@ function TabRows() {
);
return (
<div
className={clsx(styles.radioBlock, styles.stackedRadioBlock, matched && styles.matched)}
className={clsx(styles.radioBlock, matched && styles.matched)}
role="radiogroup"
aria-label={tx("Show tabs in")}
>
<div className={clsx(styles.radioLabel, disabled && styles.dim)}>
<SearchLabel text="Show tabs in" />:
</div>
<div className={clsx(styles.radios, styles.stackedRadios)}>
{radio(rowsName, "One row, and if tabs don't fit:", !multiple, () => setMultiple(false))}
<div
className={clsx(styles.children, styles.tabOverflowChoices)}
role="radiogroup"
aria-label={tx("If tabs don't fit")}
>
<div className={styles.radios}>
{radio("One row, and if tabs don't fit:", !multiple, () => setMultiple(false))}
<div className={styles.children} role="radiogroup" aria-label={tx("If tabs don't fit")}>
{radio(
overflowName,
"Scroll the tabs panel",
overflow !== "squeeze",
!multiple && overflow !== "squeeze",
() => setOverflow("scroll"),
disabled || multiple,
)}
{radio(
overflowName,
"Squeeze tabs",
overflow === "squeeze",
!multiple && overflow === "squeeze",
() => setOverflow("squeeze"),
disabled || multiple,
)}
</div>
{radio(rowsName, "Multiple rows", multiple, () => setMultiple(true))}
{radio("Multiple rows", multiple, () => setMultiple(true))}
</div>
</div>
);
@@ -666,8 +657,12 @@ const CLOSE_POSITIONS = [
function CloseButtonPosition() {
const [show, setShow] = useSetting<boolean>(`${P}.tabs.showCloseButton`);
const [position, setPosition] = useSetting<string>(`${P}.tabs.closeButtonPosition`);
const matched = useLabelMatch("Close button position:");
return (
<Row label="Close button position">
<div className={clsx(styles.check, matched && styles.matched)}>
<span>
<SearchLabel text="Close button position:" />
</span>
<Select
value={show ? (position === "left" ? "left" : "right") : "none"}
options={CLOSE_POSITIONS}
@@ -677,7 +672,7 @@ function CloseButtonPosition() {
if (v !== "none") setPosition(v);
}}
/>
</Row>
</div>
);
}
+2 -2
View File
@@ -41,8 +41,8 @@
flex: none;
position: sticky;
left: 0;
width: var(--source-preview-gutter-width, 48px);
padding-right: var(--space-3);
width: 48px;
padding-right: 12px;
text-align: right;
color: var(--fg-gutter);
background-color: var(--bg-app);
+4 -34
View File
@@ -9,7 +9,7 @@
* Usages. Files beyond `MAX_PARSE` stay plain rather than colouring the window
* with the wrong block-comment context.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import { T } from "./T";
import { tokenSpans, type SourceToken } from "./tokenSpans";
@@ -46,8 +46,6 @@ export interface SourcePreviewProps {
version?: number;
/** Stable (module-level) syntax colouring; without it lines stay plain. */
colorize?: SourceColorizer;
/** Fit the gutter to the line numbers and keep the selected line visible when the pane resizes. */
editorLayout?: boolean;
className?: string;
}
@@ -58,7 +56,6 @@ export function SourcePreview({
load,
version = 0,
colorize,
editorLayout,
className,
}: SourcePreviewProps) {
const [text, setText] = useState<{ path: string; lines: string[] } | null>(null);
@@ -163,7 +160,6 @@ export function SourcePreview({
lines={current.lines}
tokensByLine={tokensByLine}
highlights={highlights}
editorLayout={editorLayout}
className={className}
/>
);
@@ -180,7 +176,6 @@ function PreviewBody({
lines,
tokensByLine,
highlights,
editorLayout,
className,
}: {
path: string;
@@ -188,7 +183,6 @@ function PreviewBody({
lines: string[];
tokensByLine: Map<number, SourceToken[]> | null;
highlights: readonly SourceHighlight[];
editorLayout?: boolean;
className?: string;
}) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -198,21 +192,8 @@ function PreviewBody({
useLayoutEffect(() => {
const box = scrollRef.current;
const el = box?.querySelector<HTMLElement>(`[data-line="${line}"]`);
if (!box || !el) return;
const center = () => {
box.scrollTop = el.offsetTop - box.clientHeight / 2 + el.offsetHeight / 2;
};
center();
if (!editorLayout || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => {
if (el.offsetTop < box.scrollTop || el.offsetTop + el.offsetHeight > box.scrollTop + box.clientHeight) {
center();
}
});
observer.observe(box);
observer.observe(el);
return () => observer.disconnect();
}, [editorLayout, line, path, lines]);
if (box && el) box.scrollTop = el.offsetTop - box.clientHeight / 2 + el.offsetHeight / 2;
}, [line, path, lines]);
const byLine = new Map(highlights.map((h) => [h.line, h.ranges]));
const start = Math.max(0, line - WINDOW);
@@ -233,18 +214,7 @@ function PreviewBody({
}
return (
<div ref={scrollRef} className={clsx(styles.preview, className)} role="region" aria-label={tx("Preview")}>
<pre
className={styles.pre}
style={
editorLayout
? ({
"--source-preview-gutter-width": `calc(${String(lines.length).length}ch + var(--space-4))`,
} as CSSProperties)
: undefined
}
>
{rows}
</pre>
<pre className={styles.pre}>{rows}</pre>
</div>
);
}