diff --git a/e2e/agentMarkdown.spec.ts b/e2e/agentMarkdown.spec.ts index 705d9fed4..6c0b13e1f 100644 --- a/e2e/agentMarkdown.spec.ts +++ b/e2e/agentMarkdown.spec.ts @@ -695,3 +695,69 @@ test("draws a diagram without reaching the hosts its configuration names", async ); expect(asked).toEqual(["/after"]); }); + +test("Find in Conversation skips user-select:none summaries and closed
until stepped into", async ({ + page, +}) => { + await openReply(page, "Confirmed—PR is merged."); + await page.evaluate(async (task) => { + const path = "/src/features/agents/store.ts"; + const store = await import(path); + store.useAgents.setState({ + entries: new Map([ + [ + task.id, + [ + { + type: "thought", + text: "**Confirming Active Watch Shell**\n\nCheck background shell before rebasing.", + }, + { + type: "tool", + id: "t1", + title: "stop_bash", + kind: "other", + status: "completed", + locations: [], + output: "", + diffs: [], + }, + { type: "agent", text: "Confirmed—PR is merged." }, + ], + ], + ]), + }); + store.openTaskInEditorLocation(task.id); + }, TASK); + + const stream = page.locator("[class*='_stream_']:visible"); + const runSummary = stream.locator("details[class*='_processRun_'] > summary"); + await runSummary.click(); + await expect(stream.getByText("stop_bash")).toBeVisible(); + + await stream.focus(); + await page.keyboard.press("Meta+f"); + const findBox = page.getByLabel("Find in Conversation"); + await findBox.fill("confirm"); + + // 2 matches total (1 inside collapsed thought body, 1 in visible reply); unselectable is excluded. + await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2"); + const initialHighlights = await page.evaluate(() => ({ + find: [...(CSS.highlights.get("agent-find") ?? [])].map((r) => (r as Range).startContainer.textContent), + current: [...(CSS.highlights.get("agent-find-current") ?? [])].map((r) => (r as Range).startContainer.textContent), + })); + expect(initialHighlights.find).toEqual(["Confirmed—PR is merged."]); + expect(initialHighlights.current).toEqual([]); + + // Stepping to match 2/2 opens the collapsed thought
and highlights it. + await findBox.press("Enter"); + await expect(page.locator("[class*='_findCount_']")).toHaveText("2/2"); + await findBox.press("Enter"); + await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2"); + const expandedHighlights = await page.evaluate(() => ({ + thoughtOpen: document.querySelector("details[class*='_thought_']")?.open, + findCount: CSS.highlights.get("agent-find")?.size ?? 0, + currentCount: CSS.highlights.get("agent-find-current")?.size ?? 0, + })); + expect(expandedHighlights).toEqual({ thoughtOpen: true, findCount: 2, currentCount: 1 }); +}); diff --git a/src/features/agents/SessionEditor.tsx b/src/features/agents/SessionEditor.tsx index 1d0c8c333..04fd4cbfb 100644 --- a/src/features/agents/SessionEditor.tsx +++ b/src/features/agents/SessionEditor.tsx @@ -81,7 +81,7 @@ import { } from "./composerModel"; import { ConfigPickers } from "./ConfigPickers"; import { useEffortFocus } from "./effortFocus"; -import { findRanges, formatDuration, formatSentAt } from "./conversation"; +import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation"; import { ImagePreview, imageSrc } from "./ImagePreview"; import { useAgentSettings } from "./agentSettings"; import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline"; @@ -1142,14 +1142,9 @@ interface RangeSet { clear(): void; add(range: Range): void; } -const highlights = (globalThis as { CSS?: { highlights?: Map } }).CSS?.highlights; -const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight; - -/** - * Sets the ranges of highlight `name`. One registered highlight per name, changed in - * place: WebKit doesn't repaint where a replaced highlight object was. - */ function setHighlight(name: string, ranges: Range[]) { + const highlights = (globalThis as { CSS?: { highlights?: Map } }).CSS?.highlights; + const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight; if (!highlights || !HighlightCtor) return; let set = highlights.get(name); if (!set) { @@ -1225,12 +1220,15 @@ function FindBar({ return () => stream?.removeEventListener("toggle", toggled, true); }, [streamRef]); useEffect(() => { - // Only rendered matches: WebKit paints those in collapsed
over the text next to them. - const visible = (r: Range) => r.getClientRects().length > 0; + const stream = streamRef.current; + if (!stream) return; + // Only rendered selectable matches outside closed
: WebKit paints unrendered + // or user-select:none ranges in CSS.highlights over the next selectable row instead. + const visible = (r: Range) => isFindRangeShown(r, stream); const current = index >= 0 ? ranges[index]! : null; setHighlight("agent-find", ranges.filter(visible)); setHighlight("agent-find-current", current && visible(current) ? [current] : []); - }, [ranges, index, shown]); + }, [ranges, index, shown, streamRef]); useEffect( () => () => { setHighlight("agent-find", []); diff --git a/src/features/agents/conversation.test.ts b/src/features/agents/conversation.test.ts index aba72412c..db557ccc3 100644 --- a/src/features/agents/conversation.test.ts +++ b/src/features/agents/conversation.test.ts @@ -1,5 +1,14 @@ import { describe, expect, it } from "vitest"; -import { fileHref, findAll, findRanges, formatDuration, pathLink, quoteText, withQuote } from "./conversation"; +import { + fileHref, + findAll, + findRanges, + formatDuration, + isFindRangeShown, + pathLink, + quoteText, + withQuote, +} from "./conversation"; describe("quoting", () => { it("quotes each line and leaves a line to type on", () => { @@ -84,4 +93,28 @@ describe("finding", () => { expect(findRanges(root, "one").map((r) => r.toString())).toEqual(["one", "one"]); expect(findRanges(root, "TWO")).toHaveLength(1); }); + it("skips user-select:none chrome, buttons, svgs and mermaid source, and hides ranges in closed
", () => { + const root = document.createElement("div"); + root.innerHTML = [ + '
Confirming summary
hidden confirm body
', + "
stop_bash confirm
tool confirm output
", + "", + "confirm svg", + '
graph TD; confirm
', + "

Visible confirm

", + ].join(""); + const ranges = findRanges(root, "confirm"); + expect(ranges.map((r) => r.startContainer.parentElement?.tagName)).toEqual(["DIV", "SUMMARY", "PRE", "P"]); + + // Simulate WebKit's content-visibility: hidden on closed
, where getClientRects() stays non-empty. + for (const r of ranges) r.getClientRects = () => [new DOMRect(0, 0, 10, 10)] as unknown as DOMRectList; + expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual( + ["SUMMARY", "P"], + ); + + for (const d of root.querySelectorAll("details")) d.open = true; + expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual( + ["DIV", "SUMMARY", "PRE", "P"], + ); + }); }); diff --git a/src/features/agents/conversation.ts b/src/features/agents/conversation.ts index 7415973d7..47ab36576 100644 --- a/src/features/agents/conversation.ts +++ b/src/features/agents/conversation.ts @@ -93,11 +93,36 @@ export function findAll(text: string, query: string): number[] { return out; } -/** DOM ranges of `query` in the text under `root` (matches within one text node). */ +const SKIP_FIND_TAGS = new Set(["STYLE", "SCRIPT", "NOSCRIPT", "SVG", "BUTTON"]); + +function isUnselectable(el: Element): boolean { + const style = getComputedStyle(el); + return style.userSelect === "none" || style.webkitUserSelect === "none"; +} + +/** + * DOM ranges of `query` in the selectable text under `root` (matches within one text node). + * Skips `user-select: none` chrome (`.thought summary`, `.processSummary`, `.messageTime`, + * `.role`…): WebKit's `CSS.highlights` skips unselectable text renderers and paints the + * highlight over the next selectable text node instead. + */ export function findRanges(root: Node, query: string): Range[] { const out: Range[] = []; if (!query) return out; - const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, { + acceptNode(node) { + if (node.nodeType === Node.ELEMENT_NODE) { + const el = node as Element; + const tag = el.tagName.toUpperCase(); + if (SKIP_FIND_TAGS.has(tag)) return NodeFilter.FILTER_REJECT; + if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok") + return NodeFilter.FILTER_REJECT; + if (isUnselectable(el)) return NodeFilter.FILTER_REJECT; + return NodeFilter.FILTER_SKIP; + } + return NodeFilter.FILTER_ACCEPT; + }, + }); for (let node = walker.nextNode(); node; node = walker.nextNode()) { for (const at of findAll(node.textContent ?? "", query)) { const range = document.createRange(); @@ -108,3 +133,20 @@ export function findRanges(root: Node, query: string): Range[] { } return out; } + +/** + * True when `range` is rendered on screen and not inside a collapsed `
` or + * `user-select: none` subtree. WebKit hides closed `
` bodies with + * `content-visibility: hidden` (where `getClientRects()` stays non-empty once opened) + * and forwards unrendered or unselectable `CSS.highlights` ranges onto adjacent rows. + */ +export function isFindRangeShown(range: Range, root: Node): boolean { + for (let el = range.startContainer.parentElement; el && el !== root; el = el.parentElement) { + if (isUnselectable(el)) return false; + if (el instanceof HTMLDetailsElement && !el.open) { + const summary = el.querySelector(":scope > summary"); + if (!summary?.contains(range.startContainer)) return false; + } + } + return range.getClientRects().length > 0; +} diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index b92b05d8f..aa7bb42d7 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -540,20 +540,60 @@ describe("opened runs", () => { }); describe("folded content", () => { - it("is rendered for Find in Conversation, so its text is found", async () => { - backend.entries.set("A", [ - tool("one", { output: "needle in a tool output" }), - tool("two"), - { type: "agent", text: "Answer A" }, - ]); - useAgents.setState({ entries: new Map(backend.entries) }); - render(); - const summary = await screen.findByText("Read 2 files"); - expect(screen.queryByText("needle in a tool output")).toBeNull(); - fireEvent.focus(summary); - act(() => focusedSession()!.openFind()); - expect(await screen.findByText("needle in a tool output")).toBeInTheDocument(); - expect(summary.closest("details")!.open).toBe(false); + it("is rendered for Find in Conversation without painting closed
highlights until stepped into", async () => { + const rectSpy = vi + .spyOn(Range.prototype, "getClientRects") + .mockImplementation(() => [new DOMRect(0, 0, 20, 12)] as unknown as DOMRectList); + const prevCss = (globalThis as { CSS?: unknown }).CSS; + const prevHighlight = (globalThis as { Highlight?: unknown }).Highlight; + const highlights = new Map>(); + if (typeof prevHighlight === "undefined") { + (globalThis as { Highlight?: unknown }).Highlight = Set; + } + if (!(prevCss as { highlights?: unknown } | undefined)?.highlights) { + (globalThis as { CSS?: unknown }).CSS = { + ...(typeof prevCss === "object" && prevCss ? prevCss : {}), + highlights, + }; + } + try { + backend.entries.set("A", [ + { type: "thought", text: "Reviewing Changes\n\nConfirm the branch state before rebasing." }, + tool("one", { title: "stop_bash", output: "stopped" }), + { type: "agent", text: "Confirmed—PR is merged." }, + ]); + useAgents.setState({ entries: new Map(backend.entries) }); + render(); + const runSummary = await screen.findByText("Read 1 file"); + const runDetails = runSummary.closest("details")!; + runDetails.open = true; + fireEvent(runDetails, new Event("toggle")); + + const thoughtDetails = (await screen.findByText("Reviewing Changes")).closest("details")!; + expect(thoughtDetails.open).toBe(false); + + fireEvent.focus(runSummary); + act(() => focusedSession()!.openFind()); + const findBox = await screen.findByLabelText("Find in Conversation"); + fireEvent.change(findBox, { target: { value: "confirm" } }); + + const registry = (globalThis as unknown as { CSS: { highlights: Map> } }).CSS.highlights; + await waitFor(() => expect(screen.getByText("1/2")).toBeInTheDocument()); + await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(1)); + expect([...(registry.get("agent-find") ?? [])][0]!.startContainer.textContent).toContain("Confirmed"); + expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(0); + + fireEvent.keyDown(findBox, { key: "Enter" }); + fireEvent.keyDown(findBox, { key: "Enter" }); + fireEvent(thoughtDetails, new Event("toggle")); + expect(thoughtDetails.open).toBe(true); + await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(2)); + expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(1); + } finally { + rectSpy.mockRestore(); + (globalThis as { CSS?: unknown }).CSS = prevCss; + (globalThis as { Highlight?: unknown }).Highlight = prevHighlight; + } }); });