Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix Studio find-in-page correctness and typing (#10209)

Wasim Yousef Saida33c6a8fb1a5
diff --git a/studio/frontend/smoke-find-in-page-main.tsx b/studio/frontend/smoke-find-in-page-main.tsx
index bb1a31f7315..28f27b1e1d7 100644
--- a/studio/frontend/smoke-find-in-page-main.tsx
+++ b/studio/frontend/smoke-find-in-page-main.tsx
@@ -20,7 +20,6 @@ import {
type FindElementLike,
buildTextIndex,
} from "@/features/find-in-page/lib/find-text-index.ts";
-import { useFindInPageStore } from "@/features/find-in-page/stores/find-in-page-store.ts";
/* eslint-enable no-restricted-imports */
import "@/index.css";
import { StrictMode, useCallback, useEffect, useRef, useState } from "react";
@@ -30,7 +29,8 @@ declare global {
interface Window {
// Optional: the app typechecks this entry, only the harness page installs it.
__findSmoke?: {
- store: typeof useFindInPageStore;
+ /** Observable controller state, without coupling the harness to its private implementation. */
+ state: () => { open: boolean; focused: boolean };
/** What the counter is showing, read straight out of the bar. */
counter: () => string | null;
/** Scroll offset of the conversation, so a test can see the walk move it. */
@@ -209,7 +209,15 @@ function Harness() {
useEffect(() => {
window.__findSmoke = {
- store: useFindInPageStore,
+ state: () => {
+ const input = document.querySelector<HTMLInputElement>(
+ '[role="search"] input',
+ );
+ return {
+ open: input !== null,
+ focused: document.activeElement === input,
+ };
+ },
counter: () =>
document.querySelector('[role="search"] [aria-live="polite"]')
?.textContent ?? null,
diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsx
index d43c2dc485e..83103397582 100644
--- a/studio/frontend/src/components/floating-monitor.tsx
+++ b/studio/frontend/src/components/floating-monitor.tsx
@@ -3,6 +3,8 @@
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
+import { FIND_PORTAL_ATTRIBUTE } from "@/features/find-in-page/lib/find-attributes";
+
import {
useMonitorFrameStore,
useMonitorOverlayStore,
@@ -241,6 +243,7 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {
// republishing through them would re-render every overlay in the stack for
// each one, which is most of what made dragging feel heavy.
useLayoutEffect(() => {
+ void layout;
const monitor = monitorRef.current;
if (!(monitor && constraintsElement)) {
return;
@@ -495,6 +498,7 @@ function FloatingMonitorPanel({
style={{ zIndex }}
>
<motion.div
+ {...{ [FIND_PORTAL_ATTRIBUTE]: "" }}
ref={monitorRef}
onPointerDownCapture={() => raisePanel("resource-monitor")}
initial={{ opacity: 0 }}
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
index e9babc47cda..b7783e9a5c9 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
@@ -6,11 +6,12 @@
import { getApiMonitor } from "@/features/chat/api/chat-api";
import type { ApiMonitorEntry } from "@/features/chat/types/api";
+import { FIND_PORTAL_ATTRIBUTE } from "@/features/find-in-page/lib/find-attributes";
+import { useShortcut } from "@/features/settings";
import {
useFloatingPanelOrderStore,
useFloatingPanelZIndex,
} from "@/lib/floating-panel-order";
-import { useShortcut } from "@/features/settings";
import { cn } from "@/lib/utils";
import {
ArrowExpand01Icon,
@@ -310,6 +311,7 @@ export function ApiMonitorOverlay(): ReactElement | null {
style={{ zIndex }}
>
<motion.div
+ {...{ [FIND_PORTAL_ATTRIBUTE]: "" }}
ref={setPanelElement}
onPointerDownCapture={() => raisePanel("api-monitor")}
drag={true}
diff --git a/studio/frontend/src/features/find-in-page/components/find-in-page.tsx b/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
index 2413383d326..315d29f866c 100644
--- a/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
+++ b/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
@@ -15,9 +15,12 @@ import { HugeiconsIcon } from "@hugeicons/react";
// hugeicons shaft is a bezier that bows out rather than meeting at a point, and after that change
// there is no other use of the pair left to match.
import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { useFindInPage } from "../hooks/use-find-in-page.ts";
-import { resolveFindScope, resolvePortalSurfaces } from "../lib/find-dom.ts";
+import {
+ resolveDismissiblePortalSurfaces,
+ resolveFindScope,
+} from "../lib/find-dom.ts";
import { FIND_SCOPE_ATTRIBUTE } from "../lib/find-text-index.ts";
import { useFindInPageStore } from "../stores/find-in-page-store.ts";
@@ -79,16 +82,52 @@ function rewindToStart(event: { currentTarget: HTMLInputElement }): void {
*/
const FIND_BUTTON_CLASS = "size-8 hover:bg-black/[0.06] dark:hover:bg-white/10";
+/** Coalesce a typing burst before the DOM search/highlight work runs. */
+export const FIND_QUERY_SETTLE_MS = 100;
+
+function useSettledQuery(query: string): [string, () => void] {
+ const [settled, setSettled] = useState(query);
+ useEffect(() => {
+ if (query.length === 0) {
+ setSettled("");
+ return;
+ }
+ const timer = setTimeout(() => setSettled(query), FIND_QUERY_SETTLE_MS);
+ return () => clearTimeout(timer);
+ }, [query]);
+ return [settled, () => setSettled(query)];
+}
+
function FindBar() {
const t = useT();
const query = useFindInPageStore((state) => state.query);
const setQuery = useFindInPageStore((state) => state.setQuery);
const close = useFindInPageStore((state) => state.close);
const focusToken = useFindInPageStore((state) => state.focusToken);
- const { count, active, capped, truncated, next, previous } =
- useFindInPage(query);
+ const [settledQuery, settleQuery] = useSettledQuery(query);
+ const queryPending = query !== settledQuery;
+ const { count, active, capped, truncated, next, previous } = useFindInPage(
+ settledQuery,
+ queryPending,
+ );
const inputRef = useRef<HTMLInputElement>(null);
-
+ const queuedStepRef = useRef(0);
+ const stepWhenSettled = (delta: -1 | 1) => {
+ if (queryPending) {
+ queuedStepRef.current = delta;
+ settleQuery();
+ return;
+ }
+ if (delta < 0) previous();
+ else next();
+ };
+ useEffect(() => {
+ if (queryPending || queuedStepRef.current === 0) return;
+ const delta = queuedStepRef.current;
+ queuedStepRef.current = 0;
+ if (delta < 0) previous();
+ else next();
+ }, [queryPending, next, previous]);
// Hand focus back to whatever had it, usually the composer, so closing a search leaves the reader
// typing. Declared above the focus effect so it reads `activeElement` before the field takes it.
const barRef = useRef<HTMLDivElement>(null);
@@ -131,7 +170,8 @@ function FindBar() {
const onEscape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || isImeComposing(event)) return;
if (isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`)) return;
- if (resolvePortalSurfaces(resolveFindScope()).length > 0) return;
+ if (resolveDismissiblePortalSurfaces(resolveFindScope()).length > 0)
+ return;
event.preventDefault();
event.stopPropagation();
close();
@@ -142,6 +182,7 @@ function FindBar() {
// Every press of the chord, not just the one that opened the bar: pressing it again selects what
// is in the field so the next keystroke replaces the last search.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: each token requests a fresh focus/select.
useEffect(() => {
const input = inputRef.current;
if (!input) return;
@@ -150,22 +191,28 @@ function FindBar() {
}, [focusToken]);
const searching = query.length > 0;
- const empty = searching && count === 0;
- const counter = searching
- ? `${count === 0 ? 0 : active + 1}/${count}${capped ? "+" : ""}`
- : "";
+ const empty = !queryPending && searching && count === 0;
+ // A pending query has no count of its own yet, so the settled one's zero must not disable the
+ // walk: `stepWhenSettled` queues the press and runs it once the count arrives.
+ const canStep = searching && (count > 0 || queryPending);
+ const counter =
+ searching && !queryPending
+ ? `${count === 0 ? 0 : active + 1}/${count}${capped ? "+" : ""}`
+ : "";
return (
// `data-find-skip` keeps the bar out of its own index: without it every keystroke finds itself.
<div
ref={barRef}
data-find-skip=""
+ // biome-ignore lint/a11y/useSemanticElements: this landmark contains the field and navigation controls.
+
role="search"
aria-label={t("shell.find.label")}
// Escape is handled on the window for the lifetime of the bar (see the effect above), which
// covers the walk buttons and the field as well as everything outside it, so there is no
// handler here to also reach the presses that start inside.
- className="find-bar-surface fixed top-[calc(var(--studio-content-top-inset,0px)+3.5rem)] right-4 z-50 flex h-13 max-w-[calc(100vw-2rem)] items-center gap-1 rounded-full pr-4 pl-5"
+ className="find-bar-surface fixed top-[calc(var(--studio-content-top-inset,0px)+3.5rem)] right-4 z-50 flex h-13 w-[22.25rem] max-w-[calc(100vw-2rem)] items-center gap-1 rounded-full pr-4 pl-5 sm:w-[28.25rem]"
>
<input
ref={inputRef}
@@ -178,8 +225,7 @@ function FindBar() {
// match and throws away the word.
if (isImeComposing(event.nativeEvent)) return;
event.preventDefault();
- if (event.shiftKey) previous();
- else next();
+ stepWhenSettled(event.shiftKey ? -1 : 1);
}
}}
onBlur={rewindToStart}
@@ -193,7 +239,7 @@ function FindBar() {
// Narrow by default so the whole bar clears a small window, wide once there is room.
// `min-w-0` lets the field, rather than the bar, give way if it still does not fit.
// `text-ui-15`, not a raw pixel size, which ignores the UI font size preference.
- "w-40 min-w-0 bg-transparent text-ui-15 outline-none placeholder:text-muted-foreground sm:w-64",
+ "min-w-0 flex-1 bg-transparent text-ui-15 outline-none placeholder:text-muted-foreground",
empty && "text-destructive",
)}
/>
@@ -211,9 +257,9 @@ function FindBar() {
variant="ghost"
size="icon"
className={FIND_BUTTON_CLASS}
- disabled={count === 0}
+ disabled={!canStep}
onMouseDown={keepFocusInField}
- onClick={previous}
+ onClick={() => stepWhenSettled(-1)}
aria-label={t("shell.find.previous")}
title={t("shell.find.previous")}
>
@@ -223,9 +269,9 @@ function FindBar() {
variant="ghost"
size="icon"
className={FIND_BUTTON_CLASS}
- disabled={count === 0}
+ disabled={!canStep}
onMouseDown={keepFocusInField}
- onClick={next}
+ onClick={() => stepWhenSettled(1)}
aria-label={t("shell.find.next")}
title={t("shell.find.next")}
>
diff --git a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
index 70eb5fff6a3..0d8abd20dbd 100644
--- a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
+++ b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
@@ -1,15 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// The find engine. Mounted only while the bar is open, so a Studio nobody is searching runs none of
-// this: no observer, no index, no ranges.
-//
-// Everything expensive lives in refs and is rebuilt only when the document changes. A keystroke
-// runs `indexOf` over a string and creates at most `MAX_PAINTED_RANGES` ranges. Nothing here writes
-// to the DOM, which is why the observer below cannot retrigger itself.
+// The find engine mounts only while the bar is open. Expensive work stays in refs, and DOM writes
+// are limited to highlights, so the observer cannot retrigger itself.
import { completeProgressiveMounts } from "@/components/assistant-ui/progressive-messages";
-import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import {
cancelRevealPasses,
clearHighlights,
@@ -37,6 +39,7 @@ import {
buildTextIndex,
dropProbeFurthestFrom,
findMatches,
+ renumbersMatches,
} from "../lib/find-text-index.ts";
/**
@@ -107,7 +110,10 @@ function ordinalOfStart(matches: FindMatch[], start: number): number {
return -1;
}
-export function useFindInPage(query: string): FindResults {
+export function useFindInPage(
+ query: string,
+ queryPending = false,
+): FindResults {
const [results, setResults] = useState<{
count: number;
active: number;
@@ -134,9 +140,13 @@ export function useFindInPage(query: string): FindResults {
const staleRef = useRef(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const queryPendingRef = useRef(queryPending);
+ queryPendingRef.current = queryPending;
+
/** Clamp the active match, paint, and optionally move the reader to it. The only place highlights
* and React state are written, so a navigation and a rebuild take the same path. */
const apply = useCallback((reveal: boolean) => {
+ if (queryPendingRef.current) return;
const index = indexRef.current;
const matches = matchesRef.current;
const count = matches.length;
@@ -235,7 +245,7 @@ export function useFindInPage(query: string): FindResults {
*/
const reindex = useCallback((): boolean => {
staleRef.current = false;
- const before = indexRef.current.text;
+ const before = indexRef.current;
const scope = scopeRef.current;
indexRef.current = scope
? buildTextIndex(
@@ -245,7 +255,7 @@ export function useFindInPage(query: string): FindResults {
resolvePortalSurfaces(scope) as unknown as FindElementLike[],
)
: EMPTY_TEXT_INDEX;
- return !indexRef.current.text.startsWith(before);
+ return renumbersMatches(before, indexRef.current, activeStartRef.current);
}, []);
// Open: take the index and watch for changes. Closing tears all of it down, highlights included.
@@ -360,6 +370,21 @@ export function useFindInPage(query: string): FindResults {
};
}, [reindex, search]);
+ // Do not leave the previous partial word painted while the input already shows the next one.
+ // The settled search below is deliberately coalesced so a broad first letter cannot stall every
+ // following keystroke in a rich conversation.
+ useLayoutEffect(() => {
+ if (queryPending) {
+ cancelRevealPasses();
+ clearHighlights();
+ if (!supportsHighlightApi()) selectRangeFallback(null);
+ return;
+ }
+ // Returning to the already-settled query does not run the query effect again. A genuinely new
+ // settled query has not reached queryRef yet and is painted by the search effect below instead.
+ if (queryRef.current === query) apply(false);
+ }, [apply, query, queryPending]);
+
// A new query starts from the reader's position, re-indexing first if the document moved on.
useEffect(() => {
queryRef.current = query;
diff --git a/studio/frontend/src/features/find-in-page/lib/find-attributes.ts b/studio/frontend/src/features/find-in-page/lib/find-attributes.ts
index 61e8c39313f..9a5c7fc8c4f 100644
--- a/studio/frontend/src/features/find-in-page/lib/find-attributes.ts
+++ b/studio/frontend/src/features/find-in-page/lib/find-attributes.ts
@@ -1,11 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// Their own module, with no imports: the call sites that mark a subtree are ordinary chat and
-// settings components, and a constant should not pull the whole index into their chunk.
+// Import-free so ordinary call sites do not pull the index into their chunks.
/** Marks a subtree the bar must not read: the bar itself, first of all. */
export const FIND_SKIP_ATTRIBUTE = "data-find-skip";
+/** Marks a visible panel portaled outside the shell scope as searchable. */
+export const FIND_PORTAL_ATTRIBUTE = "data-find-portal";
+
/** Marks the scope the bar searches, set on the shell's content region in `__root.tsx`. */
export const FIND_SCOPE_ATTRIBUTE = "data-find-scope";
diff --git a/studio/frontend/src/features/find-in-page/lib/find-dom.ts b/studio/frontend/src/features/find-in-page/lib/find-dom.ts
index d28c44c47be..2e9eb9d1122 100644
--- a/studio/frontend/src/features/find-in-page/lib/find-dom.ts
+++ b/studio/frontend/src/features/find-in-page/lib/find-dom.ts
@@ -5,8 +5,11 @@
// to one. The arithmetic and the flatten live in find-text-index.ts, which is pure.
import {
+ FIND_PORTAL_ATTRIBUTE,
FIND_SCOPE_ATTRIBUTE,
FIND_SKIP_ATTRIBUTE,
+} from "./find-attributes.ts";
+import {
type FindMatch,
type FindTextIndex,
endPositionAt,
@@ -31,9 +34,10 @@ export const MAX_PAINTED_RANGES = 400;
/** Distance kept from a scroller's edge before a match counts as needing to be scrolled to. */
const REVEAL_INSET_PX = 24;
-type HighlightLike = { priority: number };
+type HighlightLike = { priority: number; clear(): void };
type HighlightConstructor = new (...ranges: Range[]) => HighlightLike;
type HighlightRegistry = {
+ get(name: string): HighlightLike | undefined;
set(name: string, highlight: HighlightLike): void;
delete(name: string): void;
};
@@ -69,31 +73,37 @@ export function resolveFindScope(): Element | null {
);
}
-/**
- * Surfaces the shell renders in front of the workspace but outside it.
- *
- * A popover portals to the body, so the model picker's list is on screen but not in the scope, and
- * searching the page behind it is a lie. Narrow on purpose: the layers a reader works IN, so a
- * toast or a tooltip does not change the count under them.
- */
-const PORTAL_SURFACE_SELECTOR =
+/** Searchable surfaces outside the scope; persistent portals are additive. */
+const DISMISSIBLE_PORTAL_SURFACE_SELECTOR =
'[data-slot="popover-content"], [role="menu"], [role="listbox"]';
+const SEARCHABLE_PORTAL_SURFACE_SELECTOR = `[${FIND_PORTAL_ATTRIBUTE}], ${DISMISSIBLE_PORTAL_SURFACE_SELECTOR}`;
-export function resolvePortalSurfaces(scope: Element | null): Element[] {
+function resolveSurfaces(scope: Element | null, selector: string): Element[] {
if (typeof document === "undefined" || scope === null) return [];
const found: Element[] = [];
- for (const element of document.querySelectorAll(PORTAL_SURFACE_SELECTOR)) {
+ for (const element of document.querySelectorAll(selector)) {
// Inside the scope already, or nested in a surface already taken.
if (scope.contains(element)) continue;
if (found.some((taken) => taken.contains(element))) continue;
- // On its way out: these animate closed and keep a box until that finishes, so nothing else
- // here would turn them down.
+ // Dismissible surfaces animate closed and keep a box until that finishes.
if (element.getAttribute("data-state") === "closed") continue;
found.push(element);
}
return found;
}
+/** Every visible out-of-scope surface whose text belongs in the index. */
+export function resolvePortalSurfaces(scope: Element | null): Element[] {
+ return resolveSurfaces(scope, SEARCHABLE_PORTAL_SURFACE_SELECTOR);
+}
+
+/** Transient surfaces that own Escape before the find bar does. */
+export function resolveDismissiblePortalSurfaces(
+ scope: Element | null,
+): Element[] {
+ return resolveSurfaces(scope, DISMISSIBLE_PORTAL_SURFACE_SELECTOR);
+}
+
/**
* The index offset nearest the top of the reader's viewport, or 0 when nothing can be measured.
*
@@ -136,7 +146,7 @@ export function viewportOffset(index: FindTextIndex): number {
* in the document is not the same as being searchable. Attributes only: a region hidden by a CLASS
* is skipped through resolved style, which no selector can see.
*/
-const SKIPPED_REGION_SELECTOR = `[aria-hidden="true"], [inert], [hidden], [${FIND_SKIP_ATTRIBUTE}]`;
+const SKIPPED_REGION_SELECTOR = `[aria-hidden="true"]:not(.katex-html), [inert], [hidden], [${FIND_SKIP_ATTRIBUTE}]`;
/** What the walk will actually read, asked of one element: inside the scope, and under nothing the
* walk turns back at. */
@@ -149,13 +159,7 @@ export function indexReaches(
return element.closest(SKIPPED_REGION_SELECTOR) === null;
}
-/**
- * True when a mutation touched text the index covers, rather than the bar's own chrome. `some()`
- * short-circuits, so this costs a `closest` call only on batches the bar itself produced.
- *
- * Lives here, not beside its caller, so a test can hand it a record: the hook imports React and
- * cannot be loaded under `node --test`.
- */
+/** True when a mutation affects indexed text rather than the bar's own chrome. */
export function mutatesSearchableText(record: {
target: { nodeType: number; parentElement: Element | null };
type: string;
@@ -167,16 +171,10 @@ export function mutatesSearchableText(record: {
? (target as unknown as Element)
: (target.parentElement ?? null);
if (!element) return true;
- // Whichever attribute changed, ask from the PARENT. `closest` matches where it starts, so an
- // element just parked answers with itself and its own record is dropped - the one record saying a
- // region left the index. Removal reindexed fine, addition never did, though the observer watches
- // both, and every attribute it watches decides searchability. A detached target counts as a
- // change.
+ // Attribute changes are checked from the parent so parked or newly indexed regions reindex.
const from = record.type === "attributes" ? element.parentElement : element;
if (!from) return true;
- // Not just the bar's own chrome: an off-route workspace goes on streaming a reply into the
- // document, and each character of it used to buy a full flatten that then correctly threw that
- // text away. Once per throttle for as long as the generation ran.
+ // Streaming updates in skipped workspaces still need one throttled observer pass.
return from.closest(SKIPPED_REGION_SELECTOR) === null;
}
@@ -217,6 +215,42 @@ export function paintWindow(
return { from, to: from + cap };
}
+function removeRegisteredHighlight(
+ registry: HighlightRegistry,
+ name: string,
+): boolean {
+ const highlight = registry.get(name);
+ if (!highlight) return false;
+ // WebKit versions shipped by Tauri can remove the registry entry without invalidating its
+ // painted ranges. Emptying the registered set first takes the range-removal repaint path.
+ highlight.clear();
+ registry.delete(name);
+ return true;
+}
+
+/** Flush the last stale WebKit pixels after a highlight set becomes empty.
+ *
+ * WebKitGTK can update the registry and counter but leave highlight edges painted until scrolling
+ * invalidates the layer. A transient, imperceptible opacity change plus a layout read gives that
+ * layer a synchronous reason to repaint. This only runs when registered ranges were actually
+ * removed, not for every character in an unsettled typing burst. */
+function forceHighlightRepaint(): void {
+ if (typeof document === "undefined") return;
+ // The index also includes body-level portals outside the workspace scope, so repaint their shared
+ // document root rather than only the conversation container.
+ const root = document.documentElement ?? resolveFindScope();
+ if (
+ root === null ||
+ typeof HTMLElement === "undefined" ||
+ !(root instanceof HTMLElement)
+ )
+ return;
+ const previous = root.style.opacity;
+ root.style.opacity = previous === "0.999999" ? "0.999998" : "0.999999";
+ void root.offsetHeight;
+ root.style.opacity = previous;
+}
+
/** Paint `ranges`, with `activeRange` on top. Both registries are replaced wholesale, which is one
* write per navigation rather than one per match. */
export function paintHighlights(
@@ -226,15 +260,20 @@ export function paintHighlights(
const api = highlightApi();
if (!api) return;
const { registry, Highlight } = api;
+ let removed = false;
if (ranges.length === 0) {
- registry.delete(FIND_HIGHLIGHT);
+ removed = removeRegisteredHighlight(registry, FIND_HIGHLIGHT);
} else {
+ removeRegisteredHighlight(registry, FIND_HIGHLIGHT);
registry.set(FIND_HIGHLIGHT, new Highlight(...ranges));
}
if (!activeRange) {
- registry.delete(FIND_HIGHLIGHT_ACTIVE);
+ removed =
+ removeRegisteredHighlight(registry, FIND_HIGHLIGHT_ACTIVE) || removed;
+ if (removed) forceHighlightRepaint();
return;
}
+ removeRegisteredHighlight(registry, FIND_HIGHLIGHT_ACTIVE);
const active = new Highlight(activeRange);
// The same text is in both sets, and registration order is not a guarantee the spec makes.
active.priority = 1;
@@ -245,8 +284,12 @@ export function paintHighlights(
export function clearHighlights(): void {
const api = highlightApi();
if (!api) return;
- api.registry.delete(FIND_HIGHLIGHT);
- api.registry.delete(FIND_HIGHLIGHT_ACTIVE);
+ const removedActive = removeRegisteredHighlight(
+ api.registry,
+ FIND_HIGHLIGHT_ACTIVE,
+ );
+ const removedAll = removeRegisteredHighlight(api.registry, FIND_HIGHLIGHT);
+ if (removedActive || removedAll) forceHighlightRepaint();
}
/** The caret inside a focused text field, so moving the document selection can give it back. */
diff --git a/studio/frontend/src/features/find-in-page/lib/find-text-index.ts b/studio/frontend/src/features/find-in-page/lib/find-text-index.ts
index b24028bd73e..e49fef52443 100644
--- a/studio/frontend/src/features/find-in-page/lib/find-text-index.ts
+++ b/studio/frontend/src/features/find-in-page/lib/find-text-index.ts
@@ -1,13 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// The searchable text of a subtree, flattened into one string plus the map back to its text nodes.
-// Flattening once and running `indexOf` keeps a keystroke off the DOM: a tree walk per character
-// typed would re-read a 300K conversation six times to type "unsloth". The walk is paid only when
-// the document changes (see use-find-in-page).
-//
-// Pure, and written against structural types, so it runs under `node --test` with the hand-rolled
-// DOM in tests/find-in-page.test.ts. There is no DOM library in this project.
+// Flatten searchable text once and retain offsets back to its text nodes. The module is pure, so
+// the Node tests can use a hand-rolled DOM.
import { FIND_SKIP_ATTRIBUTE } from "./find-attributes.ts";
@@ -32,14 +27,7 @@ export const MAX_MATCHES = 5_000;
* reader is looking at are not indexed at all. A share each, and the walk goes on. */
export const MAX_NODE_CHARS = 100_000;
-/**
- * Budget held back from the workspace for the surfaces portaled in front of it.
- *
- * The workspace is walked first, because that is where it sits in the document, and a conversation
- * long enough to reach the ceiling would otherwise spend the whole budget before the popover the
- * reader is actually looking at was reached. A popover, a menu or a listbox is small; this is 2.5%
- * of the ceiling and only held back while one of them is open.
- */
+/** Reserve space for visible portaled surfaces after walking the workspace. */
export const PORTAL_RESERVE_CHARS = 100_000;
/** Elements whose subtree holds no findable text. Form controls carry theirs in `value`; a `Range`
@@ -152,6 +140,12 @@ export interface TextSegment {
preserved: boolean;
}
+interface IndexedSurface {
+ root: FindElementLike;
+ start: number;
+ end: number;
+}
+
export interface FindTextIndex {
/** Case-folded haystack, block boundaries written as `BLOCK_SEPARATOR`. */
text: string;
@@ -159,12 +153,18 @@ export interface FindTextIndex {
segments: TextSegment[];
/** True when `MAX_INDEX_CHARS` stopped the walk early. */
truncated: boolean;
+ /** Where the portaled surfaces begin. The whole length when none are open. */
+ rootLength: number;
+ /** Stable portal roots and the offsets occupied by their searchable text. */
+ surfaces: IndexedSurface[];
}
export const EMPTY_TEXT_INDEX: FindTextIndex = {
text: "",
segments: [],
truncated: false,
+ rootLength: 0,
+ surfaces: [],
};
/** Dotted I, the only code point whose `toLowerCase` grows (scanned all of them). Mapped to bare
@@ -201,24 +201,26 @@ export function foldText(raw: string): string {
return plain.replace(FINAL_SIGMA_PATTERN, "\u03c3");
}
-/**
- * The half of the skip rule that costs no layout: tag name and attributes.
- *
- * Asked first, and by the walk directly, so a subtree turned down on markup alone never resolves a
- * style at all. That is most of what gets skipped: SCRIPT and STYLE, the bar itself, the off-route
- * workspaces the shell parks under `inert`, and the whole page behind a modal.
- */
+/** Check cheap markup before resolving styles, which avoids layout work for skipped subtrees. */
+function hasClassToken(element: FindElementLike, token: string): boolean {
+ return (element.getAttribute("class") ?? "").split(/\s+/).includes(token);
+}
function skipsByMarkup(element: FindElementLike): boolean {
// Uppercased first: only HTML elements report their tag that way. SVG and MathML keep their source
// casing, so an inline `<svg>` answers "svg" and walked straight past this set, putting Mermaid
// labels in the index as matches no engine can paint. Already uppercase for everything else.
if (SKIP_TAGS.has(element.tagName.toUpperCase())) return true;
+ if (hasClassToken(element, "katex-mathml")) return true;
if (element.getAttribute(FIND_SKIP_ATTRIBUTE) !== null) return true;
// Boolean attributes, so presence is the whole signal. The shell parks an off-route workspace
- // under `inert`; Radix marks the page `aria-hidden` behind a modal.
+ // under `inert`; Radix marks the page `aria-hidden` behind a modal. KaTeX is the narrow exception:
+ // its painted HTML tree is deliberately aria-hidden because a clipped MathML mirror speaks it.
if (element.getAttribute("hidden") !== null) return true;
if (element.getAttribute("inert") !== null) return true;
- return element.getAttribute("aria-hidden") === "true";
+ return (
+ element.getAttribute("aria-hidden") === "true" &&
+ !hasClassToken(element, "katex-html")
+ );
}
/**
@@ -358,6 +360,8 @@ export function buildTextIndex(
): FindTextIndex {
const parts: string[] = [];
const segments: TextSegment[] = [];
+
+ const surfaces: IndexedSurface[] = [];
let length = 0;
/** The index does not hold everything: a node was clipped, or the ceiling was reached. */
let truncated = false;
@@ -439,6 +443,9 @@ export function buildTextIndex(
};
visit(root, false);
+ // Before the surfaces and the separator joining them, so this slice is exactly the workspace.
+ // `foldText` cannot change a length, so the offset survives it.
+ const rootLength = length;
// The reserve, handed over. Portaled surfaces come after the workspace, so without this the one
// thing in front of the reader is the one left out. `truncated` stays as the workspace left it.
ceiling = MAX_INDEX_CHARS;
@@ -447,10 +454,71 @@ export function buildTextIndex(
if (full) break;
// A boundary between roots: they are separate surfaces, and a match must not run across.
pendingSeparator = true;
+ const firstSegment = segments.length;
visit(extra, false);
+ if (segments.length > firstSegment) {
+ surfaces.push({
+ root: extra,
+ start: segments[firstSegment].start,
+ end: length,
+ });
+ }
}
// Folded once, over the joined document: see foldText for why it cannot be done a node at a time.
- return { text: foldText(parts.join("")), segments, truncated };
+ return {
+ text: foldText(parts.join("")),
+ segments,
+ truncated,
+ rootLength,
+ surfaces,
+ };
+}
+
+/**
+ * True when a rebuild renumbers the match list, so the search has to re-anchor to the viewport.
+ *
+ * The index is the workspace followed by the surfaces portaled in front of it, joined at
+ * `rootLength`. A monitor stays searchable while it is up and rewrites its reading on a timer, so
+ * judged as one string every poll reads as a renumbered document and throws the reader out of the
+ * conversation behind it. What decides is whether text moved AHEAD of the reader's offset.
+ *
+ * This is the cheap half of the answer. `search` asks the exact question afterwards, by looking for
+ * a match still starting at that offset, so this only has to turn down the rebuilds where the
+ * offset would be meaningless.
+ *
+ * Here rather than beside its caller: the hook imports React and cannot run under `node --test`.
+ */
+export function renumbersMatches(
+ before: FindTextIndex,
+ after: FindTextIndex,
+ /** Where the reader's occurrence started in `before`, or null when there was none. */
+ activeStart: number | null,
+): boolean {
+ // One slice, and none at all without a surface open, where the workspace is the whole text.
+ const workspaceGrewAtTail =
+ before.rootLength <= after.rootLength &&
+ after.text.startsWith(before.text.slice(0, before.rootLength));
+ // The workspace is the prefix, so no surface can move an offset inside it. `search` re-anchors on
+ // its own when there was no occurrence to keep.
+ if (activeStart === null || activeStart < before.rootLength) {
+ return !workspaceGrewAtTail;
+ }
+ // A stable surface root tells whether another portal was inserted, removed, or reordered ahead of
+ // the occurrence. Equal-width polling within that root keeps its start and therefore the reader.
+ const beforeSurface = before.surfaces.find(
+ ({ start, end }) => start <= activeStart && activeStart < end,
+ );
+ if (beforeSurface !== undefined) {
+ const afterSurface = after.surfaces.find(
+ ({ root }) => root === beforeSurface.root,
+ );
+ return (
+ !workspaceGrewAtTail ||
+ afterSurface === undefined ||
+ afterSurface.start !== beforeSurface.start
+ );
+ }
+ return !workspaceGrewAtTail || after.rootLength !== before.rootLength;
}
/** Fold a query the way the haystack was folded. Null when it cannot match: empty, or carrying the
@@ -502,8 +570,58 @@ function canonicalVariants(needle: string, dotted: boolean): string[] {
return variants;
}
-/** A base character with the combining marks that belong to it, which compose or decompose as one. */
-const CLUSTER_PATTERN = /[\s\S][̀-ͯ҃-҉᪰-᫿᷀-᷿⃐-⃰︠-︯]*/gu;
+/**
+ * One canonical cluster. Hangul conjoining sequences can contain repeated leading, vowel, and
+ * trailing Jamo, so the whole L*V*T* run has to win before the generic character alternative.
+ */
+const CLUSTER_PATTERN =
+ // biome-ignore lint/suspicious/noMisleadingCharacterClass: Jamo and combining marks intentionally form canonical clusters.
+ /(?:[ᄀ-ᅟꥠ-꥿]+[ᅠ-ᆧힰ-ퟆ]+[ᆨ-ᇿퟋ-ퟻ]*|[\s\S])[̀-ͯ҃-҉᪰-᫿᷀-᷿⃐-⃰︠-︯]*/gu;
+
+const OPEN_HANGUL_CLUSTER_PATTERN =
+ /^[\u1100-\u115f\ua960-\ua97f]+[\u1160-\u11a7\ud7b0-\ud7c6]+$/u;
+const CLOSED_HANGUL_CLUSTER_PATTERN =
+ /^[\u1100-\u115f\ua960-\ua97f]+[\u1160-\u11a7\ud7b0-\ud7c6]+[\u11a8-\u11ff\ud7cb-\ud7fb]+$/u;
+const VOWEL_OR_TRAILING_HANGUL_JAMO_SOURCE =
+ "[\\u1160-\\u11a7\\ud7b0-\\ud7c6\\u11a8-\\u11ff\\ud7cb-\\ud7fb]";
+const TRAILING_HANGUL_JAMO_SOURCE = "[\\u11a8-\\u11ff\\ud7cb-\\ud7fb]";
+
+/** Any Hangul at all, asked first so an ASCII query pays one test and stops. */
+const HANGUL_HINT_PATTERN = /[ᄀ-ᇿꥠ-꥿가-ퟻ]/u;
+
+/**
+ * True when a cluster needs the trailing-jamo boundary, which only the pattern path writes.
+ *
+ * Extended and Old Hangul jamo have no precomposed form, so NFC and NFD spell them the same way and
+ * the single-spelling query would take the literal scan, where an open syllable prefix-matches a
+ * closed one. Modern Hangul always has two spellings and reaches the pattern anyway.
+ */
+function needsHangulBoundary(needle: string): boolean {
+ if (!HANGUL_HINT_PATTERN.test(needle)) return false;
+ for (const [cluster] of needle.normalize("NFD").matchAll(CLUSTER_PATTERN)) {
+ if (
+ OPEN_HANGUL_CLUSTER_PATTERN.test(cluster) ||
+ CLOSED_HANGUL_CLUSTER_PATTERN.test(cluster)
+ )
+ return true;
+ }
+ return false;
+}
+
+/** A closed syllable's L+V pair and everything after it. */
+const HANGUL_LVT_PATTERN =
+ /^([\u1100-\u115f\ua960-\ua97f][\u1160-\u11a7\ud7b0-\ud7c6])([\u11a8-\u11ff\ud7cb-\ud7fb][\s\S]*)$/u;
+
+/**
+ * The half-composed spelling of a closed syllable: the L+V pair precomposed, the trailing jamo left
+ * as it is. Neither NFC nor NFD writes it, so a document holding one is invisible to both.
+ */
+function partiallyComposedHangul(cluster: string): string | null {
+ const parts = HANGUL_LVT_PATTERN.exec(cluster);
+ if (!parts) return null;
+ const partial = parts[1].normalize("NFC") + parts[2];
+ return partial === cluster ? null : partial;
+}
/**
* The needle as a regex source in which each cluster may match either of its spellings.
@@ -529,13 +647,23 @@ function canonicalSource(needle: string, dotted: boolean): string {
const spellings = [cluster];
const composed = cluster.normalize("NFC");
if (composed !== cluster) spellings.push(composed);
+ // Hangul composes in two steps, and text can stop after the first.
+ const partial = partiallyComposedHangul(cluster);
+ if (partial !== null && !spellings.includes(partial))
+ spellings.push(partial);
// A decomposed dotted I folds to `i` plus a combining dot, which has no precomposed form, so
// NFC cannot put it back and the plain query would miss a word plainly on screen.
if (dotted && cluster === "i") spellings.push(`i${COMBINING_DOT}`);
- out +=
+ const spellingSource =
spellings.length === 1
? escapeForRegex(spellings[0])
: `(?:${spellings.map(escapeForRegex).join("|")})`;
+ const boundary = OPEN_HANGUL_CLUSTER_PATTERN.test(cluster)
+ ? `(?!${VOWEL_OR_TRAILING_HANGUL_JAMO_SOURCE})`
+ : CLOSED_HANGUL_CLUSTER_PATTERN.test(cluster)
+ ? `(?!${TRAILING_HANGUL_JAMO_SOURCE})`
+ : "";
+ out += spellingSource + boundary;
}
return out;
}
@@ -553,7 +681,12 @@ function escapeForRegex(text: string): string {
*/
function matchPattern(variants: string[], needle: string): RegExp | null {
const dotted = variants.some((variant) => variant.includes(COMBINING_DOT));
- if (variants.length === 1 && !/\s/.test(needle)) return null;
+ if (
+ variants.length === 1 &&
+ !/\s/.test(needle) &&
+ !needsHangulBoundary(needle)
+ )
+ return null;
try {
const pattern = new RegExp(canonicalSource(needle, dotted), "g");
// V8 compiles lazily, so an oversized pattern is accepted here and throws on the first `exec`
diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.ts
index 447c0c3d7e5..c8d4431ca0c 100644
--- a/studio/frontend/tests/find-in-page.test.ts
+++ b/studio/frontend/tests/find-in-page.test.ts
@@ -17,7 +17,9 @@ import {
FIND_HIGHLIGHT,
FIND_HIGHLIGHT_ACTIVE,
MAX_PAINTED_RANGES,
+ clearHighlights,
mutatesSearchableText,
+ paintHighlights,
paintWindow,
resolvePortalSurfaces,
selectRangeFallback,
@@ -37,10 +39,10 @@ import {
findMatches,
foldText,
normalizeQuery,
+ renumbersMatches,
segmentAt,
startPositionAt,
} from "../src/features/find-in-page/lib/find-text-index.ts";
-import { useFindInPageStore } from "../src/features/find-in-page/stores/find-in-page-store.ts";
// --- the hand-rolled tree ----------------------------------------------------------------------
@@ -126,6 +128,38 @@ test("aria-hidden false does not hide a subtree", () => {
assert.equal(buildTextIndex(root).text, "shown");
});
+test("KaTeX indexes its painted tree instead of its clipped accessibility mirror", () => {
+ const mathmlText = text("x2");
+ const paintedText = text("x2");
+ const root = el(
+ "SPAN",
+ [
+ el("SPAN", [mathmlText], { class: "katex-mathml" }),
+ el("SPAN", [paintedText], {
+ class: "katex-html",
+ "aria-hidden": "true",
+ }),
+ ],
+ { class: "katex" },
+ );
+
+ const index = buildTextIndex(root);
+ const [match] = findMatches(index, "x2");
+ assert.ok(match);
+ assert.equal(
+ index.segments.some((segment) => segment.node === mathmlText),
+ false,
+ "the clipped MathML mirror must not create ranges",
+ );
+ assert.equal(
+ index.segments.some((segment) => segment.node === paintedText),
+ true,
+ "the painted KaTeX tree must create the range",
+ );
+ assert.equal(startPositionAt(index.segments, match.start)?.node, paintedText);
+ assert.equal(endPositionAt(index.segments, match.end)?.node, paintedText);
+});
+
// --- offsets -----------------------------------------------------------------------------------
test("an offset maps back to the node and character it came from", () => {
@@ -866,6 +900,132 @@ test("an occurrence that mixes the two spellings is still one word", () => {
assert.equal(findMatches(split, `caf${composed}caf${composed}`).length, 1);
});
+test("Hangul canonical spellings match without changing document offsets", () => {
+ const composed = "가각";
+ const decomposed = composed.normalize("NFD");
+ const mixed = `가${"각".normalize("NFD")}`;
+
+ for (const written of [composed, decomposed, mixed]) {
+ for (const typed of [composed, decomposed, mixed]) {
+ const node = text(`a ${written} b`);
+ const index = buildTextIndex(el("P", [node]));
+ const matches = findMatches(index, typed);
+ assert.deepEqual(
+ matches,
+ [{ start: 2, end: 2 + written.length }],
+ `text ${escape(written)} and query ${escape(typed)} did not meet`,
+ );
+ assert.equal(
+ startPositionAt(index.segments, matches[0].start)?.node,
+ node,
+ );
+ assert.equal(
+ startPositionAt(index.segments, matches[0].start)?.offset,
+ 2,
+ );
+ assert.equal(
+ endPositionAt(index.segments, matches[0].end)?.offset,
+ 2 + written.length,
+ );
+ }
+ }
+
+ const leading = text("ᄀ");
+ const rest = text("ᅡ각");
+ const split = buildTextIndex(el("P", [leading, el("EM", [rest])]));
+ const [match] = findMatches(split, composed);
+ assert.ok(
+ match,
+ "a decomposed syllable split across inline nodes must match",
+ );
+ assert.equal(startPositionAt(split.segments, match.start)?.node, leading);
+ assert.equal(endPositionAt(split.segments, match.end)?.node, rest);
+ assert.equal(
+ endPositionAt(split.segments, match.end)?.offset,
+ rest.data.length,
+ );
+});
+
+test("an open Hangul syllable cannot match the prefix of a closed one", () => {
+ const open = "가";
+ const closed = "각";
+ for (const written of [closed, closed.normalize("NFD"), `${open}\u11a8`]) {
+ const index = buildTextIndex(el("P", [text(written)]));
+ assert.deepEqual(
+ findMatches(index, open),
+ [],
+ `open ${escape(open)} matched part of closed ${escape(written)}`,
+ );
+ }
+
+ for (const written of [open, open.normalize("NFD")]) {
+ const index = buildTextIndex(el("P", [text(written)]));
+ assert.deepEqual(findMatches(index, open), [
+ { start: 0, end: written.length },
+ ]);
+ }
+});
+
+test("the jamo boundary holds for Hangul that has only one spelling", () => {
+ // Extended and Old Hangul jamo have no precomposed form, so NFC and NFD spell them the same way.
+ // One spelling used to take the literal scan, which writes no boundary, and the open syllable
+ // painted the first two jamo of a visibly closed one. Modern Hangul always has two spellings and
+ // reached the pattern anyway, so this only ever showed up out here.
+ const open = "ꥠힰ";
+ const closed = "ꥠힰퟋ";
+ assert.equal(open.normalize("NFC"), open);
+ assert.equal(open.normalize("NFD"), open);
+
+ const inClosed = buildTextIndex(el("P", [text(closed)]));
+ assert.deepEqual(findMatches(inClosed, open), []);
+ assert.deepEqual(findMatches(inClosed, closed), [
+ { start: 0, end: closed.length },
+ ]);
+
+ const inOpen = buildTextIndex(el("P", [text(open)]));
+ assert.deepEqual(findMatches(inOpen, open), [{ start: 0, end: open.length }]);
+ assert.deepEqual(findMatches(inOpen, closed), []);
+});
+
+test("complete Old Hangul clusters cannot match inside a longer syllable", () => {
+ const leadAndVowels = "ꥠힰힱ";
+ const withTrailing = `${leadAndVowels}ퟋ`;
+ const withTwoTrailing = `${withTrailing}ퟌ`;
+
+ assert.deepEqual(
+ findMatches(buildTextIndex(el("P", [text(withTrailing)])), leadAndVowels),
+ [],
+ );
+ assert.deepEqual(
+ findMatches(buildTextIndex(el("P", [text(withTwoTrailing)])), withTrailing),
+ [],
+ );
+ assert.deepEqual(
+ findMatches(buildTextIndex(el("P", [text(withTrailing)])), withTrailing),
+ [{ start: 0, end: withTrailing.length }],
+ );
+});
+
+test("a half-composed Hangul syllable is found and covered whole", () => {
+ // Hangul composes in two steps, L+V into a syllable and then the trailing jamo into it, and text
+ // can stop after the first. NFC and NFD both write past that spelling, so a document holding one
+ // used to be invisible to every query, its own spelling included.
+ const closed = "각";
+ const spellings = [closed, closed.normalize("NFD"), `각`];
+ for (const written of spellings) {
+ const index = buildTextIndex(el("P", [text(written)]));
+ for (const query of spellings) {
+ assert.deepEqual(
+ findMatches(index, query),
+ [{ start: 0, end: written.length }],
+ `${escape(query)} did not cover ${escape(written)}`,
+ );
+ }
+ // The open syllable still stops at the trailing jamo, whichever way the closed one is written.
+ assert.deepEqual(findMatches(index, "가"), []);
+ }
+});
+
test("the index itself is left in the form the document wrote", () => {
// Normalizing it is the other way to fix the above, and it would change its length: every offset
// in the index stands for one character of a text node, so a shorter index misplaces them all.
@@ -1261,6 +1421,120 @@ test("the stylesheet paints the two highlights the code registers", async () =>
}
});
+test("registered ranges are cleared and repainted before deletion or replacement", () => {
+ const events: string[] = [];
+ class FakeHighlight {
+ priority = 0;
+ constructor(..._ranges: Range[]) {}
+ clear(): void {
+ events.push("clear");
+ }
+ }
+ class FakeElement {
+ private opacity = "";
+ style = {
+ get opacity() {
+ return root.opacity;
+ },
+ set opacity(value: string) {
+ events.push(`opacity:${value}`);
+ root.opacity = value;
+ },
+ };
+ get offsetHeight(): number {
+ events.push("reflow");
+ return 1;
+ }
+ }
+ const root = new FakeElement();
+ const entries = new Map<string, FakeHighlight>([
+ [FIND_HIGHLIGHT, new FakeHighlight()],
+ [FIND_HIGHLIGHT_ACTIVE, new FakeHighlight()],
+ ]);
+ const registry = {
+ get: (name: string) => entries.get(name),
+ set: (name: string, highlight: FakeHighlight) => {
+ events.push(`set:${name}`);
+ entries.set(name, highlight);
+ },
+ delete: (name: string) => {
+ events.push(`delete:${name}`);
+ return entries.delete(name);
+ },
+ };
+ const scope = globalThis as {
+ CSS?: unknown;
+ Highlight?: unknown;
+ HTMLElement?: unknown;
+ document?: unknown;
+ };
+ const saved = {
+ css: scope.CSS,
+ document: scope.document,
+ highlight: scope.Highlight,
+ htmlElement: scope.HTMLElement,
+ hadCss: "CSS" in scope,
+ hadDocument: "document" in scope,
+ hadHighlight: "Highlight" in scope,
+ hadHtmlElement: "HTMLElement" in scope,
+ };
+ scope.CSS = { highlights: registry };
+ scope.Highlight = FakeHighlight;
+ scope.HTMLElement = FakeElement;
+ scope.document = {
+ querySelector: () => root,
+ body: root,
+ documentElement: root,
+ };
+ try {
+ clearHighlights();
+ assert.deepEqual(events, [
+ "clear",
+ `delete:${FIND_HIGHLIGHT_ACTIVE}`,
+ "clear",
+ `delete:${FIND_HIGHLIGHT}`,
+ "opacity:0.999999",
+ "reflow",
+ "opacity:",
+ ]);
+
+ events.length = 0;
+ entries.set(FIND_HIGHLIGHT, new FakeHighlight());
+ entries.set(FIND_HIGHLIGHT_ACTIVE, new FakeHighlight());
+ paintHighlights([{} as Range], {} as Range);
+ assert.deepEqual(events, [
+ "clear",
+ `delete:${FIND_HIGHLIGHT}`,
+ `set:${FIND_HIGHLIGHT}`,
+ "clear",
+ `delete:${FIND_HIGHLIGHT_ACTIVE}`,
+ `set:${FIND_HIGHLIGHT_ACTIVE}`,
+ ]);
+
+ events.length = 0;
+ paintHighlights([], null);
+ assert.deepEqual(events, [
+ "clear",
+ `delete:${FIND_HIGHLIGHT}`,
+ "clear",
+ `delete:${FIND_HIGHLIGHT_ACTIVE}`,
+ "opacity:0.999999",
+ "reflow",
+ "opacity:",
+ ]);
+ } finally {
+ for (const [key, value, had] of [
+ ["CSS", saved.css, saved.hadCss],
+ ["document", saved.document, saved.hadDocument],
+ ["Highlight", saved.highlight, saved.hadHighlight],
+ ["HTMLElement", saved.htmlElement, saved.hadHtmlElement],
+ ] as const) {
+ if (had) Object.assign(scope, { [key]: value });
+ else delete scope[key];
+ }
+ }
+});
+
test("the bar keeps itself out of the region it searches", async () => {
const bar = await readFile(
new URL(
@@ -1388,6 +1662,16 @@ test("the bar stays out of a backgrounded scope, and off the document origin", a
assert.equal(/\babsolute\b/.test(surface[1]), false);
// And capped, so a narrow window cannot push it off the left edge.
assert.match(surface[1], /max-w-\[calc\(100vw-2rem\)\]/);
+
+ // The counter grows from `1/2` to `1234/5000+` in a long chat. The pill must keep its nominal
+ // responsive width and let the query field yield that already-reserved room instead of growing.
+ // 22.25/28.25rem is exactly the previous short-counter width: fixed input + 12rem chrome.
+ assert.match(surface[1], /(?:^|\s)w-\[22\.25rem\](?:\s|$)/);
+ assert.match(surface[1], /(?:^|\s)sm:w-\[28\.25rem\](?:\s|$)/);
+ const input = /<input[\s\S]*?className=\{cn\([\s\S]*?"([^"]*)"/.exec(bar);
+ assert.ok(input);
+ assert.match(input[1], /\bflex-1\b/);
+ assert.equal(/\bw-(?:40|64)\b/.test(input[1]), false);
});
test("the reveal looks again while the scroll is still moving", async () => {
@@ -1527,6 +1811,24 @@ test("a fresh query starts from the scroll container's top, not the window's", a
assert.equal(/top >= 0/.test(engine), false);
});
+test("a pending query clears the previous highlight before the next paint", async () => {
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // The input value is committed during the event. A passive effect may run only after the browser
+ // has painted that new value beside the old query's ranges, which is the visible `sta`/`stan`
+ // mismatch this guards. A layout effect clears those ranges in the same commit, before paint.
+ assert.match(engine, /import \{[^}]*useLayoutEffect[^}]*\} from "react";/);
+ assert.match(
+ engine,
+ /useLayoutEffect\(\(\) => \{\s*if \(queryPending\) \{\s*cancelRevealPasses\(\);\s*clearHighlights\(\);/,
+ );
+});
+
test("re-indexing while the document changes is a throttle, and says so", async () => {
const engine = await readFile(
new URL(
@@ -1625,7 +1927,7 @@ function withPortals<T>(surfaces: Element[], body: () => T): T {
return body();
} finally {
if (had) view.document = saved;
- else delete view.document;
+ else view.document = undefined;
}
}
@@ -1650,6 +1952,39 @@ test("a portaled surface is searched unless it is on its way out", () => {
);
});
+test("explicit monitor portals are searched but are not dismissible surfaces", async () => {
+ const monitor = surface(null);
+ const popover = surface("open");
+ const scope = { contains: () => false } as unknown as Element;
+ const view = globalThis as { document?: unknown };
+ const had = "document" in view;
+ const saved = view.document;
+ view.document = {
+ querySelectorAll: (selector: string) =>
+ selector.includes("data-find-portal") ? [monitor, popover] : [popover],
+ };
+ try {
+ assert.deepEqual(resolvePortalSurfaces(scope), [monitor, popover]);
+ } finally {
+ if (had) view.document = saved;
+ else view.document = undefined;
+ }
+
+ const dom = await readFile(
+ new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(dom, /export function resolveDismissiblePortalSurfaces/);
+
+ for (const path of [
+ "../src/features/api-monitor/api-monitor-overlay.tsx",
+ "../src/components/floating-monitor.tsx",
+ ]) {
+ const component = await readFile(new URL(path, import.meta.url), "utf8");
+ assert.match(component, /\[FIND_PORTAL_ATTRIBUTE\]: ""/);
+ }
+});
+
test("a surface inside the scope, or inside one already taken, is not indexed twice", () => {
const inner = surface("open");
const outer = surface("open", [inner]);
@@ -1727,7 +2062,7 @@ test("Escape closes the bar from the walk buttons, not just the field", async ()
// Two presses it deliberately does not take: a modal above the bar owns Escape, and an open
// popover, menu or listbox is dismissed by its own Escape first.
assert.match(body, /isSurfaceBackgrounded\(/);
- assert.match(body, /resolvePortalSurfaces\(/);
+ assert.match(body, /resolveDismissiblePortalSurfaces\(/);
// And nothing left on the landmark, which would take the inside presses before the window does.
const landmark = bar.slice(bar.indexOf('role="search"'));
assert.equal(
@@ -1881,9 +2216,10 @@ test("the ordinal survives an append and nothing else", async () => {
),
"utf8",
);
+ // One rule, and it lives in the pure module so the tests below can exercise it directly.
assert.match(
engine,
- /const before = indexRef\.current\.text;[\s\S]*?return !indexRef\.current\.text\.startsWith\(before\);/,
+ /return renumbersMatches\(before, indexRef\.current, activeStartRef\.current\);/,
);
// Every rebuild goes through it: no call site decides for itself that the numbering held.
assert.equal(engine.includes("search(false, false)"), false);
@@ -1895,6 +2231,191 @@ test("the ordinal survives an append and nothing else", async () => {
);
});
+test("every navigation waits for the query to settle, buttons included", async () => {
+ // The buttons stay enabled on the previous query's count while an edit is pending, and `apply`
+ // will not paint until it settles, so calling `next`/`previous` from a click dropped it silently.
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(bar, /onClick=\{\(\) => stepWhenSettled\(-1\)\}/);
+ assert.match(bar, /onClick=\{\(\) => stepWhenSettled\(1\)\}/);
+ // No control reaches the raw pair, so a new one cannot copy the losing spelling.
+ assert.equal(/onClick=\{(next|previous)\}/.test(bar), false);
+ // Reaching the handler at all: a settled zero must not disable the walk while the next query is
+ // still pending, or editing "no matches" into a match loses the press to a disabled button.
+ assert.match(
+ bar,
+ /const canStep = searching && \(count > 0 \|\| queryPending\);/,
+ );
+ assert.equal((bar.match(/disabled=\{!canStep\}/g) ?? []).length, 2);
+ assert.equal(bar.includes("disabled={count === 0}"), false);
+ // The helper queues the step and forces the settle rather than dropping it.
+ assert.match(
+ bar,
+ /if \(queryPending\) \{\s*queuedStepRef\.current = delta;\s*settleQuery\(\);/,
+ );
+});
+
+test("the seam between the workspace and the surfaces in front of it is recorded", () => {
+ const workspace = el("DIV", [el("P", [text("unsloth studio")])]);
+ const monitor = el("DIV", [el("P", [text("cpu 12%")])]);
+ const alone = buildTextIndex(workspace);
+ assert.equal(alone.rootLength, alone.text.length);
+ const withMonitor = buildTextIndex(workspace, [monitor]);
+ // The joining separator belongs to the surface, so the workspace slice is only the workspace.
+ assert.equal(withMonitor.rootLength, alone.text.length);
+ assert.equal(withMonitor.text.slice(0, withMonitor.rootLength), alone.text);
+ assert.match(withMonitor.text.slice(withMonitor.rootLength), /cpu 12%$/);
+});
+
+test("inserting an earlier surface renumbers a reader in a later one", () => {
+ const workspace = el("DIV", [el("P", [text("workspace")])]);
+ const laterSurface = el("DIV", [el("P", [text("target")])]);
+ const before = buildTextIndex(workspace, [laterSurface]);
+ const reader = findMatches(before, "target")[0].start;
+
+ const earlierSurface = el("DIV", [el("P", [text("target")])]);
+ const after = buildTextIndex(workspace, [earlierSurface, laterSurface]);
+ assert.equal(findMatches(after, "target")[0].start, reader);
+ assert.equal(renumbersMatches(before, after, reader), true);
+});
+
+test("a monitor polling behind a streaming reply does not move the reader", () => {
+ // The monitor is a permanent tail that rewrites itself on a timer. Judged as one string, every
+ // poll and every streamed character reads as renumbered and re-anchors the reader.
+ const monitorAt = (load: string) => el("DIV", [el("P", [text(load)])]);
+ const reply = (body: string) => el("DIV", [el("P", [text(body)])]);
+
+ const before = buildTextIndex(reply("unsloth one"), [monitorAt("cpu 12%")]);
+ // Where the reader is: on the occurrence in the workspace.
+ const readerInWorkspace = findMatches(before, "unsloth")[0].start;
+
+ // The monitor polls; the workspace has not moved.
+ const polled = buildTextIndex(reply("unsloth one"), [monitorAt("cpu 34%")]);
+ assert.equal(renumbersMatches(before, polled, readerInWorkspace), false);
+
+ // The reply streams on; the monitor has not moved.
+ const streamed = buildTextIndex(reply("unsloth one unsloth two"), [
+ monitorAt("cpu 12%"),
+ ]);
+ assert.equal(renumbersMatches(before, streamed, readerInWorkspace), false);
+ // And the occurrence really is still at the offset the search looks it up by.
+ assert.equal(findMatches(streamed, "unsloth")[0].start, readerInWorkspace);
+
+ // Both at once, which is the ordinary case while a reply lands.
+ const both = buildTextIndex(reply("unsloth one unsloth two"), [
+ monitorAt("cpu 34%"),
+ ]);
+ assert.equal(renumbersMatches(before, both, readerInWorkspace), false);
+});
+
+test("a reader inside a surface gives up its place when the workspace grows under it", () => {
+ // Growing the workspace moves the tail along, so an occurrence inside a surface is no longer at
+ // the offset it is looked up by. That reader, and only that reader, re-anchors.
+ const monitorText = { nodeType: 3 as const, data: "unsloth monitor" };
+ const monitor = el("DIV", [el("P", [monitorText])]);
+ const before = buildTextIndex(el("DIV", [el("P", [text("reply one")])]), [
+ monitor,
+ ]);
+ const readerInMonitor = findMatches(before, "unsloth")[0].start;
+ assert.ok(readerInMonitor >= before.rootLength);
+
+ const grown = buildTextIndex(
+ el("DIV", [el("P", [text("reply one reply two")])]),
+ [monitor],
+ );
+ assert.equal(renumbersMatches(before, grown, readerInMonitor), true);
+
+ // The same growth leaves a reader in the workspace exactly where they were.
+ const workspaceReader = 0;
+ assert.equal(renumbersMatches(before, grown, workspaceReader), false);
+
+ // A poll that does not move the seam keeps even the surface's own reader in place.
+ monitorText.data = "unsloth monitor idle";
+ const polled = buildTextIndex(el("DIV", [el("P", [text("reply one")])]), [
+ monitor,
+ ]);
+ assert.equal(renumbersMatches(before, polled, readerInMonitor), false);
+});
+
+test("a surface reader only minds the text ahead of their occurrence", () => {
+ // A monitor rewrites a reading every second. Only what sits before the occurrence can move it, so
+ // an occurrence in the static label survives the number below it changing.
+ const reply = el("DIV", [el("P", [text("reply one")])]);
+ const labelledText = {
+ nodeType: 3 as const,
+ data: "unsloth monitor cpu 12%",
+ };
+ const labelled = el("DIV", [el("P", [labelledText])]);
+ const before = buildTextIndex(reply, [labelled]);
+ const reader = findMatches(before, "unsloth")[0].start;
+ assert.ok(reader >= before.rootLength);
+ labelledText.data = "unsloth monitor cpu 345%";
+ const polled = buildTextIndex(reply, [labelled]);
+ assert.equal(renumbersMatches(before, polled, reader), false);
+ assert.equal(findMatches(polled, "unsloth")[0].start, reader);
+
+ // A reading AHEAD of the occurrence changing width does move it, and there the offset stops
+ // naming anything: `search` finds no match starting there and re-anchors itself.
+ const leadingText = { nodeType: 3 as const, data: "cpu 12% unsloth monitor" };
+ const leading = el("DIV", [el("P", [leadingText])]);
+ const wasLeading = buildTextIndex(reply, [leading]);
+ const readerAfter = findMatches(wasLeading, "unsloth")[0].start;
+ leadingText.data = "cpu 345% unsloth monitor";
+ const grewLeading = buildTextIndex(reply, [leading]);
+ assert.equal(
+ findMatches(grewLeading, "unsloth").some((m) => m.start === readerAfter),
+ false,
+ );
+
+ // Changing it without changing its width leaves the occurrence exactly where it was, which is
+ // the ordinary poll and must not move the reader.
+ leadingText.data = "cpu 99% unsloth monitor";
+ const sameWidth = buildTextIndex(reply, [leading]);
+ assert.equal(renumbersMatches(wasLeading, sameWidth, readerAfter), false);
+ assert.equal(
+ findMatches(sameWidth, "unsloth").some((m) => m.start === readerAfter),
+ true,
+ );
+});
+
+test("history arriving above the reader still renumbers the list", () => {
+ // The rule this all rests on has not been widened: a prepend is not an append on either side.
+ const monitorText = { nodeType: 3 as const, data: "cpu 12%" };
+ const monitor = el("DIV", [el("P", [monitorText])]);
+ const before = buildTextIndex(el("DIV", [el("P", [text("unsloth one")])]), [
+ monitor,
+ ]);
+ const prepended = buildTextIndex(
+ el("DIV", [el("P", [text("older unsloth one")])]),
+ [monitor],
+ );
+ assert.equal(renumbersMatches(before, prepended, 0), true);
+
+ // A surface whose reading is replaced rather than extended is the ordinary poll, and it must not
+ // renumber anything for a reader in the conversation behind it.
+ monitorText.data = "gpu 12%";
+ const replaced = buildTextIndex(el("DIV", [el("P", [text("unsloth one")])]), [
+ monitor,
+ ]);
+ assert.equal(renumbersMatches(before, replaced, 0), false);
+ // Nor for a reader inside it: the rewrite kept its width, so nothing moved for them either.
+ assert.equal(
+ renumbersMatches(before, replaced, before.text.length - 1),
+ false,
+ );
+ // Growing the workspace under them is what moves a surface reader, and that still renumbers.
+ const grown = buildTextIndex(
+ el("DIV", [el("P", [text("unsloth one unsloth two")])]),
+ [monitor],
+ );
+ assert.equal(renumbersMatches(before, grown, before.text.length - 1), true);
+});
+
test("a breakpoint that changes what is rendered invalidates the index", async () => {
// Crossing one hides or reveals whole columns (`hidden lg:flex`) with nothing in the DOM to
// observe, and the index reads computed visibility, so the observer alone cannot see it.
@@ -1915,41 +2436,17 @@ test("a breakpoint that changes what is rendered invalidates the index", async (
);
});
-test("leaving the shell forgets the search", () => {
- // The store is module-global and keeps the query across a close on purpose. Signing out unmounts
- // the shell, and the next person to sign in in the same tab must not be handed the last one's
- // search, open and focused.
- const store = useFindInPageStore;
- store.getState().setQuery("someone else's search");
- store.getState().requestFocus();
- assert.equal(store.getState().open, true);
- store.getState().reset();
- assert.deepEqual(
- { open: store.getState().open, query: store.getState().query },
- { open: false, query: "" },
- );
-});
-
-test("the shell unmounting is what calls it, not the bar closing", async () => {
- const bar = await readFile(
+test("closing preserves the query while leaving the shell forgets the session", async () => {
+ const controller = await readFile(
new URL(
"../src/features/find-in-page/components/find-in-page.tsx",
import.meta.url,
),
"utf8",
);
- // As an unmount cleanup. Not `enabled`: a dialog turns that off, and the search should still be
- // there when it closes.
- assert.match(bar, /useEffect\(\(\) => reset, \[reset\]\);/);
- // And `close` still keeps the query, which is what makes reopening offer the last search.
- const store = await readFile(
- new URL(
- "../src/features/find-in-page/stores/find-in-page-store.ts",
- import.meta.url,
- ),
- "utf8",
- );
- assert.match(store, /close: \(\) => set\(\{ open: false \}\),/);
+ assert.match(controller, /useEffect\(\(\) => reset, \[reset\]\);/);
+ assert.equal(controller.includes('setQuery("")'), false);
+ assert.match(controller, /useFindInPageStore/);
});
test("the capped window follows the reader, not the top of the document", () => {
@@ -2145,9 +2642,9 @@ test("Escape is left to the IME while it is composing", async () => {
),
"utf8",
);
- const escape = bar.slice(bar.indexOf("const onEscape ="));
- const guard = escape.indexOf("isImeComposing(event)");
- const consume = escape.indexOf("event.preventDefault()");
+ const escapeHandler = bar.slice(bar.indexOf("const onEscape ="));
+ const guard = escapeHandler.indexOf("isImeComposing(event)");
+ const consume = escapeHandler.indexOf("event.preventDefault()");
assert.ok(guard > 0 && guard < consume);
// Safe to let through: the global listener stands aside for a composing event before it looks
// for a binding, so the bare-Escape decline cannot take it either.
@@ -2281,18 +2778,3 @@ test("a container query resizing the scope invalidates the index", async () => {
/if \(!measured\) \{\s*\n\s*measured = true;\s*\n\s*return;/,
);
});
-
-test("nothing of the engine is mounted while the bar is closed", async () => {
- const bar = await readFile(
- new URL(
- "../src/features/find-in-page/components/find-in-page.tsx",
- import.meta.url,
- ),
- "utf8",
- );
- // The index, the observer and the highlights all live in `useFindInPage`, and the only component
- // that calls it is behind this return. A hook moved above it would run them on every route.
- assert.match(bar, /if \(!enabled \|\| !open\) return null;/);
- const engineCallers = bar.match(/useFindInPage\(/g) ?? [];
- assert.equal(engineCallers.length, 1);
-});
diff --git a/tests/studio/playwright_find_in_page.py b/tests/studio/playwright_find_in_page.py
index 212d51276b2..2139a6d7608 100644
--- a/tests/studio/playwright_find_in_page.py
+++ b/tests/studio/playwright_find_in_page.py
@@ -1,29 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Find in page, in a real browser, on three engines and three emulated platforms.
+"""Exercise find-in-page in real browsers and degraded engine modes.
-Drives smoke-find-in-page.html. The node suite covers the flatten, the offset
-map and the search, which are pure; a Range has no geometry off a document,
-CSS.highlights paints nothing, and a chord the browser owns cannot be taken
-from it in a unit test, so the rest is only answerable here.
+The Node suite covers pure indexing. This harness covers browser-only chords, geometry,
+highlights, fallback selection, and visibility behavior.
SMOKE_ENGINES=chromium,firefox,webkit python3 tests/studio/playwright_find_in_page.py
-Three engine capabilities decide which path the bar takes, each degraded
-deliberately rather than waited for:
-
- - no Custom Highlight API (Firefox below 140, and whatever WebKitGTK the host
- shipped), so the bar falls back to selecting the active match;
- - checkVisibility honouring only the historic option names (Chrome 105-120,
- Firefox 106-121), where Web IDL drops the modern spellings silently and
- hidden text would otherwise be indexed;
- - no checkVisibility at all (Safari below 17.4, WebKitGTK), where the call
- answers undefined and the computed properties stand in.
-
-Platform is emulated the way the app reads it, through navigator.platform and
-the user agent, because isMacPlatform() is memoised on first call.
-"""
+The modes emulate missing highlight support, legacy visibility options, and no visibility API."""
import json
import os
@@ -44,6 +29,10 @@ PORT = int(os.environ.get("SMOKE_PORT", "5419"))
ENGINES = [e for e in os.environ.get("SMOKE_ENGINES", "chromium").split(",") if e]
URL = f"http://127.0.0.1:{PORT}/smoke-find-in-page.html"
+ENTRY_FAIL = os.environ.get("SMOKE_ENTRY_FAIL", "")
+
+ENTRY_DELAY_MS = int(os.environ.get("SMOKE_ENTRY_DELAY_MS", "0"))
+ENTRY_SCREENSHOT = os.environ.get("SMOKE_ENTRY_SCREENSHOT", "")
PLATFORMS = {
"macOS": ("MacIntel", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) SmokeUA"),
"Windows": ("Win32", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeUA"),
@@ -107,12 +96,17 @@ def counter(page) -> str | None:
def state(page) -> dict:
- return page.evaluate("() => window.__findSmoke.store.getState()")
+ return page.evaluate("() => window.__findSmoke.state()")
def open_bar(page, mod: str) -> None:
page.keyboard.press(f"{mod}+f")
- page.wait_for_timeout(250)
+ # The production bar crosses a lazy boundary so the first open can include
+ # one dev-server transform. Assert that it resolves, not that Vite is warm.
+ page.wait_for_function(
+ "() => window.__findSmoke.state().open",
+ timeout = 10000,
+ )
def close_bar(page) -> None:
@@ -133,14 +127,14 @@ def check_chord(page, engine: str, mode: str, mod: str) -> None:
# Re-pressing it while the field has focus restarts the search rather than
# handing the chord back to the browser.
- before = state(page).get("focusToken")
+ page.evaluate("() => document.activeElement?.blur()")
page.keyboard.press(f"{mod}+f")
page.wait_for_timeout(200)
check(
engine,
mode,
"the chord re-focuses the field instead of closing",
- state(page).get("open") is True and state(page).get("focusToken") != before,
+ state(page).get("open") is True and state(page).get("focused") is True,
)
close_bar(page)
check(engine, mode, "Escape closes the bar", state(page).get("open") is False)
@@ -296,7 +290,8 @@ def check_modal_gate(page, engine: str, mode: str, mod: str) -> None:
"""A modal backgrounds the scope, and the chord must go back to the browser."""
page.evaluate("() => window.__findSmoke.setModal(true)")
page.wait_for_timeout(250)
- open_bar(page, mod)
+ page.keyboard.press(f"{mod}+f")
+ page.wait_for_timeout(250)
check(
engine,
mode,
@@ -316,15 +311,7 @@ def check_modal_gate(page, engine: str, mode: str, mod: str) -> None:
def check_hidden_text(page, engine: str, mode: str, mod: str) -> None:
- """Text nobody can see must not be counted, however it was hidden.
-
- `display: none` is the case an engine with no checkVisibility gets wrong,
- `visibility: hidden` is the case an engine from before the checkVisibility
- option rename gets wrong, and `display: contents` + `visibility: hidden` is
- the case where only ELEMENT children are re-checked, so a direct text child
- slips through. All three are planted here rather than in the harness so this
- stays honest about what it is measuring.
- """
+ """Verify display-none, hidden visibility, and hidden contents text are excluded."""
page.evaluate(
"""() => {
const scope = document.querySelector('[data-find-scope]') ?? document.body;
@@ -374,14 +361,7 @@ def check_hidden_text(page, engine: str, mode: str, mod: str) -> None:
def check_content_visibility_reveal(page, engine: str, mode: str, mod: str) -> None:
- """A match under `content-visibility: auto` has to end up on screen.
-
- A scroll reaches only as far as the scrollHeight the engine knows about, and a skipped subtree
- contributes its `contain-intrinsic-size` placeholder until it renders. Reaching toward it is
- what makes it relevant, so the document grows underneath the scroll that was aimed at it. The
- Hub puts this containment on README prose and on each top-level child (hub.css), and only a real
- viewport can measure it, which is why it is here and not in the node suite.
- """
+ """Verify a match below a `content-visibility: auto` placeholder is revealed."""
planted = page.evaluate(
"""() => {
const conversation = document.querySelector('[data-find-scope] .mx-auto');
@@ -442,14 +422,7 @@ def check_content_visibility_reveal(page, engine: str, mode: str, mod: str) -> N
def check_spelling_variants(page, engine: str, mode: str, mod: str) -> None:
- """A word composed and a word decomposed have to find each other.
-
- macOS hands back decomposed filenames while a model writes composed prose,
- so one thread holds both. The index is left in the form the document wrote,
- since normalizing it would change its length and misplace every offset, so
- what is checked here is that the painted range still covers exactly the
- characters that were written.
- """
+ """Verify composed and decomposed spellings share a correctly mapped range."""
planted = page.evaluate(
"""() => {
const scope = document.querySelector('[data-find-scope]') ?? document.body;
@@ -476,9 +449,8 @@ def check_spelling_variants(page, engine: str, mode: str, mod: str) -> None:
shown == "1/1",
f"counter={shown!r}",
)
- # Only where there is a registry to read. On the fallback path the selection is dropped on
- # purpose to give the caret back to the field, so there is nothing left to measure; the count
- # above is the part that holds on every engine.
+ # Only the registry path exposes a range; fallback selection is intentionally released so the
+ # field remains usable.
if page.evaluate("() => typeof CSS !== 'undefined' && !!CSS.highlights"):
covers = page.evaluate(
"""() => {
@@ -498,6 +470,171 @@ def check_spelling_variants(page, engine: str, mode: str, mod: str) -> None:
page.evaluate("() => document.getElementById('probe-nfd')?.remove()")
+def check_typing_burst(page, engine: str, mode: str, mod: str) -> None:
+ """A word typed quickly searches once, without stalling each following key."""
+ open_bar(page, mod)
+ field = page.locator('[role="search"] input')
+ field.fill("")
+ page.wait_for_timeout(150)
+ page.evaluate(
+ """() => {
+ window.__findSmokePaints = 0;
+ if (CSS.highlights) {
+ const registry = CSS.highlights;
+ const set = registry.set.bind(registry);
+ registry.set = (...args) => {
+ window.__findSmokePaints += 1;
+ return set(...args);
+ };
+ } else {
+ const addRange = Selection.prototype.addRange;
+ Selection.prototype.addRange = function (...args) {
+ window.__findSmokePaints += 1;
+ return addRange.apply(this, args);
+ };
+ }
+ }"""
+ )
+ page.keyboard.type("doing", delay = 10)
+ immediate = field.input_value()
+ page.wait_for_timeout(400)
+ paints = page.evaluate("() => window.__findSmokePaints")
+ shown = counter(page)
+ check(
+ engine,
+ mode,
+ "a typing burst leaves every character responsive",
+ immediate == "doing",
+ f"value={immediate!r}",
+ )
+ check(
+ engine,
+ mode,
+ "a typing burst coalesces to one search paint",
+ paints <= 2 and bool(shown),
+ f"paint operations={paints}, counter={shown!r}",
+ )
+ close_bar(page)
+
+
+def check_reverted_query_repaints(page, engine: str, mode: str, mod: str) -> None:
+ """Restoring the settled query inside the debounce window must restore its paint."""
+ if not page.evaluate("() => typeof CSS !== 'undefined' && !!CSS.highlights"):
+ return
+ open_bar(page, mod)
+ field = page.locator('[role="search"] input')
+ field.fill("unsloth")
+ page.wait_for_function(
+ "() => !!window.__findSmoke.counter()",
+ timeout = 10000,
+ )
+ page.wait_for_timeout(150)
+ before = page.evaluate(
+ """() => CSS.highlights.has('unsloth-find') &&
+ CSS.highlights.has('unsloth-find-active')"""
+ )
+ field.press("End")
+ field.type("x")
+ page.wait_for_timeout(20)
+ field.press("Backspace")
+ page.wait_for_timeout(250)
+ after = page.evaluate(
+ """() => ({
+ painted: CSS.highlights.has('unsloth-find') &&
+ CSS.highlights.has('unsloth-find-active'),
+ counter: window.__findSmoke.counter(),
+ })"""
+ )
+ check(
+ engine,
+ mode,
+ "returning to the settled query repaints its unchanged matches",
+ before is True and field.input_value() == "unsloth" and after["painted"] is True,
+ f"painted before={before}, after={after}, value={field.input_value()!r}",
+ )
+ close_bar(page)
+
+
+def check_pending_query_stays_unpainted(page, engine: str, mode: str, mod: str) -> None:
+ """Keeps old highlights from repainting during a typing burst."""
+ if not page.evaluate("() => typeof CSS !== 'undefined' && !!CSS.highlights"):
+ return
+ open_bar(page, mod)
+ field = page.locator('[role="search"] input')
+ field.fill("unsloth")
+ page.wait_for_function("() => !!window.__findSmoke.counter()", timeout = 10000)
+ page.wait_for_timeout(150)
+ field.press("End")
+ field.type("x")
+ page.evaluate(
+ """() => {
+ document.getElementById('pending-repaint-probe')?.remove();
+ const row = document.createElement('p');
+ row.id = 'pending-repaint-probe';
+ row.textContent = 'mutation while the query remains unsettled';
+ document.querySelector('[data-find-scope]').appendChild(row);
+ }"""
+ )
+ field.type("abcdefghi", delay = 55)
+ pending = {
+ "value": field.input_value(),
+ "counter": counter(page),
+ "painted": page.evaluate(
+ """() => CSS.highlights.has('unsloth-find') ||
+ CSS.highlights.has('unsloth-find-active')"""
+ ),
+ }
+ check(
+ engine,
+ mode,
+ "an asynchronous reindex stays unpainted while the query is pending",
+ pending["value"] != "unsloth"
+ and pending["counter"] in (None, "")
+ and not pending["painted"],
+ f"pending state={pending}",
+ )
+ page.wait_for_timeout(150)
+ close_bar(page)
+ page.evaluate("() => document.getElementById('pending-repaint-probe')?.remove()")
+
+
+def check_katex_mutation_reindexes(page, engine: str, mode: str, mod: str) -> None:
+ """A text mutation in KaTeX's painted aria-hidden tree invalidates the index."""
+ page.evaluate(
+ """() => {
+ const scope = document.querySelector('[data-find-scope]') ?? document.body;
+ document.getElementById('probe-katex-mutation')?.remove();
+ const host = document.createElement('span');
+ host.id = 'probe-katex-mutation';
+ host.className = 'katex';
+ host.innerHTML = '<span class="katex-mathml">ignored mirror</span>' +
+ '<span class="katex-html" aria-hidden="true">mutablekatex</span>';
+ scope.appendChild(host);
+ }"""
+ )
+ page.wait_for_timeout(500)
+ open_bar(page, mod)
+ page.locator('[role="search"] input').fill("mutablekatex")
+ page.wait_for_function(
+ "() => window.__findSmoke.counter() === '1/1'",
+ timeout = 10000,
+ )
+ page.evaluate(
+ "() => { document.querySelector('#probe-katex-mutation .katex-html').textContent = 'changedkatex'; }"
+ )
+ page.wait_for_timeout(900)
+ after = counter(page)
+ check(
+ engine,
+ mode,
+ "a KaTeX painted-text mutation refreshes the count",
+ after in (None, "", "0/0"),
+ f"counter={after!r} (1/1 means aria-hidden mutation filtering stayed stale)",
+ )
+ close_bar(page)
+ page.evaluate("() => document.getElementById('probe-katex-mutation')?.remove()")
+
+
def check_skip_attribute(page, engine: str, mode: str, mod: str) -> None:
"""Marking a region skippable has to take it out of the count."""
page.evaluate(
@@ -545,6 +682,10 @@ def run_page(page, engine: str, mode: str, mod: str) -> None:
check_hidden_text,
check_content_visibility_reveal,
check_spelling_variants,
+ check_typing_burst,
+ check_reverted_query_repaints,
+ check_pending_query_stays_unpainted,
+ check_katex_mutation_reindexes,
check_skip_attribute,
):
try:
@@ -573,9 +714,187 @@ def new_page(context):
return page
+def run_entry_chunk_failure(browser, engine: str) -> None:
+ """A first-use find chunk failure degrades locally instead of unmounting the shell."""
+ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])
+
+ def block_find_entry(route):
+ if "find-bar-loader" in route.request.url:
+ return route.abort("failed")
+ return route.fallback()
+
+ context.route("**/*", block_find_entry)
+ page = new_page(context)
+ page.keyboard.press("Control+f")
+ failure = page.locator('[data-testid="find-in-page-load-failure"]')
+ failure.wait_for(state = "visible", timeout = 15000)
+ root_text = page.locator("#root").inner_text()
+ mode = "entry-chunk-failure"
+ check(engine, mode, "the local failure notice is visible", failure.count() == 1)
+ check(
+ engine,
+ mode,
+ "the failure offers reload recovery",
+ failure.get_by_role("button").count() == 1,
+ )
+ check(
+ engine,
+ mode,
+ "the conversation shell survives",
+ "Message 1" in root_text and "Message 40" in root_text,
+ f"root text length={len(root_text)}",
+ )
+ check(
+ engine,
+ mode,
+ "the failed bar does not leave a search landmark",
+ page.locator('[role="search"]').count() == 0,
+ )
+ if ENTRY_SCREENSHOT:
+ Path(ENTRY_SCREENSHOT.format(engine = engine)).parent.mkdir(parents = True, exist_ok = True)
+ page.screenshot(path = ENTRY_SCREENSHOT.format(engine = engine), full_page = False)
+ context.close()
+
+
+def run_entry_chunk_delay(browser, engine: str) -> None:
+ """Keeps query, focus, selection, and commands through a delayed entry handoff."""
+ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])
+ page = new_page(context)
+ composer = page.locator('textarea[placeholder="Message"]')
+ composer.focus()
+ started = time.monotonic()
+ page.keyboard.press("Control+f")
+ loading = page.get_by_test_id("find-in-page-loading")
+ loading.wait_for(state = "visible", timeout = 5000)
+ field = loading.locator("input")
+ page.keyboard.type("unsloth", delay = 15)
+ field.press("End")
+ for _ in range(3):
+ field.press("Shift+ArrowLeft")
+
+ field.press("Enter")
+ loading_state = field.evaluate(
+ """input => ({
+ value: input.value,
+ start: input.selectionStart,
+ end: input.selectionEnd,
+ direction: input.selectionDirection,
+ })"""
+ )
+ composer_value = composer.input_value()
+ loading.wait_for(
+ state = "detached",
+ timeout = max(15000, ENTRY_DELAY_MS + 10000),
+ )
+ elapsed_ms = (time.monotonic() - started) * 1000
+ loaded = page.locator('[role="search"] input')
+ loaded_state = loaded.evaluate(
+ """input => ({
+ value: input.value,
+ start: input.selectionStart,
+ end: input.selectionEnd,
+ direction: input.selectionDirection,
+ })"""
+ )
+ mode = "entry-chunk-delay"
+ check(
+ engine,
+ mode,
+ "the controlled loading shell receives early typing",
+ loading_state["value"] == "unsloth" and composer_value == "",
+ f"loading={loading_state}, composer={composer_value!r}",
+ )
+ check(
+ engine,
+ mode,
+ "the configured delay holds the real entry chunk",
+ elapsed_ms >= ENTRY_DELAY_MS * 0.8,
+ f"delay={ENTRY_DELAY_MS}ms, observed={elapsed_ms:.1f}ms",
+ )
+ check(
+ engine,
+ mode,
+ "the loaded bar retains the query and focus",
+ loaded_state["value"] == "unsloth" and state(page).get("focused") is True,
+ f"loaded={loaded_state}, state={state(page)}",
+ )
+ check(
+ engine,
+ mode,
+ "the loaded bar retains the loading input selection",
+ loaded_state == loading_state,
+ f"loading={loading_state}, loaded={loaded_state}",
+ )
+ check(
+ engine,
+ mode,
+ "Enter queued by the loading shell advances after handoff",
+ "2/28" in page.locator('[role="search"]').inner_text(),
+ page.locator('[role="search"]').inner_text(),
+ )
+ context.close()
+
+ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])
+ page = new_page(context)
+ page.locator('textarea[placeholder="Message"]').focus()
+ page.keyboard.press("Control+f")
+ loading = page.get_by_test_id("find-in-page-loading")
+ loading.wait_for(state = "visible", timeout = 5000)
+ loading.locator("input").dispatch_event(
+ "keydown",
+ {
+ "key": "Escape",
+ "code": "Escape",
+ "keyCode": 229,
+ "isComposing": True,
+ "bubbles": True,
+ "cancelable": True,
+ },
+ )
+ page.wait_for_timeout(100)
+ check(
+ engine,
+ mode,
+ "a composing Escape leaves the loading find session open",
+ loading.count() == 1,
+ )
+ context.close()
+
+ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])
+ page = new_page(context)
+ page.locator('textarea[placeholder="Message"]').focus()
+ page.keyboard.press("Control+f")
+ loading = page.get_by_test_id("find-in-page-loading")
+ loading.wait_for(state = "visible", timeout = 5000)
+ page.locator("[data-find-scope]").click(position = {"x": 20, "y": 200})
+ page.keyboard.press("Escape")
+ page.wait_for_timeout(100)
+ check(
+ engine,
+ mode,
+ "Escape closes the loading find session after focus leaves it",
+ page.locator('[role="search"]').count() == 0,
+ )
+ context.close()
+
+
def run_engine(pw, engine: str) -> None:
launch = {"args": chromium_launch_args()} if engine == "chromium" else {}
browser = getattr(pw, engine).launch(**launch)
+
+ if ENTRY_FAIL:
+ try:
+ run_entry_chunk_failure(browser, engine)
+ finally:
+ browser.close()
+ return
+
+ if ENTRY_DELAY_MS:
+ try:
+ run_entry_chunk_delay(browser, engine)
+ finally:
+ browser.close()
+ return
try:
# The platform sweep, on the engine's own capabilities.
for platform, (nav_platform, agent) in PLATFORMS.items():
@@ -608,6 +927,10 @@ def run_engine(pw, engine: str) -> None:
def main() -> int:
+ if ENTRY_DELAY_MS:
+ os.environ["SMOKE_MODULE_DELAY_MATCH"] = "find-bar-loader"
+ os.environ["SMOKE_MODULE_DELAY_MS"] = str(ENTRY_DELAY_MS)
+
server = start_vite(PORT)
try:
with sync_playwright() as pw: