Compare commits

...
Author SHA1 Message Date
l0ng-ai 6771575c88 test(search): measure the scope pattern field after the dialog settles 2026-11-23 13:09:21 +08:00
l0ng-ai bbea793adf fix(debugger): align the Python table viewer (#5309)
- Keep the shape and paging controls above the table and put the full-width slice expression below it, above Close. The grid scrolls between the controls.
- Open at 700 × 500 when there is room. Give short tables the available width, use workbench typography and center the row and column headers.
- Update the title when a slice is submitted and show expression errors below the field.
2026-11-23 13:01:59 +08:00
l0ng-ai f1c556e2ec fix(editor): align the Find Usages source preview (#5305)
- Start with equal space for the results tree and source preview. Each orientation restores its saved split and starts at 50/50 when it has no saved split.
- Follow the editor's line height and size the preview gutter for the document's longest line number. Keep the selected line visible when the panel height or line metrics change.
2026-11-23 12:42:18 +08:00
l0ng-ai 2d99a79e69 fix(settings): align the Editor Tabs form (#5300)
- Align the tab placement and close button selectors in the Appearance form.
- Put the row and overflow choices on separate lines with the overflow options nested under the single-row choice. The two groups retain their own selections and support independent arrow-key navigation.
- Stack each set of closing policy choices below its heading, so the order stays consistent as the window narrows.
2026-11-23 12:24:08 +08:00
l0ng-ai ca778e2382 fix(search): improve structural template layout (#5298)
- Put the language picker in the Search template header and keep each label next to its template.
- Give both templates 150 px of editing space in a standard window. Tighten the editors on shorter screens and keep the dialog footer accessible.
- Use the configured editor font, size, and line height in both templates.
2026-11-23 12:08:57 +08:00
Deng Liuandl0ng-ai 414353a5bd ci: add Docker Compose setup for persistent self-hosted Actions runners (#5307)
* ci: add Docker Compose setup for persistent self-hosted Actions runners

* ci: wire Linux Rust CI to hardened self-hosted runners under scripts/

* ci: gate self-hosted runners behind a variable and use the jammy image

- Pin the Ubuntu 22.04 runner image; the untagged-distro image is 20.04 and
  cannot install libwebkit2gtk-4.1-dev.
- Route the Linux Rust job to self-hosted runners only while the
  SELFHOSTED_RUNNERS repository variable is 'true', so CI keeps working when
  no runner is online.
- On self-hosted runners, enable incremental compilation and clear the
  persistent target dir once it exceeds 40 GB.
- README: document the variable, passwordless sudo inside the container and
  the target dir shared between main and same-repo branches.

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-11-23 11:54:56 +08:00
20 changed files with 800 additions and 149 deletions

No files matched your search

+23 -3
View File
@@ -102,24 +102,44 @@ 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]
runs-on: ${{ matrix.os }}
# 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 }}
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" }
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
# 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).
- 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'
+110
View File
@@ -0,0 +1,110 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function openTable(page: Page, columns: number) {
await stubDesktop(page);
await page.evaluate(async (columns) => {
window.__ipc.handlers.debug_evaluate_in = ({ expression }) => {
const query = String(expression);
const sliced = query.includes("totals.iloc[:2, :2]");
const visibleColumns = sliced ? 2 : Math.min(30, columns);
const columnsInFrame = sliced ? 2 : columns;
const start = query.includes("100, 100,") ? 100 : 0;
const rows = sliced ? 2 : 220;
const count = sliced ? 2 : 100;
const result = query.includes("missing_table")
? { error: "NameError: missing_table" }
: {
kind: "frame",
shape: [rows, columnsInFrame],
rows,
columns: columnsInFrame,
headers: Array.from({ length: visibleColumns }, (_, i) => `Amount ${i + 1}`),
dtypes: Array.from({ length: visibleColumns }, () => "int64"),
index: Array.from({ length: count }, (_, i) => String(i + start)),
cells: Array.from({ length: count }, (_, row) =>
Array.from({ length: visibleColumns }, (_, column) => String((row + start + 1) * 10 + column)),
),
};
return {
name: "",
value: JSON.stringify(JSON.stringify(result)),
typeName: "str",
variablesReference: 0,
evaluateName: null,
};
};
const stateModule = "/src/features/debugger/state.ts";
const overlaysModule = "/src/features/debugger/ui/popoverStore.ts";
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
const { openTableView } = await import(/* @vite-ignore */ overlaysModule);
adoptSession(91, { name: "Settlement review", adapter: "debugpy", status: "paused", selectedFrame: 11 });
openTableView("totals", 91);
}, columns);
const dialog = page.getByRole("dialog", { name: "Table view of totals", exact: true });
await expect(dialog.getByRole("table")).toBeVisible();
return dialog;
}
test("View as Table gives the grid the dialog width and puts the expression below it", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const dialog = await openTable(page, 3);
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
const grid = dialog.getByRole("table");
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
const shape = dialog.getByText("Shape (220, 3)", { exact: true });
const body = (await scroll.boundingBox())!;
const input = (await expression.boundingBox())!;
expect(input.y).toBeGreaterThan(body.y + body.height);
expect((await shape.boundingBox())!.y).toBeLessThan(body.y);
expect(Math.abs((await grid.boundingBox())!.width - (await scroll.evaluate((el) => el.clientWidth)))).toBeLessThan(1);
expect((await dialog.boundingBox())!.width).toBeCloseTo(700, 0);
await expect(expression).toBeFocused();
await expect(grid).toHaveCSS("font-family", /Inter/);
await expect(grid.getByRole("columnheader").nth(1)).toHaveCSS("text-align", "center");
await expect(grid.getByRole("rowheader").first()).toHaveCSS("text-align", "center");
await expect(grid.getByRole("cell").first()).toHaveCSS("text-align", /^(start|left)$/);
});
test("View as Table keeps paging, slice input and Close usable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 450, height: 620 });
const dialog = await openTable(page, 36);
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
const rows = dialog.getByRole("button", { name: "Next Rows", exact: true });
const columns = dialog.getByRole("button", { name: "Next Columns", exact: true });
const close = dialog.getByRole("button", { name: "Close", exact: true }).filter({ hasText: /^Close$/ });
const input = (await expression.boundingBox())!;
const grid = (await scroll.boundingBox())!;
expect(input.y).toBeGreaterThan(grid.y + grid.height);
expect(input.width).toBeCloseTo(grid.width, 0);
for (const control of [expression, rows, columns, close]) await expect(control).toBeInViewport({ ratio: 0.98 });
await scroll.evaluate((el) => {
el.scrollLeft = 300;
el.scrollTop = 150;
});
await expect(dialog.getByRole("rowheader").filter({ hasText: /^9$/ })).toBeInViewport({ ratio: 0.98 });
await rows.click();
await expect(dialog.getByText("Rows 101–200 of 220", { exact: true })).toBeVisible();
await expect
.poll(() => ipcCalls(page, "debug_evaluate_in"))
.toContainEqual(expect.objectContaining({ expression: expect.stringContaining("100, 100, 0, 30") }));
await expression.fill("totals.iloc[:2, :2]");
await expression.press("Enter");
const sliced = page.getByRole("dialog", { name: "Table view of totals.iloc[:2, :2]", exact: true });
await expect(sliced.getByText("Shape (2, 2)", { exact: true })).toBeVisible();
const slicedExpression = sliced.getByRole("textbox", { name: "Expression", exact: true });
await slicedExpression.fill("missing_table");
await slicedExpression.press("Enter");
const failed = page.getByRole("dialog", { name: "Table view of missing_table", exact: true });
const alert = failed.getByRole("alert");
await expect(alert).toHaveText("NameError: missing_table");
expect((await alert.boundingBox())!.y).toBeGreaterThan(
(await failed.getByRole("textbox", { name: "Expression", exact: true }).boundingBox())!.y,
);
await failed
.getByRole("button", { name: "Close", exact: true })
.filter({ hasText: /^Close$/ })
.click();
await expect(failed).toHaveCount(0);
});
+81
View File
@@ -0,0 +1,81 @@
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();
});
+8 -1
View File
@@ -29,7 +29,14 @@ 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 });
const fields = (await pattern.boundingBox())!;
// 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();
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));
+81
View File
@@ -0,0 +1,81 @@
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
@@ -0,0 +1,95 @@
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
@@ -0,0 +1,3 @@
.env
.env.*
!.env.example
+113
View File
@@ -0,0 +1,113 @@
# 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/`).
@@ -0,0 +1,70 @@
# 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:
+23 -5
View File
@@ -231,21 +231,39 @@
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 {
min-width: 180px;
max-width: 50%;
}
.template {
width: 100%;
min-height: 96px;
height: clamp(96px, 24vh, 150px);
min-height: 50px;
resize: vertical;
padding: 6px 8px;
padding: var(--space-1-5) var(--space-2);
border: 1px solid var(--border-strong);
border-radius: var(--radius-control);
background: var(--bg-input);
background: var(--bg-editor);
color: var(--fg-editor);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 1.5;
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);
}
.template:focus {
outline: none;
+42 -28
View File
@@ -1,5 +1,6 @@
/** Inspect Code, Locate Duplicates and Search / Replace Structurally dialogs. */
import { useEffect, useMemo, useState } from "react";
import clsx from "clsx";
import {
call,
commands,
@@ -10,6 +11,8 @@ 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";
@@ -319,6 +322,15 @@ 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 =
@@ -357,47 +369,49 @@ function StructuralDialog({ replace, onClose }: { replace: boolean; onClose: ()
{ label: "Cancel", role: "cancel" },
]}
>
<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"
<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=""
/>
{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 && (
<>
<label className={styles.fieldLabel} htmlFor="ssr-replacement">
<div className={styles.templateSection}>
<label 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>{" "}
@@ -159,7 +159,7 @@
flex-direction: column;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 1.45;
line-height: var(--lh-code);
}
.sourcePreview .sourceText[role="region"] {
font: inherit;
+13 -2
View File
@@ -406,6 +406,8 @@ 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);
@@ -427,12 +429,13 @@ 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} defaultSize="45%" className={styles.panel}>
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
@@ -455,13 +458,21 @@ 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 }}>
<div
className={styles.sourcePreview}
style={{
fontFamily,
fontSize: settings?.fontSize ?? undefined,
lineHeight: settings?.lineHeight != null ? `${settings.lineHeight}px` : undefined,
}}
>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
editorLayout
className={styles.sourceText}
/>
</div>
-5
View File
@@ -12,11 +12,6 @@ export function isTableType(typeName: string | null | undefined): boolean {
return !!typeName && TABLE_TYPES.has(typeName);
}
/** Numbers are right-aligned, as in the database grid. */
export function isNumericDtype(dtype: string | undefined): boolean {
return !!dtype && /^(u?int|float|complex|Int|UInt|Float)\d*$/.test(dtype);
}
export const ROW_PAGE = 100;
export const COLUMN_PAGE = 30;
@@ -1,39 +1,35 @@
.dialog {
height: clamp(320px, 60vh, 760px);
height: 500px;
}
/* The table scrolls under a fixed bar, not the whole dialog body. */
/* Scroll only the grid between the toolbar and the expression field. */
.content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
padding: var(--space-2) var(--space-3) 0;
gap: var(--space-2);
}
.bar {
flex: none;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
padding-bottom: var(--space-2);
justify-content: space-between;
gap: var(--space-1) var(--space-2);
}
.expression {
flex: 1 1 200px;
min-width: 0;
height: var(--h-list-row);
padding: 0 6px;
font-family: var(--font-mono);
font-size: var(--fs-ui);
color: var(--fg);
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: var(--radius-small);
flex: none;
}
.expression:focus {
outline: none;
border-color: var(--focus-ring);
.pagers {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1) var(--space-2);
}
.summary,
@@ -59,7 +55,8 @@
.table {
border-collapse: separate;
border-spacing: 0;
font-family: var(--font-mono);
min-width: 100%;
font-family: var(--font-ui);
font-size: var(--fs-ui);
color: var(--fg);
}
@@ -77,7 +74,7 @@
position: sticky;
top: 0;
z-index: 1;
text-align: left;
text-align: center;
font-weight: normal;
color: var(--fg-secondary);
background: var(--bg-island);
@@ -86,7 +83,8 @@
.table .index {
position: sticky;
left: 0;
text-align: right;
text-align: center;
font-variant-numeric: tabular-nums;
font-weight: normal;
color: var(--fg-secondary);
background: var(--bg-island);
@@ -100,16 +98,22 @@
background: var(--bg-hover);
}
.numeric {
text-align: right;
}
.dtype {
margin-left: var(--space-1);
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.message {
flex: 1;
min-height: 0;
padding: var(--space-3) 0;
color: var(--fg-secondary);
}
.error {
max-height: 5em;
overflow: auto;
overflow-wrap: anywhere;
color: var(--danger);
}
+44 -58
View File
@@ -1,19 +1,10 @@
/** View as Table: a DataFrame / Series / ndarray of the paused frame, one page of rows and columns at a time. */
import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
import type { DebugSessionId } from "@/platform/ipc";
import { Dialog, IconButton } from "@/ui";
import { Dialog, IconButton, Input } from "@/ui";
import { formatMessage, tx } from "@/platform/i18n";
import { evaluate, useDebug } from "../state";
import {
COLUMN_PAGE,
ROW_PAGE,
clampWindow,
isNumericDtype,
parseTableResult,
tableExpression,
type TableResult,
} from "../tableView";
import { COLUMN_PAGE, ROW_PAGE, clampWindow, parseTableResult, tableExpression, type TableResult } from "../tableView";
import styles from "./TableViewDialog.module.css";
export function TableViewDialog({
@@ -63,7 +54,7 @@ export function TableViewDialog({
};
}, [expression, win, session, stops, frame, paused]);
const page = result && "page" in result ? result.page : null;
const page = paused && result && "page" in result ? result.page : null;
const error = !paused
? tx("Values are available while the program is paused")
: result && "error" in result
@@ -114,54 +105,37 @@ export function TableViewDialog({
open
onClose={onClose}
// An element, not a string: Dialog would translate a variable named like a catalog text ("tasks").
title={<span>{initial}</span>}
width="clamp(520px, 70vw, 1100px)"
title={<span>{expression}</span>}
width={700}
minWidth={420}
minHeight={260}
resizable="both"
aria-label={formatMessage(tx("Table view of {label}"), { label: initial })}
aria-label={formatMessage(tx("Table view of {label}"), { label: expression })}
buttons={[{ label: "Close", role: "cancel" }]}
className={styles.dialog}
>
<div className={styles.content}>
<div className={styles.bar}>
<input
className={styles.expression}
value={draft}
spellCheck={false}
autoComplete="off"
aria-label={tx("Expression")}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter" || !draft.trim()) return;
e.preventDefault();
setExpression(draft.trim());
setWin({ row: 0, column: 0 });
}}
/>
{page && (
{page && (
<div className={styles.bar}>
<span className={styles.summary}>
{formatMessage(tx("Shape ({shape})"), { shape: page.shape.join(", ") })}
{page.kind !== "frame" ? ` · ${page.dtypes[0]}` : ""}
</span>
)}
{page &&
pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
range: tx("Rows {from}–{to} of {total}"),
previous: tx("Previous Rows"),
next: tx("Next Rows"),
})}
{page &&
pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
range: tx("Columns {from}–{to} of {total}"),
previous: tx("Previous Columns"),
next: tx("Next Columns"),
})}
</div>
{error ? (
<div className={styles.message} role="alert">
{error}
<div className={styles.pagers}>
{pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
range: tx("Rows {from}–{to} of {total}"),
previous: tx("Previous Rows"),
next: tx("Next Rows"),
})}
{pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
range: tx("Columns {from}–{to} of {total}"),
previous: tx("Previous Columns"),
next: tx("Next Columns"),
})}
</div>
</div>
) : page ? (
)}
{page ? (
<div className={styles.scroll} tabIndex={0} role="region" aria-label={tx("Table")}>
<table className={styles.table}>
<thead>
@@ -182,14 +156,7 @@ export function TableViewDialog({
{page.index[r]}
</th>
{row.map((cell, c) => (
<td
key={c}
className={clsx(
isNumericDtype(page.kind === "frame" ? page.dtypes[c] : page.dtypes[0]) && styles.numeric,
)}
>
{cell}
</td>
<td key={c}>{cell}</td>
))}
</tr>
))}
@@ -197,7 +164,26 @@ export function TableViewDialog({
</table>
</div>
) : (
<div className={styles.message}>{tx("Loading…")}</div>
<div className={styles.message}>{!error && tx("Loading…")}</div>
)}
<Input
className={styles.expression}
mono
data-autofocus=""
value={draft}
aria-label="Expression"
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter" || !draft.trim()) return;
e.preventDefault();
setExpression(draft.trim());
setWin({ row: 0, column: 0 });
}}
/>
{error && (
<div className={styles.error} role="alert">
{error}
</div>
)}
</div>
</Dialog>
@@ -126,6 +126,9 @@
.stackedRadioBlock {
margin-inline-end: 0;
}
.stackedRadioBlock > .radioLabel {
white-space: normal;
}
.stackedRadios {
max-width: 100%;
}
@@ -136,6 +139,11 @@
.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;
+21 -16
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 { SearchLabel, Select } from "../../components/Form";
import { Row, SearchLabel, Select } from "../../components/Form";
import { useLabelMatch, useSearchQuery, useSetting } from "../../components/context";
import { labelMatches } from "../../model/pages";
import { editorPage } from "./kit";
@@ -581,6 +581,7 @@ 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" },
@@ -590,6 +591,7 @@ 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" },
@@ -607,10 +609,11 @@ function TabRows() {
const [overflow, setOverflow] = useSetting<string>(`${P}.tabs.oneRowOverflow`);
const [placement] = useSetting<string>(`${P}.tabs.placement`);
const matched = useLabelMatch("Show tabs in:");
const name = useId();
const rowsName = useId();
const overflowName = useId();
// Vertical (left / right) tabs always scroll in one column.
const disabled = placement === "none" || placement === "left" || placement === "right";
const radio = (label: string, checked: boolean, onChange: () => void, off = disabled) => (
const radio = (name: string, 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} />
@@ -618,30 +621,36 @@ function TabRows() {
);
return (
<div
className={clsx(styles.radioBlock, matched && styles.matched)}
className={clsx(styles.radioBlock, styles.stackedRadioBlock, 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={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")}>
<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")}
>
{radio(
overflowName,
"Scroll the tabs panel",
!multiple && overflow !== "squeeze",
overflow !== "squeeze",
() => setOverflow("scroll"),
disabled || multiple,
)}
{radio(
overflowName,
"Squeeze tabs",
!multiple && overflow === "squeeze",
overflow === "squeeze",
() => setOverflow("squeeze"),
disabled || multiple,
)}
</div>
{radio("Multiple rows", multiple, () => setMultiple(true))}
{radio(rowsName, "Multiple rows", multiple, () => setMultiple(true))}
</div>
</div>
);
@@ -657,12 +666,8 @@ 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 (
<div className={clsx(styles.check, matched && styles.matched)}>
<span>
<SearchLabel text="Close button position:" />
</span>
<Row label="Close button position">
<Select
value={show ? (position === "left" ? "left" : "right") : "none"}
options={CLOSE_POSITIONS}
@@ -672,7 +677,7 @@ function CloseButtonPosition() {
if (v !== "none") setPosition(v);
}}
/>
</div>
</Row>
);
}
+2 -2
View File
@@ -41,8 +41,8 @@
flex: none;
position: sticky;
left: 0;
width: 48px;
padding-right: 12px;
width: var(--source-preview-gutter-width, 48px);
padding-right: var(--space-3);
text-align: right;
color: var(--fg-gutter);
background-color: var(--bg-app);
+34 -4
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 ReactNode } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import clsx from "clsx";
import { T } from "./T";
import { tokenSpans, type SourceToken } from "./tokenSpans";
@@ -46,6 +46,8 @@ 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;
}
@@ -56,6 +58,7 @@ export function SourcePreview({
load,
version = 0,
colorize,
editorLayout,
className,
}: SourcePreviewProps) {
const [text, setText] = useState<{ path: string; lines: string[] } | null>(null);
@@ -160,6 +163,7 @@ export function SourcePreview({
lines={current.lines}
tokensByLine={tokensByLine}
highlights={highlights}
editorLayout={editorLayout}
className={className}
/>
);
@@ -176,6 +180,7 @@ function PreviewBody({
lines,
tokensByLine,
highlights,
editorLayout,
className,
}: {
path: string;
@@ -183,6 +188,7 @@ function PreviewBody({
lines: string[];
tokensByLine: Map<number, SourceToken[]> | null;
highlights: readonly SourceHighlight[];
editorLayout?: boolean;
className?: string;
}) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -192,8 +198,21 @@ function PreviewBody({
useLayoutEffect(() => {
const box = scrollRef.current;
const el = box?.querySelector<HTMLElement>(`[data-line="${line}"]`);
if (box && el) box.scrollTop = el.offsetTop - box.clientHeight / 2 + el.offsetHeight / 2;
}, [line, path, lines]);
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]);
const byLine = new Map(highlights.map((h) => [h.line, h.ranges]));
const start = Math.max(0, line - WINDOW);
@@ -214,7 +233,18 @@ function PreviewBody({
}
return (
<div ref={scrollRef} className={clsx(styles.preview, className)} role="region" aria-label={tx("Preview")}>
<pre className={styles.pre}>{rows}</pre>
<pre
className={styles.pre}
style={
editorLayout
? ({
"--source-preview-gutter-width": `calc(${String(lines.length).length}ch + var(--space-4))`,
} as CSSProperties)
: undefined
}
>
{rows}
</pre>
</div>
);
}