From 04611c038810c9ee345cf7e6d3378aa34d63e6c5 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:06:41 +0800 Subject: [PATCH 01/14] fix(database): show a running SQL statement in the editor and results (#4601) The console tracked the running request only for Run and Cancel; statement marks and result tabs arrived after it ended, and the Results view said "No results" meanwhile. While a request runs, the submitted statements are highlighted with a gutter spinner and a ticking elapsed time, and the Results view opens with an executing bar above the previous result. Edits during the run move the marks and the outcomes land on their statements; cancel or an error clears the indication and keeps the previous result. Fixes #4565 --- src/features/database/Database.module.css | 28 ++++ src/features/database/ResultsView.tsx | 40 ++++- src/features/database/console.tsx | 138 ++++++++++++++++-- .../database/inEditorResults.test.tsx | 60 +++++++- src/features/database/index.ts | 1 + .../database/requestLifecycle.test.ts | 3 + src/features/database/resultView.ts | 7 +- src/features/database/results-view.test.tsx | 63 ++++++++ src/features/database/store.ts | 23 ++- src/platform/locales/text/en.json | 4 + src/platform/locales/text/zh.json | 4 + src/ui/iconNode.ts | 14 ++ 12 files changed, 368 insertions(+), 17 deletions(-) diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 0fc9d749dd..773eb21ea1 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -154,6 +154,28 @@ flex: 1; min-height: 0; } +/* A console's request in flight; the previous result stays below it. */ +.executing { + flex: none; + display: flex; + align-items: center; + gap: var(--space-2); + min-width: 0; + padding: var(--space-1) var(--space-3); + border-bottom: 1px solid var(--border); + color: var(--fg-muted); + font-size: var(--fs-small); +} +.executingText { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.executingTime { + flex: none; + font-variant-numeric: tabular-nums; +} /* Gives way before the name does. */ .treeDetail { color: var(--fg-muted); @@ -657,6 +679,12 @@ } /* Console run feedback: timing after a statement, gutter check / error, error banner. */ +:global(.cm-openidea-db-executing) { + background: var(--accent-soft); +} +:global(.cm-openidea-db-elapsed) { + font-variant-numeric: tabular-nums; +} :global(.cm-openidea-db-timing) { margin-left: 1.5em; color: var(--fg-muted); diff --git a/src/features/database/ResultsView.tsx b/src/features/database/ResultsView.tsx index 7389066bff..bd09faeec0 100644 --- a/src/features/database/ResultsView.tsx +++ b/src/features/database/ResultsView.tsx @@ -16,6 +16,8 @@ import { type MouseEvent, } from "react"; import clsx from "clsx"; +import { useShallow } from "zustand/react/shallow"; +import { basename } from "@/platform/project"; import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc"; import { shortcutLabel } from "@/platform/keymap"; import { setContext } from "@/platform/context"; @@ -35,7 +37,7 @@ import { resolveTarget, type EditBlockReason, } from "./resultEditing"; -import { pageWindow } from "./resultView"; +import { formatElapsed, pageWindow } from "./resultView"; import { resultTabMenu } from "./resultTabActions"; import { analyze } from "./sql/analyze"; import { nameMatcher } from "./sql/dialect"; @@ -55,6 +57,7 @@ import { rerunResult, useDatabase, withConnection, + type ConsoleExecution, type OutputLine, type ResultTab, } from "./store"; @@ -744,8 +747,40 @@ function PinButton({ tab }: { tab: ResultTab }) { ); } +/** The most recently started console request, while it runs. */ +function useLatestExecution(): [string, ConsoleExecution] | undefined { + return useDatabase( + useShallow((s) => { + let latest: [string, ConsoleExecution] | undefined; + for (const entry of Object.entries(s.executions)) + if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry; + return latest; + }), + ); +} + +function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExecution }) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), 100); + return () => clearInterval(timer); + }, [execution.startedAt]); + const name = basename(path); + const count = execution.statements; + return ( +
+ + + {count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`} + + {formatElapsed(Math.max(0, now - execution.startedAt))} +
+ ); +} + export function ResultsView() { const results = useDatabase((s) => s.results); + const execution = useLatestExecution(); const active = useDatabase((s) => s.activeResult); const hasOutput = useDatabase((s) => s.output.length > 0); const root = useRef(null); @@ -772,6 +807,8 @@ export function ResultsView() { owner: e.currentTarget, }); }; + const executing = execution && ; + if (!results.length && !hasOutput && executing) return
{executing}
; if (!results.length && !hasOutput) return ( @@ -825,6 +862,7 @@ export function ResultsView() { ]} /> + {executing}
(); const runField = StateField.define({ - create: () => ({ marks: [], banner: null }), + create: () => ({ marks: [], banner: null, executing: null }), update(value, tr) { for (const e of tr.effects) if (e.is(setRun)) return e.value; if (!tr.docChanged) return value; + // The request runs the text it was sent; edits only move where that shows. + const ex = value.executing; + const executing = ex && { + ...ex, + spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })), + at: tr.changes.mapPos(ex.at), + }; // Editing a statement drops its mark. const marks: RunMark[] = []; for (const m of value.marks) { @@ -135,12 +165,18 @@ const runField = StateField.define({ timingAt: tr.changes.mapPos(m.timingAt), }); } - return { ...value, marks }; + return { ...value, marks, executing }; }, provide: (f) => [ EditorView.decorations.from(f, (st) => { const ranges = []; + const ex = st.executing; + for (const r of ex?.spans ?? []) + if (r.from < r.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(r.from, r.to)); + if (ex) ranges.push(Decoration.widget({ widget: new ElapsedWidget(ex.startedAt), side: 1 }).range(ex.at)); for (const m of st.marks) { + // The new run takes the place of a statement's last outcome. + if (ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) continue; if (m.error) ranges.push( Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to), @@ -164,11 +200,47 @@ class TimingWidget extends WidgetType { toDOM() { const span = document.createElement("span"); span.className = "cm-openidea-db-timing"; - span.textContent = this.ms < 1000 ? `${Math.round(this.ms)} ms` : `${(this.ms / 1000).toFixed(1)} s`; + span.textContent = formatElapsed(this.ms); return span; } } +/** The running time of the request, ticking until it ends. */ +class ElapsedWidget extends WidgetType { + private timer: ReturnType | undefined; + constructor(readonly startedAt: number) { + super(); + } + eq(other: ElapsedWidget) { + return other.startedAt === this.startedAt; + } + toDOM() { + const span = document.createElement("span"); + span.className = "cm-openidea-db-timing cm-openidea-db-elapsed"; + const tick = () => { + const elapsed = formatElapsed(Date.now() - this.startedAt); + span.textContent = tx`Executing… ${elapsed}`; + }; + tick(); + this.timer = setInterval(tick, 100); + return span; + } + destroy() { + clearInterval(this.timer); + } +} + +class ExecutingMarker extends GutterMarker { + eq(other: GutterMarker) { + return other instanceof ExecutingMarker; + } + toDOM() { + const el = spinnerNode(12, "cm-openidea-db-run-executing"); + el.title = tx("Executing"); + return el; + } +} + class RunMarker extends GutterMarker { constructor(readonly error: string | null) { super(); @@ -192,9 +264,12 @@ const runGutter = gutter({ markers: (view) => { const st = view.state.field(runField); const doc = view.state.doc; - const ranges = st.marks - .filter((m) => m.from <= doc.length) + const ex = st.executing; + const ranges: Range[] = st.marks + .filter((m) => m.from <= doc.length && !ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) .map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from)); + const first = ex?.spans[0]; + if (first && first.from <= doc.length) ranges.push(new ExecutingMarker().range(doc.lineAt(first.from).from)); return RangeSet.of(ranges, true); }, }); @@ -233,20 +308,59 @@ export function markOutcomes(view: EditorView, outcomes: readonly DbStatementOut })); const failed = outcomes.find((o) => o.error); const name = failed ? (sourceById(consoleSource(view.state.facet(consolePath)))?.name ?? "") : ""; - view.dispatch({ effects: setRun.of({ marks, banner: failed ? `[${name}] ${failed.error}` : null }) }); + view.dispatch({ + effects: setRun.of({ ...view.state.field(runField), marks, banner: failed ? `[${name}] ${failed.error}` : null }), + }); +} + +let nextExecution = 0; + +/** `outcomes` at where their statements are now, when the text was edited while they ran. */ +function placed( + executing: Executing | null, + token: number, + outcomes: readonly DbStatementOutcome[], +): readonly DbStatementOutcome[] { + if (executing?.token !== token) return outcomes; + return outcomes.map((o) => { + const i = executing.sent.findIndex((r) => r.from === o.statement.from && r.to === o.statement.to); + const now = executing.spans[i]; + return now ? { ...o, statement: { ...o.statement, from: now.from, to: now.to } } : o; + }); +} + +/** Runs `from`–`to` of `view`, showing the submitted statements as executing until the request ends. */ +async function executeRange(view: EditorView, path: string, from: number, to: number) { + const token = ++nextExecution; + const sent = view.state.doc; + const start = (statements: readonly SqlStatement[]) => { + // The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced. + if (view.state.doc !== sent) return; + const spans = statements.map((st) => ({ from: st.from, to: st.to })); + const last = spans.at(-1); + if (!last) return; + const at = view.state.sliceDoc(last.to, last.to + 1) === ";" ? last.to + 1 : last.to; + const executing = { token, sent: spans, spans, at, startedAt: Date.now() }; + view.dispatch({ effects: setRun.of({ ...view.state.field(runField), executing }) }); + }; + try { + const outcomes = await executeConsole(path, sent.toString(), from, to, start); + if (outcomes.length) markOutcomes(view, placed(view.state.field(runField).executing, token, outcomes)); + } finally { + const st = view.state.field(runField, false); + if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) }); + } } /** Runs the statement at the caret (or the selected ones) of `view`. */ export async function executeInView(view: EditorView, path: string) { const sel = view.state.selection.main; - const outcomes = await executeConsole(path, view.state.doc.toString(), sel.from, sel.to); - if (outcomes.length) markOutcomes(view, outcomes); + await executeRange(view, path, sel.from, sel.to); } /** Runs every statement of `view`, in order (stops at the first that fails). */ export async function executeScriptInView(view: EditorView, path: string) { - const outcomes = await executeConsole(path, view.state.doc.toString(), 0, view.state.doc.length); - if (outcomes.length) markOutcomes(view, outcomes); + await executeRange(view, path, 0, view.state.doc.length); } /** Explain Plan of the statement at the caret (or the first selected one) of `view`. */ diff --git a/src/features/database/inEditorResults.test.tsx b/src/features/database/inEditorResults.test.tsx index a882ae55e6..dd2c68436f 100644 --- a/src/features/database/inEditorResults.test.tsx +++ b/src/features/database/inEditorResults.test.tsx @@ -3,9 +3,10 @@ import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useProject } from "@/platform/project"; -import { consoleExtension } from "./console"; +import { consoleExtension, executeScriptInView } from "./console"; import { SQL_LANGUAGE } from "./sqlLanguage"; import { executeConsole, rerunResult, useDatabase } from "./store"; +import { provideToolWindowService } from "@/workbench/contributions"; const backend = vi.hoisted(() => ({ execute: vi.fn(), statements: vi.fn() })); @@ -30,6 +31,7 @@ const initial = useDatabase.getState(); let runs = 0; beforeEach(() => { + provideToolWindowService({ show: () => {} } as never); runs = 0; useProject.setState({ project: { name: "p", root: "/p", trusted: true } as never, @@ -134,3 +136,59 @@ describe("In-Editor Results", () => { view.destroy(); }); }); + +describe("statements in flight", () => { + it("marks what was submitted with its running time, then the outcome", async () => { + const parent = document.createElement("div"); + document.body.append(parent); + const doc = "SELECT 1;\nSELECT 2;\n"; + const view = new EditorView({ + parent, + state: EditorState.create({ + doc, + extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never), + }), + }); + let finish!: () => void; + const gate = new Promise((resolve) => { + finish = resolve; + }); + const execute = backend.execute.getMockImplementation()!; + backend.execute.mockImplementationOnce(async (...args: unknown[]) => { + await gate; + return execute(...(args as Parameters)); + }); + const executing = () => [...view.dom.querySelectorAll(".cm-openidea-db-executing")].map((e) => e.textContent); + const elapsed = () => view.dom.querySelector(".cm-openidea-db-elapsed")?.textContent; + + let pending!: Promise; + await act(async () => { + pending = executeScriptInView(view, PATH); + await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled()); + }); + expect(executing()).toEqual(["SELECT 1", "SELECT 2"]); + expect(elapsed()).toMatch(/^Executing… \d+ ms$/); + expect(view.dom.querySelector(".cm-openidea-db-run-executing")).not.toBeNull(); + + // Typing above moves the marks with their text. + act(() => view.dispatch({ changes: { from: 0, insert: "-- a longer note above\n" } })); + expect(executing()).toEqual(["SELECT 1", "SELECT 2"]); + + await act(async () => { + finish(); + await pending; + }); + expect(executing()).toEqual([]); + expect(elapsed()).toBeUndefined(); + // The outcomes land on the statements, not on where they were when sent. + const lines = [...view.dom.querySelectorAll(".cm-openidea-db-gutter .cm-gutterElement")] + .filter((e) => e.querySelector(".cm-openidea-db-run-ok")) + .map((e) => e.getBoundingClientRect().top); + expect(lines).toHaveLength(2); + expect(view.dom.querySelectorAll(".cm-openidea-db-timing")).toHaveLength(2); + expect(view.state.doc.lineAt(view.posAtDOM(view.dom.querySelector(".cm-openidea-db-timing")!)).text).toBe( + "SELECT 1;", + ); + view.destroy(); + }); +}); diff --git a/src/features/database/index.ts b/src/features/database/index.ts index f1212adab5..2419dc64d0 100644 --- a/src/features/database/index.ts +++ b/src/features/database/index.ts @@ -157,6 +157,7 @@ export function activate(): () => void { manualCommit: new Set(), pendingTx: new Set(), running: {}, + executions: {}, dialog: null, newMenuOpen: false, }); diff --git a/src/features/database/requestLifecycle.test.ts b/src/features/database/requestLifecycle.test.ts index 74bddfecff..1a8db190b2 100644 --- a/src/features/database/requestLifecycle.test.ts +++ b/src/features/database/requestLifecycle.test.ts @@ -67,6 +67,7 @@ import { useDatabase, withConnection, } from "./store"; +import { provideToolWindowService } from "@/workbench/contributions"; const initial = useDatabase.getState(); const initialProject = useProject.getState(); @@ -129,6 +130,8 @@ function switchProject(project: ProjectInfo) { } beforeEach(() => { + // `showServiceView` reaches the real service, not the mocked accessor above. + provideToolWindowService({ show: ui.show } as never); vi.resetAllMocks(); useProject.setState({ project: projectA }); savedSources = [pg, other]; diff --git a/src/features/database/resultView.ts b/src/features/database/resultView.ts index 56b16052c4..6c779c6e80 100644 --- a/src/features/database/resultView.ts +++ b/src/features/database/resultView.ts @@ -1,7 +1,7 @@ /** * Pure helpers of the result views: IDEA's local filter and client-side sort * of loaded rows, search in the grid, paging of console results, the - * Aggregates of a selection, and the series of the chart. + * Aggregates of a selection, the series of the chart, and how long a statement took. */ import type { Cell } from "./model"; @@ -462,3 +462,8 @@ export function pageWindow({ page, pageSize, rows, hasMore, total }: PageState): export function pageFetch(page: number, pageSize: number): { maxRows: number; skip: number } { return { maxRows: pageSize, skip: page * pageSize }; } + +/** A statement's run time as IDEA shows it: `840 ms`, `3.2 s`. */ +export function formatElapsed(ms: number): string { + return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`; +} diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx index 050173e809..cc8c33045f 100644 --- a/src/features/database/results-view.test.tsx +++ b/src/features/database/results-view.test.tsx @@ -9,6 +9,7 @@ import { ResultsView } from "./ResultsView"; import { executeConsole, explainConsole, pinResult, rerunResult, useDatabase, type ResultTab } from "./store"; import { registerResultTabActions } from "./resultTabActions"; import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus"; +import { provideToolWindowService } from "@/workbench/contributions"; const backend = vi.hoisted(() => ({ driver: "postgres" as DbDriver, @@ -95,6 +96,7 @@ function show(text: string, columns: Array<{ name: string }>, rows: (string | nu } beforeEach(() => { + provideToolWindowService({ show: () => {} } as never); vi.clearAllMocks(); backend.statements.mockImplementation((_id: unknown, text: string) => Promise.resolve({ status: "ok", data: [{ from: 0, to: text.length, text }] }), @@ -809,3 +811,64 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab expect(useDatabase.getState().activeResult).toBe(fresh); }); }); + +describe("a console request in flight", () => { + const hold = () => { + let finish!: () => void; + const gate = new Promise((resolve) => { + finish = resolve; + }); + const execute = backend.execute.getMockImplementation()!; + backend.execute.mockImplementationOnce(async (...args: unknown[]) => { + await gate; + return execute(...(args as Parameters)); + }); + return () => finish(); + }; + + it("shows that it is executing instead of No results on a first run", async () => { + show("SELECT 1", [{ name: "id" }], [["1"]]); + useDatabase.setState({ results: [], activeResult: null, consoles: { "console.sql": "pg" } }); + const finish = hold(); + await act(async () => render()); + let pending!: Promise; + await act(async () => { + pending = executeConsole("console.sql", "SELECT pg_sleep(5)", 0, 0); + await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled()); + }); + expect(screen.queryByText("No results")).toBeNull(); + expect(screen.getByText("Executing in console.sql…").parentElement).toHaveTextContent(/\d+ ms$/); + await act(async () => { + finish(); + await pending; + }); + expect(screen.queryByText(/Executing in/)).toBeNull(); + expect(useDatabase.getState().executions).toEqual({}); + }); + + it("keeps the previous result visible while the next run executes", async () => { + show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]); + useDatabase.setState({ consoles: { "console.sql": "pg" } }); + backend.statements.mockResolvedValueOnce({ + status: "ok", + data: [ + { from: 0, to: 8, text: "SELECT 1" }, + { from: 10, to: 18, text: "SELECT 2" }, + ], + }); + const finish = hold(); + await act(async () => render()); + let pending!: Promise; + await act(async () => { + pending = executeConsole("console.sql", "SELECT 1; SELECT 2", 0, 18); + await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled()); + }); + expect(screen.getByText("Executing 2 statements in console.sql…")).toBeTruthy(); + expect(screen.getByText("Ann")).toBeTruthy(); + await act(async () => { + finish(); + await pending; + }); + expect(screen.queryByText(/Executing/)).toBeNull(); + }); +}); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 212917e72b..b1e386dd1f 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -174,6 +174,12 @@ export interface SourceCatalog { databases: Record; } +export interface ConsoleExecution { + startedAt: number; + /** Statements submitted (a batch runs them in order; the backend doesn't say which one is current). */ + statements: number; +} + interface DatabaseState { sources: DataSource[]; loaded: boolean; @@ -205,6 +211,8 @@ interface DatabaseState { output: OutputLine[]; /** Console path → running request. */ running: Record; + /** Console path → what its running request submitted, and since when (ms since the epoch). */ + executions: Record; maxRows: number; dialog: DialogState | null; /** Target of the tree's lead node. */ @@ -271,6 +279,7 @@ export const useDatabase = create(() => ({ activeResult: null, output: [], running: {}, + executions: {}, maxRows: 500, dialog: null, selectedSource: null, @@ -1233,6 +1242,8 @@ export async function executeConsole( text: string, from: number, to: number, + /** Called once the statements are submitted, with what was submitted. */ + onStart?: (statements: readonly SqlStatement[]) => void, ): Promise { const id = consoleSource(path); if (!id) { @@ -1252,8 +1263,14 @@ export async function executeConsole( const prev = useDatabase.getState().running[path]; if (prev) void commands.cancelRequest(prev); const request = nextRequestId(); - useDatabase.setState((s) => ({ running: { ...s.running, [path]: request } })); + useDatabase.setState((s) => ({ + running: { ...s.running, [path]: request }, + executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } }, + })); + onStart?.(statements); try { + // IDEA brings the results up as the run starts, showing it executing. + if (!inEditorResults()) showServiceView(RESULTS_VIEW, false); const pageSize = useDatabase.getState().maxRows; const schema = consoleSchema(path) || (await loadCompletion(id))?.defaultSchema || ""; if (!current()) return []; @@ -1296,7 +1313,9 @@ export async function executeConsole( if (s.running[path] !== request) return s; const running = { ...s.running }; delete running[path]; - return { running }; + const executions = { ...s.executions }; + delete executions[path]; + return { running, executions }; }); } } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 70d1964192..92a13c9093 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -166,6 +166,10 @@ "Select Next Tab": "Select Next Tab", "Select Previous Tab": "Select Previous Tab", "Result {n}-{index}": "Result {n}-{index}", + "Executing": "Executing", + "Executing {count} statements in {name}…": "Executing {count} statements in {name}…", + "Executing in {name}…": "Executing in {name}…", + "Executing… {elapsed}": "Executing… {elapsed}", "Absolute": "Absolute", "Relative": "Relative", "Hybrid": "Hybrid", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index cab44ad2b4..42830a83b3 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -4861,6 +4861,10 @@ "Remove data source '{name}'? Its query console file stays on disk.": "是否移除数据源 '{name}'?其查询控制台文件将保留在磁盘上。", "Result {n}": "结果 {n}", "Result {n}-{index}": "结果 {n}-{index}", + "Executing": "正在执行", + "Executing {count} statements in {name}…": "正在 {name} 中执行 {count} 条语句…", + "Executing in {name}…": "正在 {name} 中执行…", + "Executing… {elapsed}": "正在执行… {elapsed}", "{name} has uncommitted changes. Commit or roll them back before switching to auto-commit?": "{name} 有未提交的更改。是否在切换到自动提交前提交或回滚这些更改?", "Cannot copy the name": "无法复制名称", "Cannot copy the reference": "无法复制引用", diff --git a/src/ui/iconNode.ts b/src/ui/iconNode.ts index d20f4937e7..b0ce7698a0 100644 --- a/src/ui/iconNode.ts +++ b/src/ui/iconNode.ts @@ -1,5 +1,6 @@ /** Design-system icons as DOM nodes for CodeMirror widgets. */ import { iconMarkupOrFallback, type IconName } from "./icons"; +import spinnerStyles from "./Spinner.module.css"; export function iconNode(name: IconName | (string & {}), size = 16, className?: string): HTMLElement { const span = document.createElement("span"); @@ -8,3 +9,16 @@ export function iconNode(name: IconName | (string & {}), size = 16, className?: span.innerHTML = iconMarkupOrFallback(name, size); return span; } + +/** The ring `Spinner` as a DOM node for CodeMirror widgets and gutters. */ +export function spinnerNode(size = 14, className?: string): HTMLElement { + const span = document.createElement("span"); + span.className = className ? `cm-openidea-icon ${className}` : "cm-openidea-icon"; + span.setAttribute("aria-hidden", "true"); + span.innerHTML = + `` + + '' + + '' + + ""; + return span; +} From f0273690b98ed5871fff6e8b78d130723883e512 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:07:52 +0800 Subject: [PATCH 02/14] fix(run): keep test results readable in narrow panes (#4586) The test tree's header held the counts, duration and every toolbar action in one 28px row, so narrow Run panes clipped the counts and buttons. As in IDEA's new layout, the status (icon, counts, total duration) now sits above the console, Expand All, Collapse All and Export Test Results move into a More Actions menu, and the tree and console stack vertically below 560px with their own remembered split. --- e2e/run.spec.ts | 79 ++++++++++++++++++- src/features/run/Run.module.css | 37 +++++++-- src/features/run/RunView.tsx | 47 +++++++++-- src/features/run/TestTreeView.test.tsx | 30 ++++--- src/features/run/TestTreeView.tsx | 103 ++++++++++++++++++------- 5 files changed, 239 insertions(+), 57 deletions(-) diff --git a/e2e/run.spec.ts b/e2e/run.spec.ts index 0d6edf708d..b2fd1ff95c 100644 --- a/e2e/run.spec.ts +++ b/e2e/run.spec.ts @@ -3,15 +3,21 @@ * the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them. */ import type { Page } from "@playwright/test"; +import type { RunConfig } from "../src/bindings"; import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; const RUN_ID = 7; /** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */ -async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) { +async function stubRun( + page: Page, + output: { kind: string; text: string }[], + exit: number | null, + overrides: Partial = {}, +) { await stubDesktop(page); await page.evaluate( - async ({ output, exit, runId }) => { + async ({ output, exit, runId, overrides }) => { const config = { id: "npm:dev", name: "dev", @@ -23,6 +29,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi detected: false, isTest: false, debugAdapter: null, + ...overrides, }; const h = window.__ipc.handlers; h.run_configs = () => [config]; @@ -43,7 +50,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi await loadConfigs(); selectConfig(config.id); }, - { output, exit, runId: RUN_ID }, + { output, exit, runId: RUN_ID, overrides }, ); } @@ -177,6 +184,72 @@ test("Go reruns keep each package's exact failures and the original configuratio ]); }); +test("test results keep counts, actions and selected output visible as the pane narrows", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1060, height: 740 }); + const goPackage = "example.com/checkout"; + const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations"; + const message = "expected subtotal 42, got 37"; + const records = [ + { Action: "run", Test: name }, + { Action: "output", Test: name, Output: message + "\n" }, + { Action: "fail", Test: name, Elapsed: 0.125 }, + { Action: "pass", Test: "TestPayment", Elapsed: 0.02 }, + { Action: "skip", Test: "TestDelayedShipping" }, + { Action: "fail", Elapsed: 0.17 }, + ]; + await stubRun( + page, + records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })), + 1, + { + id: "go:checkout-tests", + name: "Checkout tests", + kind: "go", + command: "go", + args: ["test", "-json"], + isTest: true, + }, + ); + await page.keyboard.press("Control+r"); + const run = page.getByRole("region", { name: "Run", exact: true }); + const tree = run.getByRole("tree", { name: "Test results" }); + const row = tree.getByRole("treeitem", { name: new RegExp(name) }); + await row.click(); + const output = run.getByRole("log"); + await expect(output).toContainText(message); + await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true); + await page.setViewportSize({ width: 540, height: 740 }); + await expect + .poll(async () => { + const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]); + return !!list && !!console && console.y >= list.y + list.height - 1; + }) + .toBe(true); + const summary = run.getByRole("status").filter({ hasText: "1 failing" }); + for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible(); + await expect(row).toHaveAttribute("aria-selected", "true"); + await expect(row.getByText("125 ms")).toBeVisible(); + await expect(output).toContainText(message); + const toolbar = run.getByRole("toolbar", { name: "Test results" }); + await toolbar.getByRole("button", { name: "More Actions" }).click(); + await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible(); + await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible(); + await page.keyboard.press("Escape"); + const divider = run.getByRole("separator"); + const treeHeight = async () => (await tree.boundingBox())!.height; + const beforeResize = await treeHeight(); + await divider.press("ArrowDown"); + await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1); + const customizedHeight = await treeHeight(); + await page.setViewportSize({ width: 1060, height: 740 }); + await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true); + await page.setViewportSize({ width: 540, height: 740 }); + await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2); + await expect(output).toContainText(message); +}); + test("CMake builds the selected target in Build before starting only the application in Run", async ({ workbench: page, }) => { diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index 113d360188..bcc40ebb2a 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -253,26 +253,44 @@ flex-direction: column; height: 100%; min-width: 0; - border-right: 1px solid var(--border); } -.testHeader { +.testToolbar, +.testStatusBar { flex: none; display: flex; + flex-wrap: wrap; align-items: center; - gap: var(--space-2); - height: 28px; - padding: 0 4px 0 10px; + min-height: 28px; border-bottom: 1px solid var(--border); +} +.testToolbar { + gap: var(--space-0-5); + padding: var(--space-0-5) var(--space-1); +} +.testStatusBar { + gap: var(--space-0-5) var(--space-2); + padding: var(--space-0-5) var(--space-2); font-size: var(--fs-ui); color: var(--fg-secondary); } .testCounts { + flex: 1 1 auto; display: flex; - gap: 10px; + flex-wrap: wrap; + gap: var(--space-0-5) var(--space-2); min-width: 0; - overflow: hidden; white-space: nowrap; } +.testStatus, +.testTotalDuration { + flex: none; +} +.testTotalDuration { + margin-left: auto; + color: var(--fg-subtle); + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} .testTree { flex: 1; min-height: 0; @@ -299,8 +317,11 @@ flex: none; padding-right: 8px; color: var(--fg-subtle); - font-family: var(--font-mono); font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} +.testTree [aria-selected="true"] .testDuration { + color: var(--fg); } .testEmpty { padding: 12px; diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx index eb77d7a7ab..f1051c4802 100644 --- a/src/features/run/RunView.tsx +++ b/src/features/run/RunView.tsx @@ -1,5 +1,6 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import clsx from "clsx"; +import type { GroupImperativeHandle, Layout } from "react-resizable-panels"; import type { RunConfig } from "@/platform/ipc"; import type { RunTargetValid } from "@/platform/remoteSettings"; import { useAgentRunSettings, useWorkflowSettings } from "@/platform/workflowSettings"; @@ -47,7 +48,7 @@ import { } from "./store"; import { rerunFailedConfigs } from "./testing/rerun"; import { formatDuration, nodeOutput } from "./testing"; -import { TestTreeView } from "./TestTreeView"; +import { TestStatusBar, TestTreeView } from "./TestTreeView"; import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace"; import { closeRunTab, runTabMenu } from "./runTabs"; import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate"; @@ -59,6 +60,11 @@ import { archivedAgentSessions, closeAgentArchive } from "./agentRuns"; import styles from "./Run.module.css"; import { tx } from "@/platform/i18n"; +const TEST_SPLIT_DEFAULTS = { + horizontal: { tests: 34, console: 66 }, + vertical: { tests: 48, console: 52 }, +}; + function failed(s: RunSession): boolean { return s.status === "failed" || (s.status === "finished" && s.exitCode !== 0 && !s.stopped); } @@ -93,6 +99,25 @@ export function SessionPanel({ const softWrap = wrapOverride ?? defaultWrap; const [selectedTest, setSelectedTest] = useState(null); const [findOpen, setFindOpen] = useState(false); + const body = useRef(null); + const [stackedTests, setStackedTests] = useState(false); + const testSplit = useRef(null); + const testLayouts = useRef>({ ...TEST_SPLIT_DEFAULTS }); + const testOrientation = stackedTests ? "vertical" : "horizontal"; + const hasTests = !!rt?.tests; + useLayoutEffect(() => { + const pane = body.current; + if (!hasTests || !pane) return; + const measure = () => setStackedTests(pane.clientWidth < 560); + measure(); + if (typeof ResizeObserver === "undefined") return; + const resize = new ResizeObserver(measure); + resize.observe(pane); + return () => resize.disconnect(); + }, [hasTests]); + useLayoutEffect(() => { + if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]); + }, [hasTests, testOrientation]); const running = isLive(session); const cwd = runDirectory(session.config.cwd); const baseConfig = useRun(() => baseConfigOf(session)); @@ -136,6 +161,7 @@ export function SessionPanel({ const consoleColumn = (
+ {rt.tests && } {rt.console.dropped > 0 && !testModel && (
{tx`${rt.console.dropped.toLocaleString()} earlier lines were discarded`}
)} @@ -279,10 +305,19 @@ export function SessionPanel({ />
-
+
{rt.tests ? ( - - + { + if (meta.isUserInteraction) testLayouts.current[testOrientation] = meta.requestedLayout ?? layout; + }} + > + - + {consoleColumn} diff --git a/src/features/run/TestTreeView.test.tsx b/src/features/run/TestTreeView.test.tsx index be22eeef85..c77b5ee5e1 100644 --- a/src/features/run/TestTreeView.test.tsx +++ b/src/features/run/TestTreeView.test.tsx @@ -49,6 +49,12 @@ function Host(props: { ); } +function moreItem(name: string) { + const trigger = screen.getByRole("button", { name: "More Actions" }); + if (trigger.getAttribute("aria-expanded") !== "true") fireEvent.click(trigger); + return screen.getByRole("menuitem", { name }); +} + describe("TestTreeView", () => { beforeEach(() => localStorage.clear()); afterEach(() => vi.clearAllMocks()); @@ -264,17 +270,17 @@ describe("Expand All / Collapse All", () => { expect(rows()).toContain("reuses()"); }); - it("the buttons run the actions, and are unavailable without suites", () => { + it("the menu runs the actions, and they are unavailable without suites", () => { const dispose = registerActions([ { id: "run.expandAllTests", title: "Expand All", run: () => {} }, { id: "run.collapseAllTests", title: "Collapse All", run: () => {} }, ]); onTestFinished(dispose); const { unmount } = render(view(nested())); - fireEvent.click(screen.getByRole("button", { name: "Expand All" })); - expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined); - fireEvent.click(screen.getByRole("button", { name: "Collapse All" })); - expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined); + fireEvent.click(moreItem("Expand All")); + expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests"); + fireEvent.click(moreItem("Collapse All")); + expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests"); unmount(); expect(testTree.expandAll).toBeNull(); @@ -282,8 +288,8 @@ describe("Expand All / Collapse All", () => { flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]); flat.finish(1); render(view(flat)); - expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled(); - expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled(); + expect(moreItem("Expand All")).toHaveAttribute("aria-disabled", "true"); + expect(moreItem("Collapse All")).toHaveAttribute("aria-disabled", "true"); }); }); @@ -306,9 +312,9 @@ describe("Export Test Results", () => { /> ); - it("the button and the action open the dialog for the finished run", () => { + it("the menu and the action open the dialog for the finished run", () => { const { unmount } = render(view(finished(), false)); - fireEvent.click(screen.getByRole("button", { name: "Export Test Results…" })); + fireEvent.click(moreItem("Export Test Results…")); expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); act(() => testTree.exportResults!()); @@ -322,13 +328,13 @@ describe("Export Test Results", () => { it("is unavailable while the tests run and without results", () => { const { rerender } = render(view(finished(), true)); - expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled(); + expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true"); expect(testTree.exportResults).toBeNull(); rerender(view(new TestResults(), false)); - expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled(); + expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true"); expect(testTree.exportResults).toBeNull(); rerender(view(finished(), false)); - expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeEnabled(); + expect(moreItem("Export Test Results…")).not.toHaveAttribute("aria-disabled", "true"); expect(testTree.exportResults).not.toBeNull(); }); }); diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx index 3f3b221d0d..21467c36a1 100644 --- a/src/features/run/TestTreeView.tsx +++ b/src/features/run/TestTreeView.tsx @@ -9,6 +9,7 @@ import { showContextMenu, useContextMenuStore, Spinner, + Toolbar, Tree, type MenuItem, type TreeHandle, @@ -83,6 +84,41 @@ export function StatusIcon({ status }: { status: TestStatus | null }) { } } +export function TestStatusBar({ + results, + version, + running, +}: { + results: TestResults; + version: number; + running: boolean; +}) { + const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps + const status = running + ? "running" + : counts.failed + ? "failed" + : counts.passed + ? "passed" + : counts.skipped + ? "skipped" + : null; + const duration = results.summary.durationMs; + + return ( +
+ + + {counts.failed > 0 && {tx`${counts.failed} failing`}} + {counts.passed > 0 && {tx`${counts.passed} passed`}} + {counts.skipped > 0 && {tx`${counts.skipped} ignored`}} + {counts.total === 0 && {running ? tx("Running…") : tx("No tests")}} + + {duration !== undefined && {formatDuration(duration)}} +
+ ); +} + const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed"; const treeModel = { @@ -163,6 +199,8 @@ export function TestTreeView({ }); const sortButton = useRef(null); const [sortMenu, setSortMenu] = useState(false); + const moreButton = useRef(null); + const [moreMenu, setMoreMenu] = useState(false); const [expanded, setExpanded] = useState | null>(null); const [exporting, setExporting] = useState(false); const [selection, setSelection] = useState>(new Set()); @@ -226,7 +264,6 @@ export function TestTreeView({ } }; - const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps // Like IDEA, Sort by Duration applies once the run has finished, so rows don't jump while tests report. const byDuration = sortByDuration && !running; const roots = useMemo(() => { @@ -276,21 +313,9 @@ export function TestTreeView({ const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null; const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null; - const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null; - const duration = results.summary.durationMs; - return (
-
- - - {counts.failed > 0 && {tx`${counts.failed} failing`}} - {counts.passed > 0 && {tx`${counts.passed} passed`}} - {counts.skipped > 0 && {tx`${counts.skipped} ignored`}} - {counts.total === 0 && {running ? tx("Running…") : tx("No tests")}} - {duration !== undefined && {formatDuration(duration)}} - - + setSortMenu(false)} /> - - setExporting(true)} + title="More Actions" + aria-haspopup="menu" + aria-expanded={moreMenu} + onClick={() => setMoreMenu((open) => !open)} /> -
+ setMoreMenu(false)} + items={[ + { + icon: "expand-all", + label: "Expand All", + disabled: !hasSuites, + run: () => void executeAction("run.expandAllTests"), + }, + { + icon: "collapse-all", + label: "Collapse All", + disabled: !hasSuites, + run: () => void executeAction("run.collapseAllTests"), + }, + { kind: "separator" }, + { + icon: "export", + label: "Export Test Results…", + disabled: !canExport, + run: () => setExporting(true), + }, + ]} + /> + {exporting && ( setExporting(false)} /> )} @@ -396,7 +441,9 @@ export function TestTreeView({ return ( - {n.name} + + {n.name} + {d !== undefined && {formatDuration(d)}} ); From 750d35dd6ecf811e2e3ecb5df185b7e6d0433141 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:10:23 +0200 Subject: [PATCH 03/14] fix(vcs): discard stale status after project switch (#4598) The VCS store reset on project switch, but replies to refreshes started for the previous project still wrote to it, restoring its branch, changed files and decorations and firing conflict notifications. A project generation, bumped on every switch (also when reopening the same folder), now gates full and incremental refresh results, errors and discovered roots; queued paths are dropped on switch, and the refresh queue still drains for the active project. Closes #4596 Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- src/features/vcs/store.switch.test.ts | 208 ++++++++++++++++++++++++++ src/features/vcs/store.ts | 25 +++- src/test/deferred.ts | 9 ++ 3 files changed, 236 insertions(+), 6 deletions(-) create mode 100644 src/features/vcs/store.switch.test.ts create mode 100644 src/test/deferred.ts diff --git a/src/features/vcs/store.switch.test.ts b/src/features/vcs/store.switch.test.ts new file mode 100644 index 0000000000..72ad8f01e2 --- /dev/null +++ b/src/features/vcs/store.switch.test.ts @@ -0,0 +1,208 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings"; +import { commands, isTauri } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { deferred } from "@/test/deferred"; +import { getFileDecoration } from "@/workbench/contributions"; +import { + discoverRoots, + installVcsStore, + onConflictsAppeared, + onConflictsCleared, + refreshNow, + refreshPathsNow, + useVcs, +} from "./store"; + +vi.mock(import("@/platform/ipc"), async (original) => ({ + ...(await original()), + isTauri: vi.fn(() => false), +})); + +const git: ProjectInfo = { root: "/a", name: "a", isGit: true, trusted: true, settings: {} }; +const nonGit: ProjectInfo = { root: "/b", name: "b", isGit: false, trusted: true, settings: {} }; +const branch: BranchInfo = { + head: "feature-a", + headCommit: "abc1234", + upstream: null, + ahead: 0, + behind: 0, + operation: "merge", +}; +const roots: VcsRoot[] = [{ root: git.root, head: branch.head, headCommit: branch.headCommit, operation: "merge" }]; +const conflicted: FileStatus = { + path: "/a/src/conflict.ts", + relPath: "src/conflict.ts", + staged: null, + unstaged: "conflicted", + renamedFrom: null, +}; +const modified: FileStatus = { + ...conflicted, + path: "/a/src/edited.ts", + relPath: "src/edited.ts", + unstaged: "modified", +}; +const status = [conflicted, modified]; + +type Ok = { status: "ok"; data: T }; +const ok = (data: T): Ok => ({ status: "ok", data }); + +let dispose: () => void; +const appeared = vi.fn(); +const cleared = vi.fn(); + +beforeEach(() => { + vi.spyOn(commands, "vcsRoots").mockResolvedValue(ok(roots)); + vi.spyOn(commands, "vcsStatus").mockResolvedValue(ok(status)); + vi.spyOn(commands, "vcsBranchInfo").mockResolvedValue(ok(branch)); + onConflictsAppeared(appeared); + onConflictsCleared(cleared); + dispose = installVcsStore(); +}); + +afterEach(() => { + dispose(); + onConflictsAppeared(() => undefined); + onConflictsCleared(() => undefined); + appeared.mockClear(); + cleared.mockClear(); + vi.restoreAllMocks(); + vi.mocked(isTauri).mockReset(); + useProject.setState(useProject.getInitialState(), true); + useVcs.setState(useVcs.getInitialState(), true); +}); + +describe("VCS status ownership", () => { + it.each([ + { command: "status", reopen: false }, + { command: "roots", reopen: false }, + { command: "status", reopen: true }, + ])("drops a late $command response after switching projects (reopen: $reopen)", async ({ command, reopen }) => { + const response = deferred(); + const request = + command === "status" + ? vi.mocked(commands.vcsStatus).mockReturnValueOnce(response.promise.then(() => ok(status))) + : vi.mocked(commands.vcsRoots).mockReturnValueOnce(response.promise.then(() => ok(roots))); + useProject.setState({ project: git }); + const refreshing = refreshNow(); + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledOnce()); + // Emulate desktop discovery of nested roots for the non-Git project; there are none. + vi.mocked(isTauri).mockReturnValueOnce(true); + vi.mocked(commands.vcsRoots).mockResolvedValueOnce(ok([])); + useProject.setState({ project: nonGit }); + const current = reopen ? { ...git } : nonGit; + if (reopen) useProject.setState({ project: current }); + const reset = useVcs.getState(); + expect(reset).toMatchObject({ root: current.root, status: [], branch: null, statusLoaded: false }); + + response.resolve(); + await refreshing; + + expect(useProject.getState().project).toBe(current); + expect.soft(useVcs.getState()).toEqual(reset); + expect.soft(getFileDecoration(conflicted.path)).toBeUndefined(); + expect.soft(getFileDecoration(modified.path)).toBeUndefined(); + expect.soft(appeared).not.toHaveBeenCalled(); + expect.soft(cleared).not.toHaveBeenCalled(); + } finally { + response.resolve(); + await refreshing; + } + }); + + it("does not publish an old refresh error in the new project", async () => { + const reply = deferred>(); + const request = vi.mocked(commands.vcsStatus).mockReturnValueOnce(reply.promise); + useProject.setState({ project: git }); + const refreshing = refreshNow(); + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledOnce()); + useProject.setState({ project: nonGit }); + const reset = useVcs.getState(); + + reply.reject(new Error("project A's Git status failed")); + await refreshing; + + expect(useVcs.getState()).toEqual(reset); + } finally { + reply.resolve(ok(status)); + await refreshing; + } + }); + + it("does not enable VCS from a discovery started before reopening the same folder", async () => { + const reply = deferred>(); + const request = vi.mocked(commands.vcsRoots).mockReturnValueOnce(reply.promise); + const folder = { ...git, isGit: false }; + useProject.setState({ project: folder }); + vi.mocked(isTauri).mockReturnValueOnce(true); + const discovering = discoverRoots(); + // Drain any incorrectly started full refresh before disposing. + const refreshed = deferred(); + const offRefresh = useVcs.subscribe((s, prev) => { + if (prev.loading && !s.loading) refreshed.resolve(); + }); + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledOnce()); + useProject.setState({ project: nonGit }); + useProject.setState({ project: { ...folder } }); + + reply.resolve(ok(roots)); + await discovering; + if (useVcs.getState().loading) await refreshed.promise; + + expect.soft(useVcs.getState()).toMatchObject({ root: folder.root, available: false, roots: [], status: [] }); + expect.soft(commands.vcsStatus).not.toHaveBeenCalled(); + } finally { + reply.resolve(ok([])); + await discovering; + if (useVcs.getState().loading) await refreshed.promise; + offRefresh(); + } + }); + + it("drains a queued refresh for the new project without retrying the old incremental refresh", async () => { + useProject.setState({ project: git }); + await refreshNow(); + const reply = deferred>(); + const request = vi.spyOn(commands, "vcsStatusPaths").mockReturnValueOnce(reply.promise); + const refreshing = refreshPathsNow([conflicted.path]); + let next: Promise | undefined; + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledWith([conflicted.path])); + const nextBranch = { ...branch, head: "main", operation: null }; + vi.mocked(commands.vcsRoots).mockResolvedValue( + ok([{ root: nonGit.root, head: nextBranch.head, headCommit: nextBranch.headCommit, operation: null }]), + ); + vi.mocked(commands.vcsStatus).mockResolvedValue(ok([])); + vi.mocked(commands.vcsBranchInfo).mockResolvedValue(ok(nextBranch)); + vi.mocked(isTauri).mockReturnValueOnce(true); + useProject.setState({ project: { ...nonGit, isGit: true } }); + next = refreshNow(); + + reply.resolve(ok([conflicted])); + await Promise.all([refreshing, next]); + + expect(useVcs.getState()).toMatchObject({ root: nonGit.root, status: [], branch: nextBranch }); + expect(getFileDecoration(conflicted.path)).toBeUndefined(); + expect(commands.vcsStatus).toHaveBeenCalledTimes(2); + } finally { + reply.resolve(ok([])); + await Promise.all([refreshing, next]); + } + }); + + it("applies branch, changed files, decorations and conflict notifications for the active project", async () => { + useProject.setState({ project: git }); + await refreshNow(); + + expect(useVcs.getState()).toMatchObject({ root: git.root, roots: [git.root], branch, status, statusLoaded: true }); + expect(useVcs.getState().byPath).toEqual(new Map(status.map((file) => [file.path, file]))); + expect(getFileDecoration(conflicted.path)?.color).toBe("var(--vcs-conflict)"); + expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)"); + expect(appeared).toHaveBeenCalledExactlyOnceWith([conflicted]); + expect(cleared).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/vcs/store.ts b/src/features/vcs/store.ts index 584f8a8911..afba340f33 100644 --- a/src/features/vcs/store.ts +++ b/src/features/vcs/store.ts @@ -152,6 +152,9 @@ export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState( return status.filter((f) => effectiveKind(f) === "conflicted"); } +// Reopening the same root starts a new lifetime. +let projectGeneration = 0; + let timer: ReturnType | undefined; /** A full refresh is queued; it answers for every path an incremental one would. */ let pendingFull = false; @@ -221,6 +224,7 @@ export function refreshNow(): Promise { }); return followUp; } + const generation = projectGeneration; inflight = (async () => { useVcs.setState({ loading: true }); try { @@ -238,6 +242,7 @@ export function refreshNow(): Promise { call(commands.vcsStatus()), scoped, ]); + if (generation !== projectGeneration) return; const roots = vcsRoots.map((r) => r.root); if ("error" in selected) { // The selected repository is gone (removed since the last scan): fall back to the primary one. @@ -263,9 +268,13 @@ export function refreshNow(): Promise { void refreshNow(); } } catch (e) { - useVcs.setState({ error: e instanceof Error ? e.message : String(e) }); + if (generation === projectGeneration) { + useVcs.setState({ error: e instanceof Error ? e.message : String(e) }); + } } finally { - useVcs.setState((st) => ({ loading: false, version: st.version + 1 })); + if (generation === projectGeneration) { + useVcs.setState((st) => ({ loading: false, version: st.version + 1 })); + } inflight = null; } })(); @@ -292,9 +301,11 @@ export function refreshPathsNow(paths: readonly string[]): Promise { }); return followUp; } + const generation = projectGeneration; const run = (async () => { try { const fresh = await call(commands.vcsStatusPaths([...paths])); + if (generation !== projectGeneration) return false; const current = useVcs.getState(); if (!current.statusLoaded || pairsRenames(current.status, paths, fresh)) return false; applyStatus(mergeStatus(current.status, paths, fresh), current.branch); @@ -306,7 +317,7 @@ export function refreshPathsNow(paths: readonly string[]): Promise { })(); const done = run.then((ok) => { inflight = null; - return ok ? undefined : refreshNow(); + return ok || generation !== projectGeneration ? undefined : refreshNow(); }); inflight = done; return done; @@ -396,10 +407,10 @@ export function statusOf(path: string): FileStatus | undefined { /** Repositories found below a project that is not itself under git (scanned in the background). */ export async function discoverRoots() { - const root = useVcs.getState().root; - if (!root || !isTauri()) return; + if (!useVcs.getState().root || !isTauri()) return; + const generation = projectGeneration; const roots = await call(commands.vcsRoots()).catch(() => []); - if (!roots.length || useVcs.getState().root !== root || useVcs.getState().available) return; + if (!roots.length || generation !== projectGeneration || useVcs.getState().available) return; useVcs.setState({ available: true }); setContext("vcsAvailable", true); void refreshNow(); @@ -412,7 +423,9 @@ export function installVcsStore(): () => void { const available = !!project?.isGit; const root = project?.root ?? null; if (useVcs.getState().root === root && useVcs.getState().available === available) return; + projectGeneration++; clearTimeout(timer); + pendingPaths.clear(); useVcs.setState({ ...initial, available, root, version: useVcs.getState().version + 1 }); setContext("vcsAvailable", available); setFileDecorations("vcs", new Map()); diff --git a/src/test/deferred.ts b/src/test/deferred.ts new file mode 100644 index 0000000000..126e5197aa --- /dev/null +++ b/src/test/deferred.ts @@ -0,0 +1,9 @@ +export function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} From 2ca0e195e5c7cb51250a67c1ba6924afa1cf3ce9 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:33:34 +0800 Subject: [PATCH 04/14] fix(editor): keep inline find controls inside narrow panes (#4588) The inline find/replace bar used a fixed grid with a 220px minimum field, so in narrow editor panes the counter, option buttons and Close spilled outside the pane. The bar is now a container-query layout: fields shrink, the action groups wrap, and below 500px (and again below 224px) the actions and replace field move to their own rows while Show Replace and Close stay reachable. --- e2e/editor.spec.ts | 42 +++ src/editor/core/view/EditorArea.module.css | 122 +++++-- src/editor/core/view/FindBar.tsx | 349 +++++++++++---------- 3 files changed, 316 insertions(+), 197 deletions(-) diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 1eb7ad2044..6a920e9023 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -232,6 +232,48 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => { await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2); }); +test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1120, height: 760 }); + const editor = await openFromTree(page, "build.gradle.kts"); + await editor.locator(".cm-content").click(); + await page.keyboard.press("Meta+r"); + const bar = page.getByRole("search", { name: "Replace in file" }); + const find = bar.getByRole("textbox", { name: "Find" }); + const replace = bar.getByRole("textbox", { name: "Replace" }); + const next = bar.getByRole("button", { name: /Next Occurrence/ }); + await find.fill("OrderDto"); + await find.press("Tab"); + await expect(replace).toBeFocused(); + await replace.fill("OrderView"); + const navigationIsBelowFind = async () => { + const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]); + return !!input && !!button && button.y >= input.y + input.height; + }; + const controlsFit = () => + bar.evaluate((panel) => { + const bounds = panel.getBoundingClientRect(); + return [...panel.querySelectorAll("button, textarea")].every((element) => { + const control = element.getBoundingClientRect(); + return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right; + }); + }); + await expect.poll(navigationIsBelowFind).toBe(false); + + await page.setViewportSize({ width: 590, height: 760 }); + await expect.poll(controlsFit).toBe(true); + await expect.poll(navigationIsBelowFind).toBe(true); + await page.setViewportSize({ width: 495, height: 760 }); + await expect.poll(controlsFit).toBe(true); + await expect(find).toHaveValue("OrderDto"); + await expect(replace).toHaveValue("OrderView"); + await next.click(); + await expect(bar.getByText(/^[12]\/2$/)).toBeVisible(); + await bar.getByRole("button", { name: "Replace All" }).click(); + await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2); + await bar.getByRole("button", { name: "Close", exact: true }).click(); + await expect(bar).toBeHidden(); +}); + test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({ workbench: page, }) => { diff --git a/src/editor/core/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index e491b6ae3f..c813c52573 100644 --- a/src/editor/core/view/EditorArea.module.css +++ b/src/editor/core/view/EditorArea.module.css @@ -151,52 +151,126 @@ } /* Find / replace bar */ -.find { +.findContainer { flex: none; - display: grid; - grid-template-columns: minmax(220px, 420px) auto 1fr; - align-items: center; - column-gap: var(--space-1-5); - row-gap: var(--space-1-5); - padding: 6px 8px 6px 10px; + min-width: 0; + container: editor-find / inline-size; background: var(--bg-editor-inline, var(--bg-elev)); border-bottom: 1px solid var(--border-editor-tabs, var(--border)); } -.findExpandable { - grid-template-columns: auto minmax(220px, 420px) auto 1fr; +.find { + display: grid; + grid-template-columns: [mode] auto [field] minmax(0, 420px) [actions] fit-content(50%) [close] minmax( + min-content, + 1fr + ); + align-items: start; + row-gap: var(--space-1); + padding: var(--space-1-5) var(--space-2); } .findExpand { - grid-column: 1; - grid-row: 1; -} -.findExpandable .findField { - grid-column: 2; + grid-area: 1 / mode; + margin-inline-end: var(--space-1); } .findField { + grid-area: 1 / field; +} +.replaceField { + grid-area: 2 / field; +} +.findField, +.replaceField { min-width: 0; } -.findButtons { +.findClose { + grid-area: 1 / close; + justify-self: end; + margin-inline-start: var(--space-1); +} +.findExpand, +.findClose { + margin-block-start: var(--space-1); +} +.findButtons, +.replaceButtons { display: flex; + flex-wrap: wrap; align-items: center; + min-width: 0; + min-height: var(--h-field); + margin-inline-start: var(--space-1-5); +} +.findButtons { + grid-area: 1 / actions; gap: var(--space-0-5); } +.replaceButtons { + grid-area: 2 / actions; + gap: var(--space-1); +} .findCount { - font-size: var(--fs-ui); + min-inline-size: 5ch; + padding-inline: var(--space-1); + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; color: var(--fg-subtle); - padding: 0 8px 0 4px; - min-width: 56px; white-space: nowrap; } .findCountNone { color: var(--danger); } -.findClose { - justify-self: end; + +@container editor-find (width < 500px) { + .find { + grid-template-columns: [mode] auto [field] minmax(0, 1fr) [close] auto; + } + .findButtons, + .replaceButtons { + grid-column: field / -1; + min-height: 0; + margin-inline-start: 0; + } + .findButtons { + grid-row: 2; + } + .replaceField { + grid-row: 3; + } + .replaceButtons { + grid-row: 4; + } + .replaceButtons > button { + max-width: 100%; + height: auto; + min-height: var(--h-control); + white-space: normal; + overflow-wrap: anywhere; + } } -.replaceButtons { - display: flex; - align-items: center; - gap: var(--space-1-5); + +@container editor-find (width < 224px) { + .findField, + .replaceField, + .replaceButtons { + grid-column: mode / -1; + } + .findExpand, + .findClose { + grid-row: 2; + margin-block-start: 0; + } + .findButtons { + grid-column: field; + } + .findInput { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(20px, 1fr)); + height: auto; + padding-block: var(--space-1); + } + .findInput textarea { + grid-column: 2 / -1; + } } /* Go to line */ diff --git a/src/editor/core/view/FindBar.tsx b/src/editor/core/view/FindBar.tsx index f419e138db..1b4a89b6b6 100644 --- a/src/editor/core/view/FindBar.tsx +++ b/src/editor/core/view/FindBar.tsx @@ -608,182 +608,185 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo const canReplace = !!opts.search && !invalid; return ( -
{ - focusedTarget = target; - setContext("findBarFocus", true); - setContext( - "findBarHasResults", - !!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total, - ); - }} - onBlurCapture={(e) => { - if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false); - }} - className={clsx(styles.find, onReplaceShown && styles.findExpandable)} - role="search" - aria-label={replace ? "Replace in file" : "Find in file"} - > - {onReplaceShown && ( - e.preventDefault()} - onClick={() => { - if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus(); - onReplaceShown(!replace); - }} +
+
{ + focusedTarget = target; + setContext("findBarFocus", true); + setContext( + "findBarHasResults", + !!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total, + ); + }} + onBlurCapture={(e) => { + if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false); + }} + className={styles.find} + role="search" + aria-label={replace ? "Replace in file" : "Find in file"} + > + {onReplaceShown && ( + e.preventDefault()} + onClick={() => { + if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus(); + onReplaceShown(!replace); + }} + /> + )} +
+ setOpts({ search })} + placeholder="Find" + aria-label="Find" + invalid={invalid || none} + multiline + onHistory={() => setHistoryMenu("find")} + onKeyDown={(e) => onKeyDown(e, "find")} + className={styles.findInput} + toggles={[ + { + id: "case", + icon: "case", + title: "Match Case", + shortcut: formatBinding("Alt+C"), + pressed: opts.caseSensitive, + onToggle: () => toggle("caseSensitive"), + }, + { + id: "word", + icon: "word", + title: "Words", + shortcut: formatBinding("Alt+W"), + pressed: opts.wholeWord, + onToggle: () => toggle("wholeWord"), + }, + { + id: "regex", + icon: "regex", + title: "Regex", + shortcut: formatBinding("Alt+X"), + pressed: opts.regexp, + onToggle: () => toggle("regexp"), + }, + ]} + /> +
+
+ + {counter} + + run(findPrevious)} + /> + run(findNext)} + /> + setFilterMenu(true)} + /> + setMoreMenu(true)} /> +
+ + {replace && ( + <> +
+ setOpts({ replace: value })} + placeholder="Replace" + aria-label="Replace" + multiline + onHistory={() => setHistoryMenu("replace")} + onKeyDown={(e) => onKeyDown(e, "replace")} + toggles={[ + { + id: "preserveCase", + icon: "preserve-case", + title: "Preserve Case", + pressed: opts.preserveCase, + onToggle: () => toggle("preserveCase"), + }, + ]} + /> +
+
+ + + +
+ + )} + setHistoryMenu(null)} /> - )} -
- setOpts({ search })} - placeholder="Find" - aria-label="Find" - invalid={invalid || none} - multiline - onHistory={() => setHistoryMenu("find")} - onKeyDown={(e) => onKeyDown(e, "find")} - toggles={[ - { - id: "case", - icon: "case", - title: "Match Case", - shortcut: formatBinding("Alt+C"), - pressed: opts.caseSensitive, - onToggle: () => toggle("caseSensitive"), - }, - { - id: "word", - icon: "word", - title: "Words", - shortcut: formatBinding("Alt+W"), - pressed: opts.wholeWord, - onToggle: () => toggle("wholeWord"), - }, - { - id: "regex", - icon: "regex", - title: "Regex", - shortcut: formatBinding("Alt+X"), - pressed: opts.regexp, - onToggle: () => toggle("regexp"), - }, - ]} + setMoreMenu(false)} + /> + setFilterMenu(false)} />
-
- - {counter} - - run(findPrevious)} - /> - run(findNext)} - /> - setFilterMenu(true)} - /> - setMoreMenu(true)} /> -
- - {replace && ( - <> -
- setOpts({ replace: value })} - placeholder="Replace" - aria-label="Replace" - multiline - onHistory={() => setHistoryMenu("replace")} - onKeyDown={(e) => onKeyDown(e, "replace")} - toggles={[ - { - id: "preserveCase", - icon: "preserve-case", - title: "Preserve Case", - pressed: opts.preserveCase, - onToggle: () => toggle("preserveCase"), - }, - ]} - /> -
-
- - - -
- - )} - setHistoryMenu(null)} - /> - setMoreMenu(false)} - /> - setFilterMenu(false)} - />
); } From 1ad8b06a1a168e11c248b49ccb22a3e96ab5d7ec Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:35:55 +0800 Subject: [PATCH 05/14] fix(markdown): keep the Project view clickable in Preview only (#4604) In Preview only the editor panel stays mounted but hidden, with no separator. react-resizable-panels adds an implicit resize region between two enabled panels without a separator; with the hidden panel's rect at zero it spanned everything left of the preview, showing a resize cursor and swallowing clicks in the Project view. The hidden editor panel is now disabled, leaving the group a single resizable panel. Fixes #4589 --- e2e/editor.spec.ts | 12 ++++++++++++ src/features/viewers/markdown/MarkdownEditor.tsx | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 6a920e9023..27db945149 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -638,3 +638,15 @@ test("dragging the Markdown split divider resizes and reflows editor and preview .poll(async () => Math.round((await reopenedEditor.boundingBox())!.width)) .toBe(Math.round(initialEditor)); }); + +test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => { + await openFromTree(page, "README.md"); + await page.getByRole("button", { name: "Preview Only" }).click(); + await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible(); + + const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }); + // A hidden editor panel used to leave an implicit resize region over everything left of the preview, + // which swallowed the click. + await row.click(); + await expect(row).toHaveAttribute("aria-selected", "true"); +}); diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index a608b6a307..3e9b29a93d 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -122,7 +122,10 @@ export function MarkdownEditor({ className={styles.group} storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined} > - + {/* Hidden but mounted in Preview only (its caret drives the preview). Disabled, it leaves the group a + single resizable panel: two enabled panels without a separator get an implicit resize region between + them, which for a hidden panel spans everything left of the preview. */} +
{children}
From 08613ca8005e7fcd14a9d9eacc37443ed566fe22 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:49:29 +0800 Subject: [PATCH 06/14] fix(debugger): keep evaluation results readable in short dialogs (#4592) The Evaluate dialog's result had a 220px minimum height, so in short windows the dialog overflowed and the result and buttons were cut off. The dialog now caps its height to the window, the expression field scrolls within half of it, imports wrap, and the result takes the remaining space; the expression uses the editor font and its label is tied to the field. --- e2e/debug.spec.ts | 57 +++++++++++ src/features/debugger/ui/Overlays.module.css | 96 ++++++++++++++----- src/features/debugger/ui/Overlays.tsx | 93 ++++++++++-------- .../debugger/ui/VariablesView.module.css | 8 ++ src/features/debugger/ui/VariablesView.tsx | 13 ++- 5 files changed, 200 insertions(+), 67 deletions(-) diff --git a/e2e/debug.spec.ts b/e2e/debug.spec.ts index 1af77663b1..3f909588da 100644 --- a/e2e/debug.spec.ts +++ b/e2e/debug.spec.ts @@ -113,3 +113,60 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1); await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden(); }); + +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); + await page.evaluate(async (session) => { + const handlers = window.__ipc.handlers; + handlers.debug_capabilities = () => ({}); + handlers.debug_completions = () => []; + handlers.debug_evaluate_in = () => ({ + name: "orderSummary", + typeName: "OrderSummary", + value: "total = 36", + variablesReference: 210, + evaluateName: null, + }); + handlers.debug_variables = () => [ + { name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null }, + ]; + const stateModule = "/src/features/debugger/state.ts"; + const { adoptSession } = await import(/* @vite-ignore */ stateModule); + adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 }); + }, SESSION); + + await page.keyboard.press("Alt+F8"); + const dialog = page.getByRole("dialog", { name: "Evaluate expression" }); + const field = dialog.getByRole("textbox", { name: "Expression" }); + const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n"); + await field.fill(expression); + await field.press("Enter"); + const result = dialog.getByRole("tree", { name: "Evaluation result" }); + const row = result.getByRole("treeitem").first(); + await expect(row).toContainText("total = 36"); + await expect + .poll(() => + dialog.locator("[data-dialog-body]").evaluate((body) => { + const area = body.querySelector("textarea")!; + const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect(); + const bounds = body.getBoundingClientRect(); + return ( + body.scrollHeight <= body.clientHeight + 1 && + area.scrollHeight > area.clientHeight && + resultRow.top >= bounds.top && + resultRow.bottom <= bounds.bottom + ); + }), + ) + .toBe(true); + await row.click(); + await row.press("ArrowRight"); + await expect(result.getByText("tax", { exact: true })).toBeVisible(); + + await field.fill("otherExpression"); + await dialog.getByRole("button", { name: "History", exact: true }).click(); + await page.getByRole("menuitem", { name: /orderSummary/ }).click(); + await expect(field).toHaveValue(expression); + await expect(field).toBeFocused(); +}); diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css index 88aef79ab9..cae3559e53 100644 --- a/src/features/debugger/ui/Overlays.module.css +++ b/src/features/debugger/ui/Overlays.module.css @@ -172,31 +172,72 @@ } /* evaluate dialog */ +.evalDialog { + height: min(440px, 100%); +} + .evalBody { height: 100%; - box-sizing: border-box; - padding: 12px 14px; + padding: var(--space-2) var(--space-3) 0; display: flex; flex-direction: column; - gap: 10px; + gap: var(--space-2); +} + +.evalExpression, +.evalResult { + display: flex; + flex-direction: column; + min-height: 0; + gap: var(--space-1); +} + +/* Long fragments scroll inside the field so the result keeps its own space. */ +.evalExpression { + max-height: 50%; } .evalImport { + flex: none; + max-height: 40%; + overflow: auto; + padding: var(--space-1); display: flex; flex-wrap: wrap; align-items: center; + align-content: start; gap: var(--space-1) var(--space-2); + border-bottom: 1px solid var(--border); +} + +.evalImport > button { + max-width: 100%; + height: auto; + min-height: var(--h-control); + white-space: normal; + overflow-wrap: anywhere; } -/* Grows with the dialog when it is resized. */ .evalResult { flex: 1; - min-height: 220px; +} + +.evalResultContent { + flex: 1; + min-height: 0; display: flex; flex-direction: column; border: 1px solid var(--border-popup); border-radius: var(--radius-small); - padding: 4px 6px; + padding: var(--space-0-5) var(--space-1); + overflow: hidden; +} + +.evalHint { + padding: var(--space-2); + color: var(--fg-muted); + font-size: var(--fs-small); + overflow: auto; } .chooser { @@ -259,33 +300,38 @@ /* Evaluate: a field that grows with ⇧Enter, like IDEA's expression editor. */ .evalInputRow { display: flex; - align-items: flex-start; - gap: var(--space-1); -} -.evalInput { - flex: 1; - min-width: 0; - min-height: var(--h-field, 28px); - padding: 5px 8px; - resize: none; - appearance: none; - border: 0; + min-height: 0; border-radius: var(--radius-control, 4px); background: var(--bg-field, var(--bg-button)); box-shadow: inset 0 0 0 1px var(--border-button); - color: var(--fg-strong); - font-family: var(--font-mono); - font-size: var(--fs-ui); - line-height: 18px; - outline: none; - -webkit-user-select: text; - user-select: text; } -.evalInput:focus { +.evalInputRow:focus-within { box-shadow: inset 0 0 0 1px var(--focus-ring), 0 0 0 1px var(--focus-ring); } +.evalInput { + flex: 1; + min-width: 0; + min-height: 0; + padding: var(--space-1) var(--space-2); + resize: none; + appearance: none; + border: 0; + background: none; + color: var(--fg-strong); + font-family: var(--font-mono); + font-size: var(--fs-code); + font-weight: var(--fw-code); + line-height: var(--lh-code); + outline: none; + -webkit-user-select: text; + user-select: text; +} .evalInput::placeholder { color: var(--fg-faint); } +.evalHistory { + align-self: flex-start; + margin: var(--space-1); +} diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index 8408d899a0..eef942f235 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -764,8 +764,9 @@ function EvaluateDialogInner({ initial }: { initial: string }) { const [history, setHistory] = useState(() => readHistory("evaluate")); const [historyMenu, setHistoryMenu] = useState(false); const historyPos = useRef(-1); - const historyButton = useRef(null); + const historyButton = useRef(null); const field = useRef(null); + const expressionId = useId(); const session = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined)); const paused = session?.status === "paused"; const close = () => useOverlays.setState({ evaluate: null }); @@ -824,7 +825,10 @@ function EvaluateDialogInner({ initial }: { initial: string }) { onClose={close} title="Evaluate" width={620} + minWidth={340} + minHeight={240} resizable="both" + className={styles.evalDialog} aria-label="Evaluate expression" footerStart={