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.

studio: find in page on Cmd/Ctrl+F (#10061)

Michael Han39673fbdb725
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 1200da617a7..5c836fb34de 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -25,6 +25,7 @@ on:
- 'tests/studio/probe_dismiss_guard.py'
- 'tests/studio/playwright_settings_tabs.py'
- 'tests/studio/playwright_keyboard_shortcuts.py'
+ - 'tests/studio/playwright_find_in_page.py'
- 'tests/studio/playwright_tool_activity.py'
- 'tests/studio/playwright_stream_pacing.py'
- 'tests/studio/playwright_code_block_flicker.py'
@@ -435,6 +436,19 @@ jobs:
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_keyboard_shortcuts.py
+ # The node suite reaches 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 count, the walk and
+ # the teardown are only answerable here. The run also degrades the engine three ways:
+ # no highlight registry, a checkVisibility that honours only the historic option
+ # names, and no checkVisibility at all, which between them are Firefox below 140,
+ # Chrome 105-120, and the WebKitGTK the desktop build is handed. Chromium here
+ # because that is what this job installs; SMOKE_ENGINES=chromium,firefox,webkit
+ # runs all three locally.
+ - name: Browser smoke for find in page
+ working-directory: ${{ github.workspace }}
+ run: python3 tests/studio/playwright_find_in_page.py
+
- name: Browser smoke for tool activity collapse
working-directory: ${{ github.workspace }}
env:
diff --git a/studio/frontend/smoke-find-in-page-main.tsx b/studio/frontend/smoke-find-in-page-main.tsx
new file mode 100644
index 00000000000..bb1a31f7315
--- /dev/null
+++ b/studio/frontend/smoke-find-in-page-main.tsx
@@ -0,0 +1,343 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness for the find bar: a vite entry with no backend, driving the real bar, the real index and
+// the real CSS Custom Highlight API against a real browser.
+//
+// The node suite reaches everything pure. What a highlight looks like painted, whether the walk
+// scrolls only when a match is off screen, whether an `inert` panel stays out of the count, and
+// what a streaming reply costs an open bar are only answerable here.
+
+/* eslint-disable no-restricted-imports -- a harness entry point, not app code. */
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { FindInPage } from "@/features/find-in-page";
+import {
+ FIND_SCOPE_ATTRIBUTE,
+ 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";
+import { createRoot } from "react-dom/client";
+
+declare global {
+ interface Window {
+ // Optional: the app typechecks this entry, only the harness page installs it.
+ __findSmoke?: {
+ store: typeof useFindInPageStore;
+ /** 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. */
+ scrollTop: () => number;
+ /** Append a message, one character at a time, the way a reply streams in. */
+ stream: (text: string, msPerChar?: number) => void;
+ /** Time one flatten of the harness document, in milliseconds. */
+ timeIndex: () => number;
+ /** Stand in for a modal: Radix marks the shell aria-hidden for as long as one is up. */
+ setModal: (open: boolean) => void;
+ /** Swap the scroller from the scope to an outer container, as non-chat routes do. */
+ setOuterScroll: (outer: boolean) => void;
+ /** Insert older messages ABOVE the thread, the way progressive completion does. */
+ prepend: (count: number) => void;
+ /** Switch workspaces the way the shell does: flip `inert` off one panel and on to the other. */
+ setWorkspace: (which: "chat" | "other") => void;
+ /** Unmount the whole content region, the way /login does when a user signs out. */
+ setShell: (mounted: boolean) => void;
+ };
+ }
+}
+
+/** Filler that mentions the search term often enough for a walk to be worth watching. */
+const PARAGRAPHS = [
+ "Unsloth Studio runs 500+ open models entirely offline, and this line exists so a search for unsloth has somewhere to land.",
+ "Training with Unsloth is about twice as fast and uses roughly 70% less VRAM, or about 80% less on reinforcement learning.",
+ "The Hub picker fills in hyperparameters for you; the export step writes GGUF, 16-bit safetensors or adapters.",
+ "Data Recipes turns unstructured documents into a training-ready dataset through a graph of processing nodes.",
+ "A long conversation is where find-in-page earns its keep, so this harness paints one that does not fit on a screen.",
+];
+
+function Conversation({ extra, older }: { extra: string[]; older: string[] }) {
+ return (
+ <div className="mx-auto flex max-w-2xl flex-col gap-4 px-6 py-10">
+ {/* Rows the progressive window withheld, arriving ABOVE everything already indexed. */}
+ {older.map((text, i) => (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: append-only list
+ key={`older-${i}`}
+ data-older=""
+ className="rounded-xl border border-border bg-card p-4 text-card-foreground text-sm"
+ >
+ <p>{text}</p>
+ </div>
+ ))}
+ {Array.from({ length: 40 }, (_, i) => (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed-length static filler
+ key={i}
+ className="rounded-xl border border-border bg-card p-4 text-card-foreground text-sm"
+ >
+ <p className="mb-1 font-medium text-muted-foreground text-xs">
+ Message {i + 1}
+ </p>
+ <p>{PARAGRAPHS[i % PARAGRAPHS.length]}</p>
+ {/* A markdown soft wrap: one text node with a newline, rendered as one line. */}
+ {i === 0 ? (
+ <p>{"A soft wrapped\n phrase about unsloth."}</p>
+ ) : null}
+ </div>
+ ))}
+ {/* Skipped, not hidden: what a Hub README and a maths-bearing thread use. It sits below the
+ fold of a long list, so the engine really is skipping it, and it has to stay searchable. */}
+ <div
+ data-skipped=""
+ style={{
+ contentVisibility: "auto",
+ containIntrinsicSize: "auto 400px",
+ }}
+ >
+ <p>unsloth inside a skipped subtree</p>
+ </div>
+ {/* A screen-reader label: a real box at full opacity, clipped to nothing. */}
+ <span className="sr-only">unsloth data input handle</span>
+ {/* A collapsible, as a Hub README renders one. Opening it changes the `open` attribute and
+ nothing else, while its body goes from skipped to searchable. */}
+ <details data-collapsible="">
+ <summary>Release notes</summary>
+ <p>unsloth inside a collapsible</p>
+ </details>
+ {/* Transparent until the row is hovered, which is a hover affordance rather than an entrance
+ animation: a match in here would be walked to under a highlight nobody can see. */}
+ <div className="group/row">
+ <span
+ data-find-skip=""
+ className="opacity-0 transition-opacity group-hover/row:opacity-100"
+ >
+ unsloth hover only badge
+ </span>
+ </div>
+ {/* Greek, where the fold of a sigma depends on what follows it, next to a character whose
+ own fold is two units long. */}
+ <p data-greek="">{"\u039f\u0394\u039f\u03a3 \u0130 \u039f\u03a3"}</p>
+ {/* The same word split by inline markup, which is how markdown emphasis arrives. */}
+ <p data-greek-split="">
+ {"\u039f"}
+ <em>{"\u03a3"}</em>
+ </p>
+ {/* A code fence, where whitespace is what it says it is rather than what HTML collapses it
+ to. A query typed with one space must not land on three. */}
+ <pre className="whitespace-pre rounded-lg bg-muted p-3 text-xs">
+ {"def train(model):\n unsloth fast = True\n"}
+ </pre>
+ {/* Two spans the CSS renders as blocks, which is how the research panel stacks a source's
+ title over its URL. No tag name says so, and run together they invent a word. */}
+ <div data-css-blocks="">
+ <span className="block">Open</span>
+ <span className="block">AI models</span>
+ </div>
+ {/* An inline SVG, as a Mermaid diagram renders. Its tag name is lowercase in an HTML
+ document, which is how it slipped past a skip list spelled in HTML casing. */}
+ <svg viewBox="0 0 200 40" role="img" aria-label="diagram">
+ <title>diagram</title>
+ <text x="0" y="20">
+ unsloth drawn into a diagram
+ </text>
+ </svg>
+ {/* Boxless, not hidden: `display: contents` is how the shell and the training page hand a
+ grid its children, and `checkVisibility` calls a wrapper with no box invisible. */}
+ <div className="contents">
+ <p>unsloth inside a display contents wrapper</p>
+ </div>
+ {extra.map((text, i) => (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: append-only list
+ key={`extra-${i}`}
+ data-streamed=""
+ className="rounded-xl border border-primary/40 bg-card p-4 text-card-foreground text-sm"
+ >
+ <p>{text}</p>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/** A second workspace, parked above the conversation exactly as the shell parks one. Its matches
+ * come BEFORE the thread's, so switching to it is not an append. */
+function OtherWorkspace({ active }: { active: boolean }) {
+ return (
+ <div hidden={!active} inert={!active || undefined} data-workspace="other">
+ {Array.from({ length: 12 }, (_, i) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed-length static filler
+ <div key={i} className="rounded-xl border border-border p-4 text-sm">
+ <p>Another workspace, unsloth line {i + 1}.</p>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function Harness() {
+ const [streamed, setStreamed] = useState<string[]>([]);
+ const [workspace, setWorkspace] = useState<"chat" | "other">("chat");
+ const [shell, setShell] = useState(true);
+ const [older, setOlder] = useState<string[]>([]);
+ const [modal, setModal] = useState(false);
+ const [outerScroll, setOuterScroll] = useState(false);
+ const scrollerRef = useRef<HTMLDivElement>(null);
+ const scopeRef = useRef<HTMLDivElement>(null);
+
+ const stream = useCallback((text: string, msPerChar = 12) => {
+ setStreamed((rows) => [...rows, ""]);
+ let at = 0;
+ const tick = () => {
+ at += 1;
+ setStreamed((rows) => {
+ const next = [...rows];
+ next[next.length - 1] = text.slice(0, at);
+ return next;
+ });
+ if (at < text.length) setTimeout(tick, msPerChar);
+ };
+ setTimeout(tick, msPerChar);
+ }, []);
+
+ useEffect(() => {
+ window.__findSmoke = {
+ store: useFindInPageStore,
+ counter: () =>
+ document.querySelector('[role="search"] [aria-live="polite"]')
+ ?.textContent ?? null,
+ scrollTop: () => scrollerRef.current?.scrollTop ?? -1,
+ stream,
+ setModal,
+ setOuterScroll,
+ setWorkspace,
+ setShell,
+ prepend: (count) =>
+ setOlder(
+ Array.from(
+ { length: count },
+ (_, i) => `An older message about unsloth, number ${i + 1}.`,
+ ),
+ ),
+ // What one flatten of a conversation costs, against the same function the bar calls.
+ timeIndex: () => {
+ const scope = scopeRef.current;
+ if (!scope) return -1;
+ const started = performance.now();
+ buildTextIndex(scope as unknown as FindElementLike);
+ return performance.now() - started;
+ },
+ };
+ return () => {
+ window.__findSmoke = undefined;
+ };
+ }, [stream]);
+
+ return (
+ <div className="dark flex h-dvh flex-col bg-background text-foreground">
+ <div className="flex shrink-0 items-center gap-3 border-border border-b px-4 py-2 text-sm">
+ <strong>find-in-page smoke</strong>
+ <span className="text-muted-foreground">
+ Press{" "}
+ {navigator.platform.toLowerCase().includes("mac") ? "⌘F" : "Ctrl+F"}{" "}
+ and search for "unsloth"
+ </span>
+ <button
+ type="button"
+ className="rounded-md border border-border px-2 py-1"
+ onClick={() =>
+ stream("A streamed reply mentioning unsloth as it arrives.")
+ }
+ >
+ Stream a reply
+ </button>
+ {/* The app's own popover, which portals to the body and so lands outside the scope. */}
+ <Popover>
+ <PopoverTrigger className="rounded-md border border-border px-2 py-1">
+ Model picker
+ </PopoverTrigger>
+ <PopoverContent data-picker="">
+ <p>unsloth inside a portaled popover</p>
+ </PopoverContent>
+ </Popover>
+ </div>
+ {/* The shell's content region: relative because the bar floats inside it, and the scope. */}
+ {/* `outerScroll` mirrors a non-chat route, where SidebarInset scrolls and the scope is
+ taller than the window. Chat routes are the default: the scope is the fixed-height
+ container and the thread viewport inside it scrolls. */}
+ <div
+ ref={outerScroll ? scrollerRef : undefined}
+ className={
+ outerScroll
+ ? "min-h-0 flex-1 overflow-y-auto"
+ : "flex min-h-0 flex-1 flex-col overflow-hidden"
+ }
+ >
+ <div
+ ref={scopeRef}
+ {...{ [FIND_SCOPE_ATTRIBUTE]: "" }}
+ aria-hidden={modal || undefined}
+ className={
+ outerScroll
+ ? "relative flex flex-col"
+ : "relative flex min-h-0 flex-1 flex-col overflow-hidden"
+ }
+ >
+ {shell ? <FindInPage /> : null}
+ <div
+ ref={outerScroll ? undefined : scrollerRef}
+ className={outerScroll ? "" : "min-h-0 flex-1 overflow-y-auto"}
+ >
+ <OtherWorkspace active={workspace === "other"} />
+ <div
+ hidden={workspace !== "chat"}
+ inert={workspace !== "chat" || undefined}
+ >
+ <Conversation extra={streamed} older={older} />
+ </div>
+ </div>
+ {/* The composer, marked out of the index the way thread.tsx marks the real one. The
+ chord is pressed from here more than anywhere, so closing has to give focus back. */}
+ <form
+ data-find-skip=""
+ className="shrink-0 border-border border-t p-2"
+ >
+ <textarea
+ className="aui-composer-input w-full resize-none bg-transparent text-sm outline-none"
+ placeholder="Message"
+ rows={2}
+ />
+ <span className="text-muted-foreground text-xs">
+ unsloth pill label
+ </span>
+ </form>
+ {/* A workspace parked off-route, as `__root.tsx` parks one. Never counted. */}
+ <div hidden={true} inert={true}>
+ <p>unsloth unsloth unsloth from a workspace nobody is looking at</p>
+ </div>
+ {/* Hidden by a CLASS, not an attribute: the case attributes alone miss. Tailwind's
+ `hidden` is `display: none`, which is what a responsive `hidden lg:flex` resolves to
+ at a breakpoint that is not active. */}
+ <div className="hidden">
+ <p>unsloth from a breakpoint that is not active</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// StrictMode, as main.tsx does it: effects are set up, torn down and set up again on mount in
+// development, which is the only place the focus origin and the observers see that happen.
+createRoot(document.getElementById("root") as HTMLElement).render(
+ <StrictMode>
+ <Harness />
+ </StrictMode>,
+);
diff --git a/studio/frontend/smoke-find-in-page.html b/studio/frontend/smoke-find-in-page.html
new file mode 100644
index 00000000000..9fc5e0f3551
--- /dev/null
+++ b/studio/frontend/smoke-find-in-page.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <title>find in page smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-find-in-page-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 03023d2c216..4bb84e319c1 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -21,6 +21,7 @@ import {
useChatRuntimeStore,
} from "@/features/chat";
import { useExportRuntimeLifecycle } from "@/features/export";
+import { FIND_SCOPE_ATTRIBUTE, FindInPage } from "@/features/find-in-page";
import { HfTokenWarningDialog } from "@/features/hf-auth";
import { bootstrapPersistedCredentials } from "@/features/credentials/bootstrap";
import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";
@@ -548,8 +549,13 @@ function RootLayout() {
>
<Navbar />
<div
+ {...{ [FIND_SCOPE_ATTRIBUTE]: "" }}
className={`relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col ${isChatLike ? "overflow-hidden" : "overflow-visible"} ${isChatLike ? "" : "pt-14 md:pt-[var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))] md:[--studio-titlebar-height:var(--studio-non-chat-content-top-inset,var(--studio-content-top-inset,0px))]"}`}
>
+ {/* The find bar floats over this region and searches it: the workspace on screen,
+ without the sidebar, the navbar, or the off-route workspaces parked here under
+ `inert`. Gated off behind a modal, which owns Escape while it is up. */}
+ <FindInPage enabled={routeShortcutEnabled} />
{/* Stays mounted across navigation so an in-flight generation is
not cancelled when leaving /chat; hidden (not unmounted) off-route.
`active` lets ChatPage close its body-portaled surfaces (model
diff --git a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
index c372a8060e8..2ef11d14e0f 100644
--- a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
@@ -20,6 +20,7 @@ import {
formatMcpToolName,
mcpServerFromProvenance,
} from "@/features/chat";
+import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
import { cn } from "@/lib/utils";
import { useMessage, useMessageTiming } from "@assistant-ui/react";
import { HelpCircleIcon } from "@hugeicons/core-free-icons";
@@ -313,6 +314,11 @@ export const MessageResponseModelBadge: FC<{ className?: string }> = ({
return (
<span
+ // Out of find-in-page's reach: this is a hover affordance, transparent and unclickable until
+ // the message is hovered, so a match here would be counted and walked to under a highlight
+ // nobody can see. The index leaves opacity alone otherwise, so a message still fading in
+ // stays findable.
+ {...{ [FIND_SKIP_ATTRIBUTE]: "" }}
className={cn(
"aui-response-model-badge pointer-events-none relative inline-flex min-h-5 max-w-full cursor-text select-text items-center text-muted-foreground/80 text-xs font-medium leading-5 opacity-0 transition-opacity duration-150 after:absolute after:inset-x-0 after:top-full after:h-1 after:content-[''] hover:opacity-100 group-hover/assistant-message:pointer-events-auto group-hover/assistant-message:opacity-100 group-focus-within/assistant-message:pointer-events-auto group-focus-within/assistant-message:opacity-100",
className,
diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
index d255b84c55a..177616d82f6 100644
--- a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx
@@ -56,7 +56,13 @@ import { useAdjustForContentInsertedAbove } from "@/components/assistant-ui/use-
* imperative DOM readers (screenshot capture, the #9016 harness census) not necessarily in the React
* tree, and a thread can be mounted twice at once (the Compare panes).
*/
-const activeCompleters = new Set<() => Promise<void>>();
+interface ActiveCompleter {
+ complete: () => Promise<void>;
+ /** The scroll viewport these withheld rows belong to, so a caller can ask for only its own. */
+ viewportRef: RefObject<HTMLElement | null>;
+}
+
+const activeCompleters = new Set<ActiveCompleter>();
/**
* Force every in-flight progressive mount to completion, resolving once the commit has painted.
@@ -67,7 +73,18 @@ const activeCompleters = new Set<() => Promise<void>>();
*/
export const PROGRESSIVE_MOUNT_SEARCH_MS = 400;
-export async function completeProgressiveMounts(): Promise<void> {
+export async function completeProgressiveMounts(
+ /**
+ * Force only the threads whose viewport this accepts. Every one of them by default. Find-in-page
+ * passes one: the shell keeps each workspace mounted and marks the off-route ones `inert`, and
+ * mounting a retained conversation's withheld rows serves nobody looking at another route.
+ */
+ wants?: (viewport: HTMLElement | null) => boolean,
+): Promise<void> {
+ const wanted = () =>
+ wants === undefined
+ ? [...activeCompleters]
+ : [...activeCompleters].filter((entry) => wants(entry.viewportRef.current));
// Two waits, failing in opposite directions.
//
// Draining is easy: ask every completer that exists to finish. Reading the set ONCE is not enough,
@@ -84,14 +101,17 @@ export async function completeProgressiveMounts(): Promise<void> {
const deadline = Date.now() + PROGRESSIVE_MOUNT_SEARCH_MS;
let observed = false;
for (;;) {
- if (activeCompleters.size > 0) {
+ const pending = wanted();
+ if (pending.length > 0) {
observed = true;
- await Promise.all([...activeCompleters].map((complete) => complete()));
+ await Promise.all(pending.map((entry) => entry.complete()));
}
await new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
- if (activeCompleters.size === 0 && (observed || Date.now() >= deadline)) {
+ // The filtered set, not the whole one: a completer this caller does not want would otherwise
+ // hold the loop open forever.
+ if (wanted().length === 0 && (observed || Date.now() >= deadline)) {
return;
}
}
@@ -498,11 +518,12 @@ function useProgressiveMountWindow(
completionWaiters.current.push(resolve);
setMountWindow(null);
});
- activeCompleters.add(complete);
+ const entry: ActiveCompleter = { complete, viewportRef };
+ activeCompleters.add(entry);
return () => {
- activeCompleters.delete(complete);
+ activeCompleters.delete(entry);
};
- }, [isWithholding]);
+ }, [isWithholding, viewportRef]);
// Resolve on the commit that actually dropped the window, then after a paint. A bare two-frame
// timer started at the call raced the commit it had just asked for: measured, it resolved with 16
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 889e8aeeb2b..3b55df33214 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -155,6 +155,7 @@ import {
isSurfaceInForeground,
useShortcut,
} from "@/features/settings";
+import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
import { create } from "zustand";
import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabilities";
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
@@ -4847,6 +4848,10 @@ const Composer: FC<{
<PromptQueueContext.Provider value={queueContextValue}>
<ComposerPrimitive.Root
ref={attachComposer}
+ // Out of find-in-page's reach: the draft itself lives in a textarea the index cannot read, so
+ // all this leaves to find are the pill labels, and a search for "code" or "images" would land
+ // on the toolbar instead of on the conversation.
+ {...{ [FIND_SKIP_ATTRIBUTE]: "" }}
className="aui-composer-root relative flex w-full flex-col"
aria-disabled={disabled}
onSubmit={handleSubmit}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
index d7bd53d9ae6..444f309796d 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
@@ -4,11 +4,12 @@
"use client";
import { Button } from "@/components/ui/button";
+import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
import { cn } from "@/lib/utils";
import type { ToolCallMessagePartComponent } from "@assistant-ui/react";
-import { ImageIcon, PencilIcon } from "lucide-react";
import { Download01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { ImageIcon, PencilIcon } from "lucide-react";
import type { CSSProperties, MouseEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { useGeneratedImageOverlay } from "./generated-image-overlay-context";
@@ -357,7 +358,15 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
)}
/>
</button>
- <div className="pointer-events-none absolute inset-x-0 bottom-0 z-20 flex items-end justify-between gap-2 bg-gradient-to-t from-black/55 via-black/20 to-transparent p-3 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/generated-image:opacity-100 sm:group-focus-within/generated-image:opacity-100">
+ <div
+ // Out of find-in-page's reach, like the response model badge: from `sm` up these
+ // actions are transparent until the card is hovered, so "Edit" would be counted and
+ // walked to under a highlight nobody can see. The index leaves opacity alone, since
+ // every user message fades in and reading it would drop one mid-fade. Marked whole
+ // rather than per breakpoint, which costs finding a button label on a phone.
+ {...{ [FIND_SKIP_ATTRIBUTE]: "" }}
+ className="pointer-events-none absolute inset-x-0 bottom-0 z-20 flex items-end justify-between gap-2 bg-gradient-to-t from-black/55 via-black/20 to-transparent p-3 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/generated-image:opacity-100 sm:group-focus-within/generated-image:opacity-100"
+ >
<Button
type="button"
variant="dark"
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 8e396044120..314ba70463e 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -29,6 +29,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";
+import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";
import {
StudioDictationAdapter,
@@ -2181,6 +2182,9 @@ export function SharedComposer({
return (
<div
className="chat-composer-surface"
+ // Compare mode's composer, same as the thread's: find searches the conversation, not the
+ // chrome around it. This one is rendered from `chat-page.tsx`, outside the marked one.
+ {...{ [FIND_SKIP_ATTRIBUTE]: "" }}
onDragOver={(e) => {
if (isTauri || isPortaledDrop(e)) return;
e.preventDefault();
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
new file mode 100644
index 00000000000..2413383d326
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/components/find-in-page.tsx
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import {
+ isImeComposing,
+ isSurfaceBackgrounded,
+ useShortcut,
+} from "@/features/settings";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { Cancel01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+// lucide for the two arrows, which is where #10129 moved every directional arrow in the app: the
+// 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 { useFindInPage } from "../hooks/use-find-in-page.ts";
+import { resolveFindScope, resolvePortalSurfaces } from "../lib/find-dom.ts";
+import { FIND_SCOPE_ATTRIBUTE } from "../lib/find-text-index.ts";
+import { useFindInPageStore } from "../stores/find-in-page-store.ts";
+
+/**
+ * The find bar, and the chord that raises it.
+ *
+ * Split in two: this component is always mounted and holds nothing but the shortcut, while
+ * `FindBar` owns the index, the observer and the highlights and exists only while the bar is open.
+ * A Studio nobody is searching runs one keydown listener and no engine.
+ */
+export function FindInPage({ enabled = true }: { enabled?: boolean }) {
+ const open = useFindInPageStore((state) => state.open);
+ const requestFocus = useFindInPageStore((state) => state.requestFocus);
+ const reset = useFindInPageStore((state) => state.reset);
+
+ // Leaving the shell for good, which on the web means signing out: the store is module-global and
+ // keeps the query across a close, so without this the next person to sign in in the same tab is
+ // handed the last one's search. Unmount, not `enabled`, which a dialog also turns off.
+ useEffect(() => reset, [reset]);
+
+ // Not `skipInTextFields`: the chord has to work from the composer, and pressing it inside the
+ // find field is how a find bar is asked to start over.
+ useShortcut("findInPage", requestFocus, {
+ enabled,
+ // Every modal, not just Settings: Radix marks the shell `aria-hidden`/`inert` while one is up,
+ // so a bar behind it is unreachable. As `claims`, not a return from the handler, which runs
+ // after the event is prevented: declining there would leave the chord dead and native find
+ // suppressed.
+ claims: () => !isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`),
+ });
+
+ if (!enabled || !open) return null;
+ return <FindBar />;
+}
+
+/**
+ * Keep the caret in the field when a walk button is clicked. Without this, one click on the down
+ * arrow and Enter stops working, because the field no longer has the key.
+ */
+function keepFocusInField(event: { preventDefault: () => void }): void {
+ event.preventDefault();
+}
+
+/**
+ * Show the start of the query again once the field loses focus. A query longer than the field
+ * scrolls as it is typed, which is right while typing and wrong once the caret is gone: what is
+ * left is the tail of a word. The caret goes home too, so the scroll does not spring back.
+ */
+function rewindToStart(event: { currentTarget: HTMLInputElement }): void {
+ const input = event.currentTarget;
+ input.setSelectionRange(0, 0);
+ input.scrollLeft = 0;
+}
+
+/**
+ * The walk and close buttons. The ghost variant's `--muted/50` hover resolves to within a shade of
+ * this bar's background, so in dark mode nothing visibly happens; a plain wash reads on either
+ * surface. Same one the outline variant uses.
+ */
+const FIND_BUTTON_CLASS = "size-8 hover:bg-black/[0.06] dark:hover:bg-white/10";
+
+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 inputRef = useRef<HTMLInputElement>(null);
+
+ // 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);
+ const originRef = useRef<HTMLElement | null>(null);
+ useEffect(() => {
+ const active = document.activeElement as HTMLElement | null;
+ // First answer only, and never anything in the bar: StrictMode replays this effect, and by the
+ // second run the field has focus, so the bar would try to hand focus back to its own input.
+ // The bar's own element, not `data-find-skip`, which the composer carries too.
+ if (
+ originRef.current === null &&
+ active !== null &&
+ barRef.current?.contains(active) !== true
+ ) {
+ originRef.current = active;
+ }
+ return () => {
+ const origin = originRef.current;
+ if (!origin?.isConnected || typeof origin.focus !== "function") return;
+ // Only when closing dropped focus on the floor. Anywhere else and the reader moved it.
+ const focused = document.activeElement;
+ if (focused !== null && focused !== document.body) return;
+ origin.focus();
+ };
+ }, []);
+
+ // Escape closes the bar for as long as it is open, wherever focus is.
+ //
+ // On the bar it only reached presses that started inside it, so clicking a message to read it
+ // left the reader with a bar Escape would not close -- and with a tool request waiting, that
+ // same unprevented Escape carried on to `declineToolRequest` (bare Escape, and
+ // `isTextEntryFocused` is false on a message body) and denied the call. Closing a find bar must
+ // not be able to answer a tool request.
+ //
+ // Capture on the window, so it runs before the registry's own keydown listener rather than
+ // racing it, and two things are deliberately left alone: a modal above the bar backgrounds the
+ // scope and owns Escape, and an open popover, menu or listbox is dismissed by its own Escape
+ // first. Composition is left to the IME, as before.
+ useEffect(() => {
+ const onEscape = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || isImeComposing(event)) return;
+ if (isSurfaceBackgrounded(`[${FIND_SCOPE_ATTRIBUTE}]`)) return;
+ if (resolvePortalSurfaces(resolveFindScope()).length > 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ close();
+ };
+ window.addEventListener("keydown", onEscape, true);
+ return () => window.removeEventListener("keydown", onEscape, true);
+ }, [close]);
+
+ // 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.
+ useEffect(() => {
+ const input = inputRef.current;
+ if (!input) return;
+ input.focus();
+ input.select();
+ }, [focusToken]);
+
+ const searching = query.length > 0;
+ const empty = searching && count === 0;
+ const counter = searching
+ ? `${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=""
+ 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"
+ >
+ <input
+ ref={inputRef}
+ type="text"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ // The Enter committing an IME candidate arrives here too; taken, it walks to the next
+ // match and throws away the word.
+ if (isImeComposing(event.nativeEvent)) return;
+ event.preventDefault();
+ if (event.shiftKey) previous();
+ else next();
+ }
+ }}
+ onBlur={rewindToStart}
+ // The same string the landmark is labelled with: one phrase, one key to translate.
+ placeholder={t("shell.find.label")}
+ aria-label={t("shell.find.label")}
+ spellCheck={false}
+ autoComplete="off"
+ autoCorrect="off"
+ className={cn(
+ // 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",
+ empty && "text-destructive",
+ )}
+ />
+ <span
+ aria-live="polite"
+ title={truncated ? t("shell.find.truncated") : undefined}
+ className={cn(
+ "min-w-12 shrink-0 pr-3 text-right text-muted-foreground text-sm tabular-nums",
+ truncated && "cursor-help underline decoration-dotted",
+ )}
+ >
+ {counter}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className={FIND_BUTTON_CLASS}
+ disabled={count === 0}
+ onMouseDown={keepFocusInField}
+ onClick={previous}
+ aria-label={t("shell.find.previous")}
+ title={t("shell.find.previous")}
+ >
+ <ArrowUpIcon strokeWidth={1.75} className="size-[18px]" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className={FIND_BUTTON_CLASS}
+ disabled={count === 0}
+ onMouseDown={keepFocusInField}
+ onClick={next}
+ aria-label={t("shell.find.next")}
+ title={t("shell.find.next")}
+ >
+ <ArrowDownIcon strokeWidth={1.75} className="size-[18px]" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className={FIND_BUTTON_CLASS}
+ onClick={close}
+ aria-label={t("shell.find.close")}
+ title={t("shell.find.close")}
+ >
+ <HugeiconsIcon icon={Cancel01Icon} className="size-[18px]" />
+ </Button>
+ </div>
+ );
+}
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
new file mode 100644
index 00000000000..70eb5fff6a3
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts
@@ -0,0 +1,385 @@
+// 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.
+
+import { completeProgressiveMounts } from "@/components/assistant-ui/progressive-messages";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ cancelRevealPasses,
+ clearHighlights,
+ indexReaches,
+ mutatesSearchableText,
+ paintHighlights,
+ paintWindow,
+ rangeForMatch,
+ rangeTop,
+ resolveFindScope,
+ resolvePortalSurfaces,
+ revealRangeWhenPainted,
+ scrollViewportTop,
+ selectRangeFallback,
+ supportsHighlightApi,
+ viewportOffset,
+} from "../lib/find-dom.ts";
+import {
+ EMPTY_TEXT_INDEX,
+ FIND_SKIP_ATTRIBUTE,
+ type FindElementLike,
+ type FindMatch,
+ type FindTextIndex,
+ MAX_MATCHES,
+ buildTextIndex,
+ dropProbeFurthestFrom,
+ findMatches,
+} from "../lib/find-text-index.ts";
+
+/**
+ * Shortest gap between two rebuilds while the document is changing.
+ *
+ * A throttle rather than a debounce: a reply streams for as long as it takes to write, and a
+ * debounce would leave the count frozen and the new text unfindable for that whole time. This
+ * bounds the cost instead, at one flatten per interval however fast the tokens arrive.
+ */
+export const REINDEX_INTERVAL_MS = 300;
+
+export interface FindResults {
+ /** Matches for the current query, capped at `MAX_MATCHES`. */
+ count: number;
+ /** Zero-based position in `count`, or -1 when nothing matches. */
+ active: number;
+ /** True when the cap actually cut something off, so `count` is a floor rather than the total. */
+ capped: boolean;
+ /** True when the document was too large to flatten in full. */
+ truncated: boolean;
+ next: () => void;
+ previous: () => void;
+}
+
+/**
+ * The first match at or below the top of the viewport, so a fresh query starts where the reader is
+ * rather than at the top of the conversation.
+ *
+ * Binary search, not a scan: matches come out in document order, so their rects are ordered too.
+ * Absolutely positioned content can break that; being one match out is the whole cost.
+ */
+function firstMatchFromViewport(
+ index: FindTextIndex,
+ matches: FindMatch[],
+): number {
+ if (matches.length === 0) return -1;
+ let lo = 0;
+ let hi = matches.length - 1;
+ let found = -1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const range = rangeForMatch(index, matches[mid]);
+ if (!range) return 0;
+ const top = rangeTop(range);
+ if (top === null) return 0;
+ if (top >= scrollViewportTop(range)) {
+ found = mid;
+ hi = mid - 1;
+ } else {
+ lo = mid + 1;
+ }
+ }
+ // Everything is above the fold: wrap to the first match.
+ return found === -1 ? 0 : found;
+}
+
+/** The ordinal of the match starting at `start`, or -1. Sorted by `start`, so a binary search. */
+function ordinalOfStart(matches: FindMatch[], start: number): number {
+ let lo = 0;
+ let hi = matches.length - 1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const at = matches[mid].start;
+ if (at === start) return mid;
+ if (at < start) lo = mid + 1;
+ else hi = mid - 1;
+ }
+ return -1;
+}
+
+export function useFindInPage(query: string): FindResults {
+ const [results, setResults] = useState<{
+ count: number;
+ active: number;
+ capped: boolean;
+ truncated: boolean;
+ }>({ count: 0, active: -1, capped: false, truncated: false });
+
+ const scopeRef = useRef<Element | null>(null);
+ const indexRef = useRef<FindTextIndex>(EMPTY_TEXT_INDEX);
+ const matchesRef = useRef<FindMatch[]>([]);
+ /**
+ * Where the active match sits in the document, so it can be found again after a rebuild.
+ *
+ * The ordinal only means something inside one match list, and the list is not stable even when
+ * the document merely grows: past the cap the kept window recentres as matches are appended, so
+ * the same number is a different occurrence. This is the occurrence itself.
+ */
+ const activeStartRef = useRef<number | null>(null);
+ /** Whether the cap cut the last search short. */
+ const cappedRef = useRef(false);
+ const activeRef = useRef(-1);
+ const queryRef = useRef(query);
+ /** The document changed since the index was built. */
+ const staleRef = useRef(false);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ /** 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) => {
+ const index = indexRef.current;
+ const matches = matchesRef.current;
+ const count = matches.length;
+ let active = activeRef.current;
+ if (count === 0) active = -1;
+ else if (active < 0) active = 0;
+ else if (active >= count) active = count - 1;
+ activeRef.current = active;
+
+ const activeRange =
+ active >= 0 ? rangeForMatch(index, matches[active]) : null;
+
+ if (supportsHighlightApi()) {
+ const window_ = paintWindow(count, Math.max(active, 0));
+ const ranges: Range[] = [];
+ for (let i = window_.from; i < window_.to; i += 1) {
+ const range =
+ i === active ? activeRange : rangeForMatch(index, matches[i]);
+ if (range) ranges.push(range);
+ }
+ paintHighlights(ranges, activeRange);
+ } else {
+ selectRangeFallback(activeRange);
+ }
+
+ if (reveal && activeRange) revealRangeWhenPainted(activeRange);
+
+ activeStartRef.current = active >= 0 ? matches[active].start : null;
+
+ const capped = cappedRef.current;
+ setResults((previous) =>
+ previous.count === count &&
+ previous.active === active &&
+ previous.capped === capped &&
+ previous.truncated === index.truncated
+ ? previous
+ : { count, active, capped, truncated: index.truncated },
+ );
+ }, []);
+
+ /** Re-run the query against the index already in hand. */
+ const search = useCallback(
+ (reveal: boolean, fromViewport: boolean) => {
+ const index = indexRef.current;
+ // One past the cap: a count equal to the cap cannot say whether it is the total or a floor,
+ // and the counter would read "5000+" for a page holding exactly 5000. Only its existence is
+ // kept.
+ //
+ // The anchor decides WHICH matches survive the cap, keeping the ones nearest the reader. It
+ // is a thunk because `viewportOffset` reads layout and an argument is evaluated whether or
+ // not the callee wants it, so inline it ran on every keystroke however few matches there
+ // were.
+ //
+ // Remembered as the thunk resolves it, so the trim below can ask where the reader was
+ // without a second layout read, and without one at all under the cap.
+ let anchoredAt: number | null = null;
+ const matches = findMatches(
+ index,
+ queryRef.current,
+ MAX_MATCHES + 1,
+ () => {
+ anchoredAt = viewportOffset(index);
+ return anchoredAt;
+ },
+ );
+ cappedRef.current = matches.length > MAX_MATCHES;
+ if (cappedRef.current) dropProbeFurthestFrom(matches, anchoredAt);
+ // Read before `apply` writes it: this is where the last list left the reader.
+ const wasAt = activeStartRef.current;
+ matchesRef.current = matches;
+ if (fromViewport) {
+ activeRef.current = firstMatchFromViewport(index, matches);
+ } else {
+ // Same occurrence, not same number. Offsets are comparable here only because the caller has
+ // established that the document merely grew at the tail; the number never was, since a
+ // capped window slides along as matches arrive.
+ const at = wasAt === null ? -1 : ordinalOfStart(matches, wasAt);
+ activeRef.current =
+ at === -1 ? firstMatchFromViewport(index, matches) : at;
+ }
+ apply(reveal);
+ },
+ [apply],
+ );
+
+ /**
+ * Flatten the document again. True when the result RENUMBERS the match list, which is anything
+ * but a pure append at the tail.
+ *
+ * That one test settles who keeps their place. A streaming reply only ever adds to the end, so
+ * match 20 is still match 20 and the ordinal is worth keeping. History arriving above, a
+ * workspace switch flipping `inert`, a breakpoint revealing a column: each renumbers everything
+ * after it, and the reader's number then points at unrelated text, usually off screen. Those
+ * re-anchor to the viewport. An unchanged document is a pure append of nothing, so a rebuild that
+ * finds no news leaves the reader exactly where they were.
+ */
+ const reindex = useCallback((): boolean => {
+ staleRef.current = false;
+ const before = indexRef.current.text;
+ const scope = scopeRef.current;
+ indexRef.current = scope
+ ? buildTextIndex(
+ scope as unknown as FindElementLike,
+ // Resolved every time: a popover opens and closes under an open bar, and its list is on
+ // screen in front of the workspace while it is up.
+ resolvePortalSurfaces(scope) as unknown as FindElementLike[],
+ )
+ : EMPTY_TEXT_INDEX;
+ return !indexRef.current.text.startsWith(before);
+ }, []);
+
+ // Open: take the index and watch for changes. Closing tears all of it down, highlights included.
+ useEffect(() => {
+ const scope = resolveFindScope();
+ scopeRef.current = scope;
+ reindex();
+ // A fresh open always starts from the reader, whatever the index says.
+ search(false, true);
+
+ // The thread mounts its tail first and widens over the next few frames, so a search against
+ // the document as found would miss everything above the fold. The bar stays usable throughout.
+ //
+ // Only the threads this search can read: asking globally would make an off-route conversation
+ // mount every row it withheld, to be skipped by the very walk that asked for it.
+ let live = true;
+ void completeProgressiveMounts((viewport) =>
+ indexReaches(scope, viewport),
+ ).then(() => {
+ if (!live) return;
+ // Completion PREPENDS, so it renumbers and the walk re-anchors. On a settled thread it
+ // brings in nothing, and the reader may have pressed Enter while it ran: an unconditional
+ // re-anchor would take that back.
+ search(false, reindex());
+ });
+
+ // Mark the index stale and schedule one rebuild. No reveal: something moved under the reader,
+ // they did not ask to go anywhere.
+ const invalidate = () => {
+ staleRef.current = true;
+ // Nothing to re-run against an empty query, so streaming into an unused bar only sets a flag.
+ if (queryRef.current.length === 0) return;
+ // Already scheduled: the interval is the floor, so a burst costs one rebuild, not one each.
+ if (timerRef.current !== null) return;
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ if (!staleRef.current) return;
+ search(false, reindex());
+ }, REINDEX_INTERVAL_MS);
+ };
+
+ // A media query is not a mutation: crossing a breakpoint hides or reveals whole columns with
+ // nothing in the DOM to observe, so without this the bar searches the layout that has gone.
+ window.addEventListener("resize", invalidate);
+
+ // And a container query does not even need the window to change. Images is an `@container` with
+ // labels on `@[50rem]`, so pinning or collapsing the sidebar crosses that breakpoint on its own.
+ // Watching the scope catches it: the same thing that resizes the container resizes this.
+ let sized: ResizeObserver | null = null;
+ if (scope && typeof ResizeObserver !== "undefined") {
+ // Delivered once on observe, for the size it already had. That one is not news.
+ let measured = false;
+ sized = new ResizeObserver(() => {
+ if (!measured) {
+ measured = true;
+ return;
+ }
+ invalidate();
+ });
+ sized.observe(scope);
+ }
+
+ // The body, not the scope: a portaled surface is a sibling of the shell, so a popover opening
+ // is not a mutation of the region it floats over. The wider net still costs at most one flatten
+ // per interval.
+ const watched = scope?.ownerDocument?.body ?? scope;
+ let observer: MutationObserver | null = null;
+ if (watched && typeof MutationObserver !== "undefined") {
+ observer = new MutationObserver((records) => {
+ // The bar floats inside the region it searches, so its own counter re-rendering is a
+ // mutation of the scope. Without this it re-indexes every time the match count changes.
+ if (!records.some(mutatesSearchableText)) return;
+ invalidate();
+ });
+ observer.observe(watched, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ // Switching workspaces adds and removes nothing: it flips `inert` on one panel and off the
+ // other. A filter, not `attributes: true`, because `class` changes on every hover.
+ attributes: true,
+ // `open` toggles a `<details>` and nothing else while its body goes from visible to not, so
+ // a Hub README collapsible opened after indexing would stay unfindable. `data-state` is how
+ // a popover, menu or accordion says it is closing, keeping its box until the animation
+ // ends.
+ attributeFilter: [
+ "inert",
+ "hidden",
+ "aria-hidden",
+ "open",
+ "data-state",
+ FIND_SKIP_ATTRIBUTE,
+ ],
+ });
+ }
+
+ return () => {
+ live = false;
+ // The bar is going away; any queued reveal would scroll the reader after it is gone.
+ cancelRevealPasses();
+ window.removeEventListener("resize", invalidate);
+ sized?.disconnect();
+ observer?.disconnect();
+ if (timerRef.current !== null) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ clearHighlights();
+ if (!supportsHighlightApi()) selectRangeFallback(null);
+ indexRef.current = EMPTY_TEXT_INDEX;
+ matchesRef.current = [];
+ };
+ }, [reindex, search]);
+
+ // A new query starts from the reader's position, re-indexing first if the document moved on.
+ useEffect(() => {
+ queryRef.current = query;
+ if (staleRef.current) reindex();
+ search(true, true);
+ }, [query, reindex, search]);
+
+ const step = useCallback(
+ (delta: number) => {
+ const count = matchesRef.current.length;
+ if (count === 0) return;
+ // Wraps, so the walk never dead-ends.
+ activeRef.current = (activeRef.current + delta + count) % count;
+ apply(true);
+ },
+ [apply],
+ );
+
+ const next = useCallback(() => step(1), [step]);
+ const previous = useCallback(() => step(-1), [step]);
+
+ return { ...results, next, previous };
+}
diff --git a/studio/frontend/src/features/find-in-page/index.ts b/studio/frontend/src/features/find-in-page/index.ts
new file mode 100644
index 00000000000..9eed763f062
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/index.ts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export { FindInPage } from "./components/find-in-page.tsx";
+export { useFindInPageStore } from "./stores/find-in-page-store.ts";
+export {
+ FIND_SCOPE_ATTRIBUTE,
+ FIND_SKIP_ATTRIBUTE,
+} from "./lib/find-attributes.ts";
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
new file mode 100644
index 00000000000..61e8c39313f
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/lib/find-attributes.ts
@@ -0,0 +1,11 @@
+// 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.
+
+/** Marks a subtree the bar must not read: the bar itself, first of all. */
+export const FIND_SKIP_ATTRIBUTE = "data-find-skip";
+
+/** 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
new file mode 100644
index 00000000000..d28c44c47be
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/lib/find-dom.ts
@@ -0,0 +1,501 @@
+// 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 DOM half of find-in-page: offsets back into `Range`s, painting them, and moving the reader
+// to one. The arithmetic and the flatten live in find-text-index.ts, which is pure.
+
+import {
+ FIND_SCOPE_ATTRIBUTE,
+ FIND_SKIP_ATTRIBUTE,
+ type FindMatch,
+ type FindTextIndex,
+ endPositionAt,
+ startPositionAt,
+} from "./find-text-index.ts";
+
+/**
+ * Registry names for the two highlights: every match with the first, the active one on top.
+ *
+ * The Custom Highlight API keeps highlighting off the document: a `Highlight` is a set of `Range`s
+ * painted over text already laid out, so nothing is inserted and nothing reflows. `<mark>` would
+ * mutate the thread on every keystroke, splitting nodes that streaming markdown, `thread-fast-copy`
+ * and the export path read back.
+ */
+export const FIND_HIGHLIGHT = "unsloth-find";
+export const FIND_HIGHLIGHT_ACTIVE = "unsloth-find-active";
+
+/** How many matches are painted at once. The window travels with the active match, so what is on
+ * screen is always painted; the rest are counted and reachable, just not tinted. */
+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 HighlightConstructor = new (...ranges: Range[]) => HighlightLike;
+type HighlightRegistry = {
+ set(name: string, highlight: HighlightLike): void;
+ delete(name: string): void;
+};
+
+/** The registry and constructor, or null on an engine without them. Read through `globalThis`
+ * because the app's `lib` is ES2022 + DOM, which has no `Highlight`. WebKitGTK lands here, and
+ * `selectRangeFallback` covers it. */
+function highlightApi(): {
+ registry: HighlightRegistry;
+ Highlight: HighlightConstructor;
+} | null {
+ const scope = globalThis as {
+ CSS?: { highlights?: HighlightRegistry };
+ Highlight?: HighlightConstructor;
+ };
+ const registry = scope.CSS?.highlights;
+ const Highlight = scope.Highlight;
+ if (!registry || typeof Highlight !== "function") return null;
+ return { registry, Highlight };
+}
+
+/** True when this engine can paint highlights without touching the document. */
+export function supportsHighlightApi(): boolean {
+ return highlightApi() !== null;
+}
+
+/** The subtree the bar searches: the shell's content region, which leaves out the sidebar and the
+ * bar itself. `document.body` is the fallback for a route that renders no shell. */
+export function resolveFindScope(): Element | null {
+ if (typeof document === "undefined") return null;
+ return (
+ document.querySelector(`[${FIND_SCOPE_ATTRIBUTE}]`) ?? document.body ?? 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 =
+ '[data-slot="popover-content"], [role="menu"], [role="listbox"]';
+
+export function resolvePortalSurfaces(scope: Element | null): Element[] {
+ if (typeof document === "undefined" || scope === null) return [];
+ const found: Element[] = [];
+ for (const element of document.querySelectorAll(PORTAL_SURFACE_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.
+ if (element.getAttribute("data-state") === "closed") continue;
+ found.push(element);
+ }
+ return found;
+}
+
+/**
+ * The index offset nearest the top of the reader's viewport, or 0 when nothing can be measured.
+ *
+ * Binary search over the segments: a dozen or so rect reads whatever the document's size. Only
+ * asked when a query is common enough to hit the match cap, which is what needs to know where the
+ * reader is.
+ */
+export function viewportOffset(index: FindTextIndex): number {
+ const segments = index.segments;
+ if (segments.length === 0) return 0;
+ let lo = 0;
+ let hi = segments.length - 1;
+ let found = -1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const segment = segments[mid];
+ const range = rangeForMatch(index, {
+ start: segment.start,
+ end: segment.start + 1,
+ });
+ if (!range) return 0;
+ const top = rangeTop(range);
+ if (top === null) return 0;
+ if (top >= scrollViewportTop(range)) {
+ found = mid;
+ hi = mid - 1;
+ } else {
+ lo = mid + 1;
+ }
+ }
+ // Everything is above the fold, so the reader is at the end of it.
+ return found === -1 ? index.text.length : segments[found].start;
+}
+
+/**
+ * What the walk turns back at, as a selector.
+ *
+ * The shell keeps every workspace mounted and parks off-route ones under `hidden` and `inert` so a
+ * long generation survives navigation, and Radix marks the page `aria-hidden` behind a modal. Being
+ * 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}]`;
+
+/** What the walk will actually read, asked of one element: inside the scope, and under nothing the
+ * walk turns back at. */
+export function indexReaches(
+ scope: Element | null,
+ element: Element | null,
+): boolean {
+ if (scope === null || element === null) return false;
+ if (!scope.contains(element)) return false;
+ 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`.
+ */
+export function mutatesSearchableText(record: {
+ target: { nodeType: number; parentElement: Element | null };
+ type: string;
+ attributeName: string | null;
+}): boolean {
+ const target = record.target;
+ const element =
+ target.nodeType === 1
+ ? (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.
+ 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.
+ return from.closest(SKIPPED_REGION_SELECTOR) === null;
+}
+
+/**
+ * A live `Range` over one match, or null when the index has drifted from the document.
+ *
+ * Drift is expected, not exceptional: a streaming reply rewrites text nodes under the index. A
+ * stale offset past the end of a shortened node throws, so a null drops that match until the next
+ * rebuild.
+ */
+export function rangeForMatch(
+ index: FindTextIndex,
+ match: FindMatch,
+): Range | null {
+ const start = startPositionAt(index.segments, match.start);
+ const end = endPositionAt(index.segments, match.end);
+ if (!start || !end) return null;
+ try {
+ const range = document.createRange();
+ range.setStart(start.node as unknown as Node, start.offset);
+ range.setEnd(end.node as unknown as Node, end.offset);
+ return range;
+ } catch {
+ return null;
+ }
+}
+
+/** The slice of `matches` to paint, centred on `active`. Pure so the window can be tested without
+ * a document: the active match is always inside it, and it is never wider than the cap. */
+export function paintWindow(
+ total: number,
+ active: number,
+ cap = MAX_PAINTED_RANGES,
+): { from: number; to: number } {
+ if (total <= cap) return { from: 0, to: total };
+ const half = Math.floor(cap / 2);
+ const from = Math.min(Math.max(0, active - half), total - cap);
+ return { from, to: from + cap };
+}
+
+/** 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(
+ ranges: Range[],
+ activeRange: Range | null,
+): void {
+ const api = highlightApi();
+ if (!api) return;
+ const { registry, Highlight } = api;
+ if (ranges.length === 0) {
+ registry.delete(FIND_HIGHLIGHT);
+ } else {
+ registry.set(FIND_HIGHLIGHT, new Highlight(...ranges));
+ }
+ if (!activeRange) {
+ registry.delete(FIND_HIGHLIGHT_ACTIVE);
+ return;
+ }
+ 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;
+ registry.set(FIND_HIGHLIGHT_ACTIVE, active);
+}
+
+/** Take both highlights back down. Safe to call on an engine that never had them. */
+export function clearHighlights(): void {
+ const api = highlightApi();
+ if (!api) return;
+ api.registry.delete(FIND_HIGHLIGHT);
+ api.registry.delete(FIND_HIGHLIGHT_ACTIVE);
+}
+
+/** The caret inside a focused text field, so moving the document selection can give it back. */
+type CaretHold = {
+ field: HTMLInputElement | HTMLTextAreaElement;
+ start: number | null;
+ end: number | null;
+};
+
+/**
+ * The find field's caret, captured before the selection is moved out from under it.
+ *
+ * On WebKit and Blink, moving the selection into ordinary text while a field is focused takes the
+ * caret with it: `activeElement` still reports the field, but every keystroke is swallowed, so the
+ * query freezes at one character. Gecko keeps the two apart. WebKit is the case that matters: an
+ * engine with no highlight registry is Firefox below 140 or the desktop build's WebKitGTK.
+ */
+function holdCaret(): CaretHold | null {
+ // Through `globalThis`: the node suite drives this with a hand-rolled window, no document and
+ // none of the constructors below.
+ const scope = globalThis as {
+ document?: { activeElement?: unknown };
+ HTMLInputElement?: unknown;
+ HTMLTextAreaElement?: unknown;
+ };
+ const active = scope.document?.activeElement;
+ if (
+ typeof scope.HTMLInputElement !== "function" ||
+ typeof scope.HTMLTextAreaElement !== "function"
+ ) {
+ return null;
+ }
+ if (
+ active instanceof HTMLInputElement ||
+ active instanceof HTMLTextAreaElement
+ ) {
+ return {
+ field: active,
+ start: active.selectionStart,
+ end: active.selectionEnd,
+ };
+ }
+ return null;
+}
+
+/** Put the caret back where it was, so the next keystroke reaches the field. */
+function releaseCaret(held: CaretHold | null): void {
+ if (!held) return;
+ const { field, start, end } = held;
+ field.focus({ preventScroll: true });
+ if (start === null || end === null) return;
+ try {
+ field.setSelectionRange(start, end);
+ } catch {
+ // Some input types refuse a range. Focus is the half that matters.
+ }
+}
+
+/**
+ * Show the active match by selecting it, for an engine with no highlight registry, which is what a
+ * browser's own find does. A selection is one range, so there the bar counts every match and tints
+ * one.
+ *
+ * The caret is handed back afterwards, which keeps the field typable. Whether the selection
+ * survives is the engine's call: Gecko keeps both, WebKit and Blink drop it. Losing the tint is a
+ * worse look; losing the field is a broken feature.
+ */
+export function selectRangeFallback(range: Range | null): void {
+ if (typeof window === "undefined") return;
+ const selection = window.getSelection();
+ if (!selection) return;
+ if (range === null) {
+ // Only clear the selection this put there, and only while it is still the one on screen:
+ // opening paints before a query is typed, and dragging replaces the match, and neither has a
+ // way back.
+ const owned = ownedSelection;
+ ownedSelection = null;
+ if (owned === null || !sameBoundaries(owned, currentRange(selection)))
+ return;
+ selection.removeAllRanges();
+ return;
+ }
+ const held = holdCaret();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ ownedSelection = currentRange(selection) ?? range;
+ releaseCaret(held);
+}
+
+/** The range this put on screen, or null when the selection is the reader's own. */
+let ownedSelection: Range | null = null;
+
+function currentRange(selection: Selection): Range | null {
+ return selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
+}
+
+/** Boundary points, not identity: engines differ on whether `getRangeAt` hands back what was added. */
+function sameBoundaries(a: Range, b: Range | null): boolean {
+ return (
+ b !== null &&
+ a.startContainer === b.startContainer &&
+ a.startOffset === b.startOffset &&
+ a.endContainer === b.endContainer &&
+ a.endOffset === b.endOffset
+ );
+}
+
+/** True when this element scrolls its own overflow on the given axis. */
+function scrollsAxis(element: Element, axis: "x" | "y"): boolean {
+ const overflowing =
+ axis === "y"
+ ? element.scrollHeight > element.clientHeight + 1
+ : element.scrollWidth > element.clientWidth + 1;
+ if (!overflowing) return false;
+ const style = getComputedStyle(element);
+ const overflow = axis === "y" ? style.overflowY : style.overflowX;
+ return overflow === "auto" || overflow === "scroll" || overflow === "overlay";
+}
+
+/** Scroll one container so `rect` sits comfortably inside it, or leave it alone when it already
+ * does: a match on screen must not move the page, or stepping through one paragraph would jerk
+ * the conversation on every press. */
+function revealWithin(scroller: Element, rect: DOMRect): boolean {
+ const view = scroller.getBoundingClientRect();
+ let top = scroller.scrollTop;
+ let left = scroller.scrollLeft;
+ let moved = false;
+
+ if (scrollsAxis(scroller, "y")) {
+ const overTop = rect.top - (view.top + REVEAL_INSET_PX);
+ const overBottom = rect.bottom - (view.bottom - REVEAL_INSET_PX);
+ if (overTop < 0 || overBottom > 0) {
+ top += rect.top - view.top - Math.max(0, (view.height - rect.height) / 2);
+ moved = true;
+ }
+ }
+ if (scrollsAxis(scroller, "x")) {
+ const overLeft = rect.left - (view.left + REVEAL_INSET_PX);
+ const overRight = rect.right - (view.right - REVEAL_INSET_PX);
+ if (overLeft < 0 || overRight > 0) {
+ left +=
+ rect.left - view.left - Math.max(0, (view.width - rect.width) / 2);
+ moved = true;
+ }
+ }
+ if (!moved) return false;
+ // `instant`, not the viewport's own `scroll-smooth`: holding Enter outruns a smooth scroll.
+ scroller.scrollTo({ top, left, behavior: "instant" });
+ return true;
+}
+
+/** The element a range starts in, which is where both walks below begin. */
+function elementFor(range: Range): Element | null {
+ const start = range.startContainer;
+ return start.nodeType === 1
+ ? (start as Element)
+ : (start.parentElement ?? null);
+}
+
+/**
+ * A rect to aim at for `range`, or null when nothing about it is laid out.
+ *
+ * A skipped `content-visibility: auto` subtree gives a range inside it a collapsed rect at the
+ * origin, while the subtree's own box keeps its placeholder geometry. Aiming at the nearest laid
+ * out ancestor gets the reader there, and the subtree renders on the way.
+ */
+export function revealRect(range: Range): DOMRect | null {
+ const rect = range.getBoundingClientRect();
+ if (rect.width !== 0 || rect.height !== 0) return rect;
+ let element = elementFor(range);
+ while (element) {
+ const box = element.getBoundingClientRect();
+ if (box.width !== 0 || box.height !== 0) return box;
+ element = element.parentElement;
+ }
+ return null;
+}
+
+/** Where `range` sits vertically, through the same fallback. */
+export function rangeTop(range: Range): number | null {
+ return revealRect(range)?.top ?? null;
+}
+
+/** The top edge of the scroll container `range` sits in, in window coordinates. Not zero: the
+ * thread viewport starts below the navbar and header, so a match clipped just off its top still
+ * has a positive `top`, and treating that as visible sends a query backwards out of sight. */
+export function scrollViewportTop(range: Range): number {
+ let element = elementFor(range);
+ while (element) {
+ if (scrollsAxis(element, "y")) return element.getBoundingClientRect().top;
+ element = element.parentElement;
+ }
+ return 0;
+}
+
+/** Bring `range` into view, innermost scroller first. Nested scrollers are real (a wide code fence
+ * in the thread viewport), so the rect is re-read after each. The window is never scrolled: the
+ * shell is a fixed-height `100dvh` grid with `overflow-hidden`. */
+export function scrollRangeIntoView(range: Range): boolean {
+ let element = elementFor(range);
+ let moved = false;
+ // Bounded by DOM depth, and each step is one rect read plus at most one scroll write.
+ while (element) {
+ if (scrollsAxis(element, "y") || scrollsAxis(element, "x")) {
+ // Re-read each time: scrolling the inner container decides what the outer one still owes.
+ const rect = revealRect(range);
+ if (!rect) return moved;
+ if (revealWithin(element, rect)) moved = true;
+ }
+ element = element.parentElement;
+ }
+ return moved;
+}
+
+/**
+ * Bring `range` into view, and again for as long as the view keeps moving.
+ *
+ * A scroll reaches only the scrollHeight the engine knows, and a `content-visibility: auto` subtree
+ * contributes its placeholder until it renders: a Hub README block can stand at 140px for a 2904px
+ * reality. Reaching toward it is what makes it render, so the next frame has more to scroll and the
+ * match has moved. Without this the reader was left 3415px below an 800px viewport on all three
+ * engines. Typing hides it, since every keystroke reveals again; one reveal from a paste or an
+ * Enter stays wrong.
+ *
+ * "Still moving" rather than asking whether the subtree was skipped, because the engines that most
+ * need this are the ones that do not answer `checkVisibility`. Ends when a pass moves nothing: 2
+ * frames on webkit, 3 on chromium and firefox. The bound stops anything spinning.
+ */
+export function revealRangeWhenPainted(range: Range, tries = 8): void {
+ cancelRevealPasses();
+ revealPass(range, tries, revealGeneration);
+}
+
+/** The chain in flight. A new reveal or a closing bar supersedes the last one. */
+let revealGeneration = 0;
+
+/** Abandon any queued reveal. The workspace stays mounted after the bar closes, so `isConnected`
+ * alone would let the old chain keep scrolling the reader toward a match nobody asked for. */
+export function cancelRevealPasses(): void {
+ revealGeneration += 1;
+}
+
+function revealPass(range: Range, tries: number, generation: number): void {
+ if (!scrollRangeIntoView(range) || tries <= 1) return;
+ if (typeof requestAnimationFrame !== "function") return;
+ requestAnimationFrame(() => {
+ if (generation !== revealGeneration) return;
+ // A streaming reply rewrites the nodes under the index, so the range can be gone by now.
+ if (!range.startContainer.isConnected) return;
+ revealPass(range, tries - 1, generation);
+ });
+}
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
new file mode 100644
index 00000000000..b24028bd73e
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/lib/find-text-index.ts
@@ -0,0 +1,805 @@
+// 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.
+
+import { FIND_SKIP_ATTRIBUTE } from "./find-attributes.ts";
+
+/** `Node.ELEMENT_NODE` / `Node.TEXT_NODE`, spelled out so this module needs no DOM globals. */
+export const ELEMENT_NODE = 1;
+export const TEXT_NODE = 3;
+
+/** Written at block boundaries so a match cannot run from one paragraph into the next. NUL because
+ * no query can contain it, and `findMatches` rejects the one route that could (a paste). */
+export const BLOCK_SEPARATOR = "\u0000";
+
+/** Ceiling on the flattened text. A thread is bounded by what a person scrolled through, a tool
+ * result is not: a Bash step can paste a megabyte of build log in. Scanning 4M costs about 2ms. */
+export const MAX_INDEX_CHARS = 4_000_000;
+
+/** Ceiling on matches for one query. Every match is a `Range` the highlight registry has to paint,
+ * and a single letter in a long thread has thousands. */
+export const MAX_MATCHES = 5_000;
+
+/** Ceiling on what ONE text node may contribute. A Bash step's log arrives as a single text node,
+ * and left to itself it spends the whole budget on the top of the document, so the messages the
+ * 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.
+ */
+export const PORTAL_RESERVE_CHARS = 100_000;
+
+/** Elements whose subtree holds no findable text. Form controls carry theirs in `value`; a `Range`
+ * over `SVG` or `CANVAS` content is not paintable on every engine. */
+const SKIP_TAGS: ReadonlySet<string> = new Set([
+ "SCRIPT",
+ "STYLE",
+ "NOSCRIPT",
+ "TEMPLATE",
+ "INPUT",
+ "TEXTAREA",
+ "SELECT",
+ "OPTION",
+ "SVG",
+ "CANVAS",
+ "VIDEO",
+ "AUDIO",
+ "IFRAME",
+ "OBJECT",
+ "EMBED",
+]);
+
+/** Elements that end the line they sit on, so a separator goes in either side of them. A tag set,
+ * not `getComputedStyle`: this runs on every element in the thread. Being wrong about an exotic
+ * one inserts a break that was not needed, never invents a match. */
+const BLOCK_TAGS: ReadonlySet<string> = new Set([
+ "ADDRESS",
+ "ARTICLE",
+ "ASIDE",
+ "BLOCKQUOTE",
+ "BR",
+ "BUTTON",
+ "DD",
+ "DETAILS",
+ "DIALOG",
+ "DIV",
+ "DL",
+ "DT",
+ "FIELDSET",
+ "FIGCAPTION",
+ "FIGURE",
+ "FOOTER",
+ "FORM",
+ "H1",
+ "H2",
+ "H3",
+ "H4",
+ "H5",
+ "H6",
+ "HEADER",
+ "HR",
+ "LI",
+ "MAIN",
+ "NAV",
+ "OL",
+ "P",
+ "PRE",
+ "SECTION",
+ "SUMMARY",
+ "TABLE",
+ "TBODY",
+ "TD",
+ "TFOOT",
+ "TH",
+ "THEAD",
+ "TR",
+ "UL",
+]);
+
+// Re-exported so this module stays the one import for everything about the index.
+export {
+ FIND_SCOPE_ATTRIBUTE,
+ FIND_SKIP_ATTRIBUTE,
+} from "./find-attributes.ts";
+
+/** Spaces that render as a space but are not one. Each is one UTF-16 unit, which keeps the map valid. */
+const HARD_SPACE_PATTERN = /[\u00A0\u2002\u2003\u2007\u2009\u202F]/g;
+
+/** Only the shape this module reads, so a test can hand it plain objects. */
+export interface FindTextNodeLike {
+ readonly nodeType: number;
+ readonly data: string;
+}
+
+export interface FindElementLike {
+ readonly nodeType: number;
+ readonly tagName: string;
+ readonly childNodes: ArrayLike<FindTextNodeLike | FindElementLike>;
+ getAttribute(name: string): string | null;
+ /** Optional so a test can hand this plain objects; every browser we ship on has it. */
+ checkVisibility?(options?: {
+ contentVisibilityAuto?: boolean;
+ opacityProperty?: boolean;
+ visibilityProperty?: boolean;
+ /** Historic spellings of the two above, still the only ones older engines read. */
+ checkOpacity?: boolean;
+ checkVisibilityCSS?: boolean;
+ }): boolean;
+}
+
+export type FindNodeLike = FindTextNodeLike | FindElementLike;
+
+/** One text node's contribution, at the offset its first character took in `text`. */
+export interface TextSegment {
+ node: FindTextNodeLike;
+ start: number;
+ /** Always the node's own `data.length`, so an offset inside the run maps straight through. */
+ length: number;
+ /** True inside a `<pre>` or anything else that keeps its whitespace. See `findMatches`. */
+ preserved: boolean;
+}
+
+export interface FindTextIndex {
+ /** Case-folded haystack, block boundaries written as `BLOCK_SEPARATOR`. */
+ text: string;
+ /** Sorted by `start`, gapped wherever a separator was written. */
+ segments: TextSegment[];
+ /** True when `MAX_INDEX_CHARS` stopped the walk early. */
+ truncated: boolean;
+}
+
+export const EMPTY_TEXT_INDEX: FindTextIndex = {
+ text: "",
+ segments: [],
+ truncated: false,
+};
+
+/** Dotted I, the only code point whose `toLowerCase` grows (scanned all of them). Mapped to bare
+ * `i`, the Turkic fold: the default adds a combining dot, and one index char must stand for one
+ * document char. */
+const DOTTED_I_PATTERN = /\u0130/g;
+
+/** Final sigma, mapped to medial as `CaseFolding.txt` does. `toLowerCase` picks between them by
+ * what follows, so only one of the two spellings a reader can type would match. One unit each. */
+const FINAL_SIGMA_PATTERN = /\u03c2/g;
+
+/**
+ * Case-fold the flattened document without changing its length.
+ *
+ * The two mappings above are what the default fold misses. With dotted I gone first `toLowerCase`
+ * cannot change a length, so this is one pass: 11ms at the 4M ceiling, against 146ms walking code
+ * points.
+ */
+export function foldText(raw: string): string {
+ const spaced = raw
+ .replace(HARD_SPACE_PATTERN, " ")
+ .replace(DOTTED_I_PATTERN, "i");
+ const folded = spaced.toLowerCase();
+ if (folded.length === spaced.length) {
+ return folded.replace(FINAL_SIGMA_PATTERN, "\u03c3");
+ }
+ // Nothing reaches this: dotted I was the only expansion and it is gone by here. But a wrong
+ // length would misplace every offset after it, so fall back to the fold that cannot drift.
+ let plain = "";
+ for (const point of spaced) {
+ const lower = point.toLowerCase();
+ plain += lower.length === point.length ? lower : point;
+ }
+ 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.
+ */
+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 (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.
+ if (element.getAttribute("hidden") !== null) return true;
+ if (element.getAttribute("inert") !== null) return true;
+ return element.getAttribute("aria-hidden") === "true";
+}
+
+/**
+ * True when the walk must not descend into this element.
+ *
+ * `style` is the element's resolved style, passed in by the walk so the read is made once per
+ * element rather than once here and once again in `visit` -- which is what the measurement quoted
+ * on `computedStyle` was taken to mean, and was not what the code did. Optional because the
+ * exported signature is one the tests call directly; resolving it here is the same answer.
+ */
+export function skipsSubtree(
+ element: FindElementLike,
+ style: ResolvedStyle | null = computedStyle(element),
+): boolean {
+ if (skipsByMarkup(element)) return true;
+ // Anything the engine is not painting. Attributes miss the common case: `hidden lg:flex` is a
+ // CLASS, and text under it would be counted and walked to while nobody can see it.
+ //
+ // `contentVisibilityAuto` off: such a subtree is skipped, not hidden, and asking would drop the
+ // far half of a Hub README and of a maths thread, with nothing to put it back (scrolling renders
+ // without mutating, so the observer never fires). Opacity off, so a message fading in stays
+ // findable.
+ //
+ // Both spellings of each option: `visibilityProperty`/`opacityProperty` are renames of
+ // `checkVisibilityCSS`/`checkOpacity`, an engine reads only the name it knows, and Web IDL drops
+ // an unknown member silently. The modern name alone is a no-op on Chrome 105-120 and Firefox
+ // 106-121, which would then index and highlight `visibility: hidden` text.
+ const painted = element.checkVisibility?.({
+ contentVisibilityAuto: false,
+ opacityProperty: false,
+ checkOpacity: false,
+ visibilityProperty: true,
+ checkVisibilityCSS: true,
+ });
+ if (painted === false) {
+ // `display: contents` has no box, and no box is the first thing `checkVisibility` calls
+ // invisible, so a wrapper whose children are all on screen answers false. The shell and the
+ // training page both use one, which is most of what there is to search. A real box is what
+ // makes an element hidden rather than absent.
+ return style?.display !== "contents";
+ }
+ // No `checkVisibility` to ask: it landed in Safari 17.4, and WebKitGTK is a supported engine
+ // here, so this is a real path and the visible branch would index every `display: none` subtree.
+ // `paintsNothing` mirrors what the call above asks for.
+ if (painted === undefined && paintsNothing(style)) return true;
+ return clippedAway(style);
+}
+
+interface ResolvedStyle {
+ display?: string;
+ visibility?: string;
+ whiteSpace?: string;
+ clip?: string;
+ clipPath?: string;
+}
+
+/**
+ * True when this element keeps its own text off screen while still being descended into.
+ *
+ * Only `display: contents` reaches this, and `skipsSubtree` lets it through on purpose. But
+ * `visibility` inherits, and only ELEMENT children are re-checked, so a direct text child of a
+ * hidden `contents` wrapper would be indexed and highlighted. Scoped to the element's own text:
+ * a descendant restoring `visibility: visible` is painted again and still reached.
+ */
+function hidesOwnText(style: ResolvedStyle | null): boolean {
+ return (
+ style?.display === "contents" &&
+ (style.visibility === "hidden" || style.visibility === "collapse")
+ );
+}
+
+/** True when this element paints no box, for engines with no `checkVisibility`. `display: contents`
+ * is boxless rather than hidden, so it is excluded here and `hidesOwnText` covers its own text,
+ * which is what the branch above does when the API answers. */
+function paintsNothing(style: ResolvedStyle | null): boolean {
+ if (style?.display === "none") return true;
+ if (style?.display === "contents") return false;
+ return style?.visibility === "hidden" || style?.visibility === "collapse";
+}
+
+/** The two spellings of Tailwind's `sr-only`: a real box, full opacity, clipped to nothing.
+ * `checkVisibility` calls that visible, so without this the app's 46 screen-reader labels are
+ * counted and walked to under a highlight clipped away with them. */
+function clippedAway(style: ResolvedStyle | null): boolean {
+ return (
+ style?.clipPath === "inset(50%)" ||
+ style?.clip === "rect(0px, 0px, 0px, 0px)"
+ );
+}
+
+/**
+ * `display` and `white-space` as resolved, or null off the DOM where the tag sets stand in.
+ *
+ * Used for three things: telling a boxless wrapper from a hidden one, the block boundaries no tag
+ * name carries, and where whitespace is preserved. At 8000 elements: 2.5ms for the visibility check
+ * alone, 4.3ms with this, against a 300ms floor between rebuilds.
+ */
+function computedStyle(element: FindElementLike): ResolvedStyle | null {
+ const view = globalThis as unknown as {
+ getComputedStyle?: (element: FindElementLike) => ResolvedStyle;
+ };
+ return view.getComputedStyle?.(element) ?? null;
+}
+
+/** True when this element ends the line it sits on. `inline-block` and friends do not, `contents`
+ * has no box. Being wrong inserts a needless separator, which can only lose a match and never
+ * invent one, so anything unrecognised counts as a boundary. */
+function isBlockDisplay(display: string | undefined): boolean {
+ if (display === undefined) return false;
+ return !(
+ display.startsWith("inline") ||
+ display === "contents" ||
+ display === "none"
+ );
+}
+
+/** True where whitespace is kept rather than collapsed. `pre-line` is excluded: it still collapses
+ * runs of spaces, which is the half the query flexibility below cares about. */
+function preservesWhitespace(whiteSpace: string | undefined): boolean {
+ return (
+ whiteSpace === "pre" ||
+ whiteSpace === "pre-wrap" ||
+ whiteSpace === "break-spaces"
+ );
+}
+
+/**
+ * Flatten `root` into one case-folded string plus the map back to its text nodes.
+ *
+ * Recursive rather than a `TreeWalker`: the walker reports entering an element but not leaving one,
+ * and the closing separator is what stops `<p>a</p>b` reading as "ab".
+ */
+export function buildTextIndex(
+ root: FindElementLike,
+ /** Subtrees to index after `root`, in the order they sit in the document. Portaled surfaces. */
+ extraRoots: readonly FindElementLike[] = [],
+): FindTextIndex {
+ const parts: string[] = [];
+ const segments: TextSegment[] = [];
+ let length = 0;
+ /** The index does not hold everything: a node was clipped, or the ceiling was reached. */
+ let truncated = false;
+ /** The ceiling was reached, which is the only thing that stops the walk. */
+ let full = false;
+ /** What `full` is measured against. Raised for the portaled surfaces below, which the workspace
+ * gives up a share of the budget for, and only when there is one of them to give it to. */
+ let ceiling =
+ MAX_INDEX_CHARS - (extraRoots.length > 0 ? PORTAL_RESERVE_CHARS : 0);
+ // Written lazily, so a run of empty blocks costs nothing and no separator lands at either end.
+ let pendingSeparator = false;
+
+ const visit = (element: FindElementLike, inherited: boolean): void => {
+ // Markup first, so a subtree turned down on a tag or an attribute costs no layout read at all.
+ // Then one resolved style, shared with the rest of the skip rule: both halves need it, and
+ // resolving it separately in each doubled the cost the comment on `computedStyle` quotes.
+ if (skipsByMarkup(element)) return;
+ const style = computedStyle(element);
+ if (skipsSubtree(element, style)) return;
+ // The tag set answers `<br>`, whose display is inline. Layout is the rest: two `span.block`
+ // run together without a boundary, so "Open" above "AI" reads as one word.
+ const block =
+ BLOCK_TAGS.has(element.tagName) || isBlockDisplay(style?.display);
+ if (block) pendingSeparator = true;
+ const preserved =
+ style?.whiteSpace === undefined
+ ? inherited
+ : preservesWhitespace(style.whiteSpace);
+ // Asked once per element, not per text node: a boxless wrapper that is also invisible paints
+ // none of its own text, and that text is the one thing `skipsSubtree` never gets to judge.
+ const ownTextHidden = hidesOwnText(style);
+ const children = element.childNodes;
+ for (let i = 0; i < children.length; i += 1) {
+ if (full) return;
+ const child = children[i];
+ if (child.nodeType === TEXT_NODE) {
+ if (ownTextHidden) continue;
+ const node = child as FindTextNodeLike;
+ const data = node.data;
+ if (data.length === 0) continue;
+ // Before the separator, not after: one emitted past the ceiling makes `take` negative, and
+ // `slice(0, negative)` takes all but the last character of the next node.
+ if (length >= ceiling) {
+ truncated = true;
+ full = true;
+ return;
+ }
+ if (pendingSeparator) {
+ pendingSeparator = false;
+ if (length > 0) {
+ parts.push(BLOCK_SEPARATOR);
+ length += 1;
+ }
+ }
+ // A share, not all of it: the prefix keeps one huge node findable, while the whole
+ // remaining budget for it would leave out everything after, messages on screen included.
+ const take = Math.min(ceiling - length, MAX_NODE_CHARS);
+ if (take <= 0) {
+ truncated = true;
+ full = true;
+ return;
+ }
+ const raw = data.length > take ? data.slice(0, take) : data;
+ parts.push(raw);
+ segments.push({ node, start: length, length: raw.length, preserved });
+ length += raw.length;
+ // Siblings still get indexed, but what was dropped must leave a boundary or the prefix
+ // runs into the next node and a match across that seam paints over the gap.
+ if (raw.length < data.length) {
+ truncated = true;
+ pendingSeparator = true;
+ }
+ } else if (child.nodeType === ELEMENT_NODE) {
+ visit(child as FindElementLike, preserved);
+ if (full) return;
+ }
+ }
+ if (block) pendingSeparator = true;
+ };
+
+ visit(root, false);
+ // 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;
+ full = false;
+ for (const extra of extraRoots) {
+ if (full) break;
+ // A boundary between roots: they are separate surfaces, and a match must not run across.
+ pendingSeparator = true;
+ visit(extra, false);
+ }
+ // 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 };
+}
+
+/** Fold a query the way the haystack was folded. Null when it cannot match: empty, or carrying the
+ * separator, which only a paste could produce. */
+export function normalizeQuery(query: string): string | null {
+ if (query.length === 0) return null;
+ const folded = foldText(query);
+ if (folded.includes(BLOCK_SEPARATOR)) return null;
+ return folded;
+}
+
+export interface FindMatch {
+ start: number;
+ /** Exclusive, as a `Range` end is. */
+ end: number;
+}
+
+/** Regex metacharacters, so a query of "a.b" does not match "axb". */
+const REGEX_META_PATTERN = /[.*+?^${}()|[\]\\]/g;
+
+/** Combining dot above, the tail of a decomposed dotted I. */
+const COMBINING_DOT = "̇";
+
+/**
+ * The canonically equivalent spellings of `needle`, longest first so the fuller one wins.
+ *
+ * Composed and decomposed spellings look identical on screen and both turn up in one thread.
+ * Normalizing the index would change its length, and every offset stands for one document
+ * character, so the variants go into the pattern instead and the document is left alone.
+ *
+ * `dotted` adds the spelling a decomposed dotted I leaves behind. U+0130 decomposes to `I` plus a
+ * combining dot, which folds to `i` plus that dot, and `i` + dot has no precomposed form, so NFC
+ * cannot put it back and the plain query misses a word plainly on screen. Only offered when the
+ * index carries a combining dot, so an ordinary document keeps the single-variant `indexOf` path.
+ */
+function canonicalVariants(needle: string, dotted: boolean): string[] {
+ const variants = [needle];
+ for (const form of ["NFC", "NFD"] as const) {
+ const variant = needle.normalize(form);
+ if (!variants.includes(variant)) variants.push(variant);
+ }
+ if (dotted && needle.includes("i")) {
+ for (const variant of [...variants]) {
+ const dottedVariant = variant.replace(/i/g, `i${COMBINING_DOT}`);
+ if (!variants.includes(dottedVariant)) variants.push(dottedVariant);
+ }
+ }
+ if (variants.length > 1) variants.sort((a, b) => b.length - a.length);
+ 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;
+
+/**
+ * The needle as a regex source in which each cluster may match either of its spellings.
+ *
+ * Alternating whole spellings of the WHOLE query only reaches text that is all-composed or
+ * all-decomposed. A single occurrence can be neither: joining two text nodes joins two sources, so
+ * `café` in one and `café` in the next make one visible word with a spelling the query
+ * cannot be written in. Every engine's own find matches that (measured on chromium, firefox and
+ * webkit), so it is below the baseline the rest of this file is held to.
+ *
+ * Per cluster rather than per query, which is also SMALLER: the old form repeated the query once
+ * per spelling, this writes it once and pays about eight characters for each cluster that actually
+ * has two spellings. Decomposed first, since it is the longer of the two.
+ */
+function canonicalSource(needle: string, dotted: boolean): string {
+ let out = "";
+ for (const [cluster] of needle.normalize("NFD").matchAll(CLUSTER_PATTERN)) {
+ if (/^\s/.test(cluster)) {
+ // A whitespace run in the query matches a run in the document, however it is spelt there.
+ out += out.endsWith("\\s+") ? "" : "\\s+";
+ continue;
+ }
+ const spellings = [cluster];
+ const composed = cluster.normalize("NFC");
+ if (composed !== cluster) spellings.push(composed);
+ // 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 +=
+ spellings.length === 1
+ ? escapeForRegex(spellings[0])
+ : `(?:${spellings.map(escapeForRegex).join("|")})`;
+ }
+ return out;
+}
+
+function escapeForRegex(text: string): string {
+ return text.replace(REGEX_META_PATTERN, "\\$&");
+}
+
+/**
+ * A pattern for a query spanning whitespace or spelt more than one way, or null for a plain scan.
+ *
+ * HTML collapses whitespace, so a soft-wrapped paragraph renders as one line while its node holds
+ * the newline; each run in the query matches a run in the document. The separator is not
+ * whitespace, so block boundaries stay closed. Single-word ASCII queries keep the `indexOf` path.
+ */
+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;
+ 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`
+ // instead, back outside this `try`. One run against nothing forces the compile while it can
+ // still be caught, and leaves `lastIndex` at 0 for the real scan.
+ pattern.exec("");
+ return pattern;
+ } catch {
+ // Every engine caps how large a pattern it will compile, and the cap is its own business:
+ // the spec sets none, so there is no length to test against that would be right everywhere.
+ // A pasted log reaches it -- measured at 15,651 characters on V8 -- and the throw came out
+ // through the keystroke that caused it and took the bar down with it. Falling back to the
+ // literal scan below costs the flexed whitespace and keeps the search working.
+ return null;
+ }
+}
+
+/**
+ * Walk every match for `needle` in document order, stopping when `visit` says so. Non-overlapping,
+ * like every browser's own find, which is what terminates a self-overlapping query.
+ *
+ * One place, so the two ways of matching stay one behaviour. Flexed whitespace is for prose; inside
+ * a `<pre>` the whitespace on screen IS the whitespace in the node, so "foo bar" must not land on
+ * "foo bar" there. The platform's own find draws the same line.
+ */
+function eachMatch(
+ index: FindTextIndex,
+ needle: string,
+ visit: (start: number, end: number) => boolean,
+): void {
+ const variants = canonicalVariants(
+ needle,
+ index.text.includes(COMBINING_DOT),
+ );
+ // Nothing longer than the haystack can be inside it. Measured against the SHORTEST spelling,
+ // since a decomposed query is longer than the precomposed text it is meant to find. This is
+ // ahead of `matchPattern` because that is the expensive half: escaping a pasted log, repeating
+ // it once per variant and handing the result to the regex compiler.
+ if (
+ Math.min(...variants.map((variant) => variant.length)) > index.text.length
+ )
+ return;
+ // What counts as "spelt the way it was typed": any whole-query spelling, or any mixture of the
+ // per-cluster ones, which compare equal once composed. Whitespace flexing survives NFC, so a hit
+ // that only flexed a space is still told apart from one that merely spells a letter differently.
+ const composedNeedle = needle.normalize("NFC");
+ const asTyped = (hit: string): boolean =>
+ variants.includes(hit) || hit.normalize("NFC") === composedNeedle;
+ const pattern = matchPattern(variants, needle);
+ if (pattern) {
+ for (;;) {
+ const hit = pattern.exec(index.text);
+ if (hit === null) return;
+ const end = hit.index + hit[0].length;
+ // Any spelling of the query counts as typed exactly; only flexed whitespace does not.
+ if (
+ touchesPreserved(index.segments, hit.index, end) &&
+ !asTyped(hit[0])
+ ) {
+ pattern.lastIndex = hit.index + 1;
+ continue;
+ }
+ if (!visit(hit.index, end)) return;
+ pattern.lastIndex = end;
+ }
+ }
+ let from = 0;
+ for (;;) {
+ const at = index.text.indexOf(needle, from);
+ if (at === -1) return;
+ if (!visit(at, at + needle.length)) return;
+ from = at + needle.length;
+ }
+}
+
+/** `limit` matches starting from the `skip`-th one. */
+function collectMatches(
+ index: FindTextIndex,
+ needle: string,
+ limit: number,
+ skip: number,
+): FindMatch[] {
+ const out: FindMatch[] = [];
+ let seen = 0;
+ eachMatch(index, needle, (start, end) => {
+ seen += 1;
+ if (seen <= skip) return true;
+ out.push({ start, end });
+ return out.length < limit;
+ });
+ return out;
+}
+
+/**
+ * Matches for `query`, at most `limit` of them, as a window around `anchor`.
+ *
+ * A common letter in a long thread has tens of thousands of matches, and keeping the first `limit`
+ * keeps only the top of the document, walking a reader at the bottom away from the occurrences
+ * beside them. When the cap bites the kept matches are the ones nearest the reader; under the cap
+ * this is the same single pass it always was.
+ *
+ * `anchor` may be a thunk, because working it out reads layout and a plain argument is evaluated
+ * whether or not it is wanted. A number still means the same thing.
+ */
+export function findMatches(
+ index: FindTextIndex,
+ query: string,
+ limit = MAX_MATCHES,
+ anchor: number | (() => number) = 0,
+): FindMatch[] {
+ const needle = normalizeQuery(query);
+ if (needle === null) return [];
+ const head = collectMatches(index, needle, limit, 0);
+ // Before resolving the anchor, so an under-cap query never pays for it.
+ if (head.length < limit) return head;
+ const at = typeof anchor === "function" ? anchor() : anchor;
+ if (at <= 0) return head;
+
+ // Capped, so where the window sits matters. Two more passes, no allocation in the first.
+ //
+ // The count stops early: `total` only keeps the window from running off the end, and once
+ // `total - limit` reaches the left edge it can no longer pull it back, so later matches are
+ // counted for nothing. Past the anchor `before` is final, which is what makes the edge knowable.
+ // The clamp is safe because it only binds near the end, where the true total is under the
+ // ceiling and the walk never stops early. At 4M chars, 444,444 matches, anchored halfway:
+ // 6.4ms over all of them to 3.3ms over 224,722, same window either way.
+ let total = 0;
+ let before = 0;
+ let enough = Number.POSITIVE_INFINITY;
+ eachMatch(index, needle, (start) => {
+ total += 1;
+ if (start < at) {
+ before += 1;
+ return true;
+ }
+ if (enough === Number.POSITIVE_INFINITY) {
+ enough = Math.max(before - (limit >> 1), 0) + limit;
+ }
+ return total < enough;
+ });
+ // Centred on the reader, then pushed back inside the list at either end.
+ const start = Math.min(
+ Math.max(before - (limit >> 1), 0),
+ Math.max(total - limit, 0),
+ );
+ return start === 0 ? head : collectMatches(index, needle, limit, start);
+}
+
+/**
+ * Throw away the one match asked for over the cap, from whichever end the reader is further from.
+ *
+ * The caller asks for `MAX_MATCHES + 1` so that a page holding exactly the cap does not have to
+ * read as a floor, then throws the extra one away. Taking it off the tail is right only while the
+ * window starts at the top of the document. Once the reader is far enough down the anchored window
+ * IS the tail, and its last entry is the document's final occurrence -- the one nearest them, and
+ * the one the walk was then unable to reach at all.
+ *
+ * Measured on 6000 matches with the reader at the bottom: the window covered the final occurrence
+ * at offset 11998, and trimming the tail left the walk ending at 11996.
+ *
+ * Lives here rather than beside its caller for the same reason `mutatesSearchableText` does: the
+ * hook imports React and cannot be loaded under `node --test`.
+ */
+export function dropProbeFurthestFrom(
+ matches: FindMatch[],
+ anchor: number | null,
+ limit = MAX_MATCHES,
+): void {
+ // No anchor means `findMatches` never resolved one, which only happens under the cap. A window
+ // that already starts at the document's first match has nothing above the reader to give up.
+ if (
+ anchor !== null &&
+ matches.length > 0 &&
+ anchor - matches[0].start > matches[matches.length - 1].start - anchor
+ ) {
+ matches.shift();
+ return;
+ }
+ matches.length = limit;
+}
+
+/** True when `[start, end)` reaches into a run whose whitespace is kept rather than collapsed. */
+function touchesPreserved(
+ segments: TextSegment[],
+ start: number,
+ end: number,
+): boolean {
+ let at = segmentAt(segments, start);
+ // A match can open on a separator, which belongs to no segment; take the next one along.
+ if (at === -1) {
+ at = segments.findIndex((segment) => segment.start >= start);
+ if (at === -1) return false;
+ }
+ for (let i = at; i < segments.length; i += 1) {
+ const segment = segments[i];
+ if (segment.start >= end) return false;
+ if (segment.preserved) return true;
+ }
+ return false;
+}
+
+/** The segment holding `offset`, or -1 when it lands on a separator or past the end. */
+export function segmentAt(segments: TextSegment[], offset: number): number {
+ let lo = 0;
+ let hi = segments.length - 1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const segment = segments[mid];
+ if (offset < segment.start) {
+ hi = mid - 1;
+ } else if (offset >= segment.start + segment.length) {
+ lo = mid + 1;
+ } else {
+ return mid;
+ }
+ }
+ return -1;
+}
+
+/** A text node and an offset inside it, which is what a `Range` boundary takes. */
+export interface TextPosition {
+ node: FindTextNodeLike;
+ offset: number;
+}
+
+/** Where a match starts. */
+export function startPositionAt(
+ segments: TextSegment[],
+ offset: number,
+): TextPosition | null {
+ const index = segmentAt(segments, offset);
+ if (index === -1) return null;
+ const segment = segments[index];
+ return { node: segment.node, offset: offset - segment.start };
+}
+
+/**
+ * Where a match ends. Located from its last character, since an exclusive end sits one past the run
+ * whenever the match finishes a text node, and that is the boundary `setEnd` wants there.
+ */
+export function endPositionAt(
+ segments: TextSegment[],
+ end: number,
+): TextPosition | null {
+ const index = segmentAt(segments, end - 1);
+ if (index === -1) return null;
+ const segment = segments[index];
+ return { node: segment.node, offset: end - segment.start };
+}
diff --git a/studio/frontend/src/features/find-in-page/stores/find-in-page-store.ts b/studio/frontend/src/features/find-in-page/stores/find-in-page-store.ts
new file mode 100644
index 00000000000..df2e6d85bb7
--- /dev/null
+++ b/studio/frontend/src/features/find-in-page/stores/find-in-page-store.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { create } from "zustand";
+
+/**
+ * Whether the bar is up and what is typed in it. Nothing else: the index, matches and ranges are
+ * refs inside the bar, which only exists while it is open.
+ */
+interface FindInPageStore {
+ open: boolean;
+ query: string;
+ /**
+ * Bumped on every press of the chord, so pressing it again re-focuses the field and selects what
+ * is in it. A counter rather than a boolean: two presses in a row have to be two events.
+ */
+ focusToken: number;
+ requestFocus: () => void;
+ close: () => void;
+ setQuery: (query: string) => void;
+ /** Forget the search entirely, query included. For leaving the shell, not for closing the bar. */
+ reset: () => void;
+}
+
+export const useFindInPageStore = create<FindInPageStore>((set) => ({
+ open: false,
+ query: "",
+ focusToken: 0,
+ requestFocus: () =>
+ set((state) => ({ open: true, focusToken: state.focusToken + 1 })),
+ // The query survives a close, so re-opening offers the last search again, selected.
+ close: () => set({ open: false }),
+ setQuery: (query) => set({ query }),
+ reset: () => set({ open: false, query: "" }),
+}));
diff --git a/studio/frontend/src/features/settings/hooks/use-shortcut.ts b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
index 46b6cdfe2ad..6fc01a3a57c 100644
--- a/studio/frontend/src/features/settings/hooks/use-shortcut.ts
+++ b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
@@ -4,9 +4,9 @@
import { useEffect, useMemo, useRef } from "react";
import {
SHORTCUT_SLOTS,
- activationBelongsToFocus,
type ShortcutBinding,
type ShortcutId,
+ activationBelongsToFocus,
formatBindingLabel,
matchesBinding,
parseBinding,
@@ -107,13 +107,21 @@ export interface UseShortcutOptions {
* past the repeat delay would land wherever the user let go.
*/
repeats?: boolean;
+ /**
+ * Asked at press time, before the chord is consumed. Return false to leave the
+ * key to whatever else would have had it, the browser's own binding included.
+ * `enabled` cannot answer this: it is read at render, and returning from the
+ * handler is too late, since the event is already prevented by then.
+ */
+ claims?: () => boolean;
}
/** The chords `id` answers to now, joined so the effect re-runs only on a real change. */
function useBindingValues(id: ShortcutId): string {
return useKeyboardShortcutsStore((s) =>
- SHORTCUT_SLOTS.map((slot) => resolveBinding(s.overrides, id, slot) ?? "")
- .join("\0"),
+ SHORTCUT_SLOTS.map(
+ (slot) => resolveBinding(s.overrides, id, slot) ?? "",
+ ).join("\0"),
);
}
@@ -132,6 +140,7 @@ export function useShortcut(
skipInTextFields = false,
textFieldException,
repeats = false,
+ claims,
} = options;
const values = useBindingValues(id);
// A chord claimed by two actions is consumed by whichever listener runs
@@ -154,10 +163,10 @@ export function useShortcut(
});
return out;
}, [values, ownedFlags]);
- // The handler usually closes over fresh props, so keep it in a ref rather
- // than tearing down and re-adding the listener on every render.
- const handlerRef = useRef(handler);
- handlerRef.current = handler;
+ // These usually close over fresh props, so keep them in a ref rather than
+ // tearing down and re-adding the listener on every render.
+ const latestRef = useRef({ handler, claims });
+ latestRef.current = { handler, claims };
useEffect(() => {
if (bindings.length === 0 || !enabled) return;
@@ -178,12 +187,15 @@ export function useShortcut(
) {
return;
}
+ // Before preventDefault, which is the whole point: an unclaimed chord has
+ // to reach the browser untouched.
+ if (latestRef.current.claims?.() === false) return;
event.preventDefault();
// Held past the OS repeat delay the chord arrives again and again. It
// stays consumed either way, but only an action that asked for repeats
// runs on them.
if (event.repeat && !repeats) return;
- handlerRef.current(event);
+ latestRef.current.handler(event);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 16d5da33001..df3e484b77c 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -62,6 +62,7 @@ export type {
} from "./api/personalization";
export {
COMPOSER_INPUT_SELECTOR,
+ isImeComposing,
isSurfaceBackgrounded,
isSurfaceInForeground,
useShortcut,
diff --git a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts
index 82ef6c63495..6bda9679990 100644
--- a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts
+++ b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts
@@ -45,6 +45,7 @@ export type ShortcutId =
| "switchToAudio"
| "switchToExport"
// Panels and app-level actions
+ | "findInPage"
| "toggleApiMonitor"
| "toggleSidebar"
| "openMcpServers"
@@ -200,6 +201,11 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [
...WORKSPACE_DEFS,
// -- Panels and app-level actions ---------------------------------------
+ // The one default that deliberately takes a chord the browser owns, because the browser's own
+ // find is what it replaces: that one cannot reach a message the mount window has not committed,
+ // counts the sidebar and composer as page, and does not exist on the desktop build. The chord is
+ // cancellable in every engine this ships on, so the handler wins it; Settings still flags it.
+ def("findInPage", "Mod+KeyF"),
// ⌥⌘U is view source on macOS, so U keeps its mnemonic on ⌃⇧ there instead,
// the same swap the composer pair below makes. Off macOS it gives U up
// altogether: three actions wanted that letter and only two chords carry it
@@ -313,6 +319,9 @@ const BROWSER_RESERVED_VALUES = new Set<string>([
"Mod+KeyW",
"Mod+Shift+KeyW",
"Mod+KeyL",
+ // Find in page, on every engine. Unsloth ships its own on it anyway (see the note by the
+ // default); this is what warns a web user before they rebind onto it.
+ "Mod+KeyF",
"Mod+KeyR",
"Mod+Shift+KeyR",
"Mod+KeyP",
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index a5b807186c8..08103523dfe 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -197,6 +197,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.keyboardShortcuts.actions.switchToVideo.label",
"settings.keyboardShortcuts.actions.switchToAudio.label",
"settings.keyboardShortcuts.actions.switchToExport.label",
+ "settings.keyboardShortcuts.actions.findInPage.label",
"settings.keyboardShortcuts.actions.toggleApiMonitor.label",
"settings.keyboardShortcuts.actions.toggleSidebar.label",
"settings.keyboardShortcuts.actions.openMcpServers.label",
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 5f6fbbe0ffb..385c16bf086 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -52,6 +52,13 @@ export const ar = {
shutdown: "إيقاف التشغيل",
},
shell: {
+ find: {
+ label: "البحث في الصفحة",
+ previous: "التطابق السابق",
+ next: "التطابق التالي",
+ close: "إغلاق البحث",
+ truncated: "هذه الصفحة أطول من أن يتم البحث فيها بالكامل.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -222,6 +229,10 @@ export const ar = {
browserReserved:
"قد يحتفظ متصفحك بهذه التركيبة لنفسه. تعمل في تطبيق سطح المكتب.",
actions: {
+ findInPage: {
+ label: "البحث في الصفحة",
+ description: "البحث في نص هذه الصفحة",
+ },
openSettings: {
label: "فتح الإعدادات",
description: "فتح مربع حوار الإعدادات",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index cfb79302325..4c29c2234c0 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -55,6 +55,13 @@ export const de = {
shutdown: "Herunterfahren",
},
shell: {
+ find: {
+ label: "Auf der Seite suchen",
+ previous: "Vorheriger Treffer",
+ next: "Nächster Treffer",
+ close: "Suche schließen",
+ truncated: "Diese Seite ist zu lang, um vollständig durchsucht zu werden.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -226,6 +233,10 @@ export const de = {
browserReserved:
"Dein Browser behält diese Tastenkombination unter Umständen für sich. In der Desktop-App funktioniert sie.",
actions: {
+ findInPage: {
+ label: "Auf der Seite suchen",
+ description: "Den Text auf dieser Seite durchsuchen",
+ },
openSettings: {
label: "Einstellungen öffnen",
description: "Den Einstellungsdialog öffnen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 741b0b166b8..a309bcf6845 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -47,6 +47,13 @@ export const en = {
shutdown: "Shutdown",
},
shell: {
+ find: {
+ label: "Find in page",
+ previous: "Previous match",
+ next: "Next match",
+ close: "Close find",
+ truncated: "This page is too long to search in full.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -222,6 +229,10 @@ export const en = {
browserReserved:
"Your browser may keep this chord for itself. It works in the desktop app.",
actions: {
+ findInPage: {
+ label: "Find in page",
+ description: "Search the text on this page",
+ },
openSettings: {
label: "Open settings",
description: "Open the settings dialog",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 7325b72fc11..f45970efe90 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -54,6 +54,13 @@ export const es = {
shutdown: "Apagar",
},
shell: {
+ find: {
+ label: "Buscar en la página",
+ previous: "Coincidencia anterior",
+ next: "Coincidencia siguiente",
+ close: "Cerrar búsqueda",
+ truncated: "Esta página es demasiado larga para buscarla por completo.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -225,6 +232,10 @@ export const es = {
browserReserved:
"Puede que tu navegador se reserve esta combinación. En la app de escritorio funciona.",
actions: {
+ findInPage: {
+ label: "Buscar en la página",
+ description: "Buscar el texto de esta página",
+ },
openSettings: {
label: "Abrir ajustes",
description: "Abrir el diálogo de ajustes",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 475fde15a8f..de7637f6997 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -55,6 +55,13 @@ export const fr = {
shutdown: "Arrêter",
},
shell: {
+ find: {
+ label: "Rechercher dans la page",
+ previous: "Résultat précédent",
+ next: "Résultat suivant",
+ close: "Fermer la recherche",
+ truncated: "Cette page est trop longue pour être parcourue en entier.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -226,6 +233,10 @@ export const fr = {
browserReserved:
"Votre navigateur peut réserver cette combinaison. Elle fonctionne dans l’application de bureau.",
actions: {
+ findInPage: {
+ label: "Rechercher dans la page",
+ description: "Rechercher le texte de cette page",
+ },
openSettings: {
label: "Ouvrir les paramètres",
description: "Ouvrir la fenêtre des paramètres",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index b5f71690cc0..786e200708f 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -55,6 +55,13 @@ export const hi = {
shutdown: "शटडाउन",
},
shell: {
+ find: {
+ label: "पेज में खोजें",
+ previous: "पिछला मिलान",
+ next: "अगला मिलान",
+ close: "खोज बंद करें",
+ truncated: "यह पेज पूरी तरह खोजने के लिए बहुत लंबा है।",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -225,6 +232,10 @@ export const hi = {
browserReserved:
"आपका ब्राउज़र यह कुंजी संयोजन अपने पास रख सकता है। डेस्कटॉप ऐप में यह काम करता है।",
actions: {
+ findInPage: {
+ label: "पेज में खोजें",
+ description: "इस पेज के टेक्स्ट में खोजें",
+ },
openSettings: {
label: "सेटिंग्स खोलें",
description: "सेटिंग्स संवाद खोलें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 17ef7f6e533..c21f360b04c 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -19,6 +19,13 @@ export const it = {
shutdown: "Arresta",
},
shell: {
+ find: {
+ label: "Trova nella pagina",
+ previous: "Risultato precedente",
+ next: "Risultato successivo",
+ close: "Chiudi ricerca",
+ truncated: "Questa pagina è troppo lunga per essere cercata per intero.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -190,6 +197,10 @@ export const it = {
browserReserved:
"Il browser potrebbe riservare questa combinazione per sé. Nell’app desktop funziona.",
actions: {
+ findInPage: {
+ label: "Trova nella pagina",
+ description: "Cerca il testo di questa pagina",
+ },
openSettings: {
label: "Apri le impostazioni",
description: "Apri la finestra delle impostazioni",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 26c866c8ee2..150ab4a2512 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -54,6 +54,13 @@ export const ja = {
shutdown: "シャットダウン",
},
shell: {
+ find: {
+ label: "ページ内検索",
+ previous: "前の一致",
+ next: "次の一致",
+ close: "検索を閉じる",
+ truncated: "このページは長すぎるため、全体を検索できません。",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -224,6 +231,10 @@ export const ja = {
browserReserved:
"ブラウザがこのキーを使う場合があります。デスクトップアプリでは動作します。",
actions: {
+ findInPage: {
+ label: "ページ内検索",
+ description: "このページ内のテキストを検索します",
+ },
openSettings: {
label: "設定を開く",
description: "設定ダイアログを開きます",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index f5a17b5bceb..c784e4332e1 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -52,6 +52,13 @@ export const ko = {
shutdown: "종료",
},
shell: {
+ find: {
+ label: "페이지에서 찾기",
+ previous: "이전 결과",
+ next: "다음 결과",
+ close: "찾기 닫기",
+ truncated: "이 페이지는 너무 길어 전체를 검색할 수 없습니다.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -222,6 +229,10 @@ export const ko = {
browserReserved:
"브라우저가 이 조합을 가져갈 수 있습니다. 데스크톱 앱에서는 동작합니다.",
actions: {
+ findInPage: {
+ label: "페이지에서 찾기",
+ description: "이 페이지의 텍스트를 검색합니다",
+ },
openSettings: {
label: "설정 열기",
description: "설정 창을 엽니다",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 1885b182f8b..e5fd4b52b90 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -54,6 +54,13 @@ export const ptBR = {
shutdown: "Desligar",
},
shell: {
+ find: {
+ label: "Localizar na página",
+ previous: "Ocorrência anterior",
+ next: "Próxima ocorrência",
+ close: "Fechar busca",
+ truncated: "Esta página é longa demais para ser pesquisada por completo.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -224,6 +231,10 @@ export const ptBR = {
browserReserved:
"Seu navegador pode reservar essa combinação. No app para desktop ela funciona.",
actions: {
+ findInPage: {
+ label: "Localizar na página",
+ description: "Pesquisar o texto desta página",
+ },
openSettings: {
label: "Abrir configurações",
description: "Abrir a janela de configurações",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 36b73939726..8e293c30031 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -54,6 +54,13 @@ export const ru = {
shutdown: "Выключить",
},
shell: {
+ find: {
+ label: "Поиск на странице",
+ previous: "Предыдущее совпадение",
+ next: "Следующее совпадение",
+ close: "Закрыть поиск",
+ truncated: "Эта страница слишком длинная, чтобы выполнить поиск целиком.",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -224,6 +231,10 @@ export const ru = {
browserReserved:
"Браузер может оставить это сочетание себе. В настольном приложении оно работает.",
actions: {
+ findInPage: {
+ label: "Поиск на странице",
+ description: "Искать текст на этой странице",
+ },
openSettings: {
label: "Открыть настройки",
description: "Открыть окно настроек",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 4789c3b9bdf..3f7a016ccd0 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -50,6 +50,13 @@ export const zhCN = {
shutdown: "关闭服务",
},
shell: {
+ find: {
+ label: "在页面中查找",
+ previous: "上一个匹配项",
+ next: "下一个匹配项",
+ close: "关闭查找",
+ truncated: "此页面过长,无法搜索全部内容。",
+ },
beta: "BETA",
brand: "unsloth",
product: "Unsloth",
@@ -220,6 +227,10 @@ export const zhCN = {
browserReserved:
"浏览器可能会占用该组合键。桌面应用中可正常使用。",
actions: {
+ findInPage: {
+ label: "在页面中查找",
+ description: "搜索此页面上的文本",
+ },
openSettings: {
label: "打开设置",
description: "打开设置对话框",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 2ff0c4caf28..d5c00191ec8 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -3473,3 +3473,49 @@ html[data-chat-font] .aui-root {
animation: none !important;
transition: none !important;
}
+
+/* Find in page. The bar paints matches through the CSS Custom Highlight API,
+ so these two pseudo-elements are the whole visual: nothing is inserted into
+ the thread and nothing reflows when a match moves. An engine without the
+ registry falls back to selecting the active match.
+
+ Fixed colours in both themes, not palette tokens: a highlight has to stay
+ legible over body text, over a code fence with its own background, and over
+ a badge, and the accent colours move with the palette while that text does
+ not. `color` is set alongside the background because the API paints over
+ text of any colour. */
+::highlight(unsloth-find) {
+ background-color: #ffd84d;
+ color: #1a1a1a;
+}
+
+::highlight(unsloth-find-active) {
+ background-color: #ff8c1a;
+ color: #1a1a1a;
+}
+
+/* The find bar's surface: no border in either mode, so colour and shadow are
+ what separate it from the conversation.
+
+ Light is the chatbox's own background and shadow, so the panel a reader
+ summons over the conversation is made of the same material as the one they
+ type into. Dark cannot copy it: the composer sits at `--card` with no shadow,
+ because nothing overlaps it. This bar floats over cards that are themselves
+ `--card`, so it sits one step lighter, which also gives the ghost buttons
+ inside somewhere to go: their default `--muted/50` hover lands within a shade
+ of `--card` and reads as nothing. The shadow is the page background rather
+ than black, a halo that fades what passes underneath instead of a dark edge
+ around a panel that has given up its border. */
+.find-bar-surface {
+ background-color: #ffffff;
+ /* The composer's shadow spread wider and softened: that one sits at the
+ bottom of the page with nothing under it, this one floats over content and
+ needs more to sit on, but not more weight. Kept in step by
+ tests/find-in-page.test.ts. */
+ box-shadow: 0 3px 14px -1px rgba(0, 0, 0, 0.13);
+}
+
+.dark .find-bar-surface {
+ background-color: #2c2c2c;
+ box-shadow: 0 4px 20px 6px var(--background);
+}
diff --git a/studio/frontend/tests/find-in-page.test.ts b/studio/frontend/tests/find-in-page.test.ts
new file mode 100644
index 00000000000..447c0c3d7e5
--- /dev/null
+++ b/studio/frontend/tests/find-in-page.test.ts
@@ -0,0 +1,2298 @@
+// 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. What has to hold is that the flat index and the document agree: every offset the
+// search reports has to land on the character a reader sees, or the highlight paints over the wrong
+// word and the walk sends them somewhere they did not ask to go.
+//
+// There is no DOM library in this project. The runner is `node --test` and every sibling test that
+// needs a document hand-rolls one, which is what the flatten's structural types are for. The rest
+// of the DOM half is covered in smoke-find-in-page.tsx.
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import {
+ FIND_HIGHLIGHT,
+ FIND_HIGHLIGHT_ACTIVE,
+ MAX_PAINTED_RANGES,
+ mutatesSearchableText,
+ paintWindow,
+ resolvePortalSurfaces,
+ selectRangeFallback,
+} from "../src/features/find-in-page/lib/find-dom.ts";
+import {
+ BLOCK_SEPARATOR,
+ FIND_SKIP_ATTRIBUTE,
+ type FindElementLike,
+ type FindTextNodeLike,
+ MAX_INDEX_CHARS,
+ MAX_MATCHES,
+ MAX_NODE_CHARS,
+ PORTAL_RESERVE_CHARS,
+ buildTextIndex,
+ dropProbeFurthestFrom,
+ endPositionAt,
+ findMatches,
+ foldText,
+ normalizeQuery,
+ 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 ----------------------------------------------------------------------
+
+function text(data: string): FindTextNodeLike {
+ return { nodeType: 3, data };
+}
+
+function el(
+ tagName: string,
+ childNodes: (FindTextNodeLike | FindElementLike)[] = [],
+ attributes: Record<string, string> = {},
+): FindElementLike {
+ return {
+ nodeType: 1,
+ tagName,
+ childNodes,
+ getAttribute: (name) =>
+ Object.hasOwn(attributes, name) ? attributes[name] : null,
+ };
+}
+
+// --- the flatten -------------------------------------------------------------------------------
+
+test("inline markup does not break a word", () => {
+ // The case the whole feature turns on: markdown emphasis, code spans and links split a word
+ // across text nodes, and a find that searched node by node would not see it.
+ const root = el("DIV", [
+ el("P", [text("un"), el("EM", [text("sloth")]), text(" studio")]),
+ ]);
+ const index = buildTextIndex(root);
+ assert.equal(index.text, "unsloth studio");
+ assert.equal(findMatches(index, "unsloth").length, 1);
+});
+
+test("a block boundary stops a match running across it", () => {
+ const root = el("DIV", [
+ el("P", [text("the end")]),
+ el("P", [text("start of the next")]),
+ ]);
+ const index = buildTextIndex(root);
+ assert.equal(index.text, `the end${BLOCK_SEPARATOR}start of the next`);
+ // Neither the run-together form nor the spaced one: the two words are not adjacent on screen.
+ assert.deepEqual(findMatches(index, "endstart"), []);
+ assert.deepEqual(findMatches(index, "end start"), []);
+});
+
+test("no separator is written before the first character or after the last", () => {
+ const root = el("DIV", [el("P", [text("only")])]);
+ assert.equal(buildTextIndex(root).text, "only");
+});
+
+test("a subtree the walk must not read contributes nothing", () => {
+ for (const [tag, attributes] of [
+ ["SCRIPT", {}],
+ ["STYLE", {}],
+ ["TEXTAREA", {}],
+ // The bar itself, so the query typed into it is not a match of itself.
+ ["DIV", { [FIND_SKIP_ATTRIBUTE]: "" }],
+ // A workspace the shell parks off-route rather than unmounting.
+ ["DIV", { inert: "" }],
+ ["DIV", { hidden: "" }],
+ // The rest of the page for as long as a modal is up.
+ ["DIV", { "aria-hidden": "true" }],
+ ] as const) {
+ const root = el("DIV", [
+ el("P", [text("visible")]),
+ el(tag, [text("buried")], attributes),
+ ]);
+ const index = buildTextIndex(root);
+ assert.equal(
+ index.text.includes("buried"),
+ false,
+ `${tag} ${JSON.stringify(attributes)} leaked into the index`,
+ );
+ assert.equal(index.text.includes("visible"), true);
+ }
+});
+
+test("aria-hidden false does not hide a subtree", () => {
+ const root = el("DIV", [
+ el("P", [text("shown")], { "aria-hidden": "false" }),
+ ]);
+ assert.equal(buildTextIndex(root).text, "shown");
+});
+
+// --- offsets -----------------------------------------------------------------------------------
+
+test("an offset maps back to the node and character it came from", () => {
+ const first = text("Unsloth ");
+ const second = text("Studio");
+ const root = el("DIV", [el("P", [first, el("B", [second])])]);
+ const index = buildTextIndex(root);
+
+ const [match] = findMatches(index, "studio");
+ assert.ok(match);
+ const start = startPositionAt(index.segments, match.start);
+ const end = endPositionAt(index.segments, match.end);
+ assert.equal(start?.node, second);
+ assert.equal(start?.offset, 0);
+ // The match finishes the node, so the end boundary is its length -- the one offset no segment
+ // holds, and the one a Range needs there.
+ assert.equal(end?.node, second);
+ assert.equal(end?.offset, 6);
+});
+
+test("a match spanning two nodes ends in the second", () => {
+ const first = text("uns");
+ const second = text("loth");
+ const index = buildTextIndex(el("DIV", [el("P", [first, second])]));
+ const [match] = findMatches(index, "unsloth");
+ assert.ok(match);
+ assert.equal(startPositionAt(index.segments, match.start)?.node, first);
+ assert.equal(endPositionAt(index.segments, match.end)?.node, second);
+ assert.equal(endPositionAt(index.segments, match.end)?.offset, 4);
+});
+
+test("an offset on a separator belongs to no node", () => {
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text("a")]), el("P", [text("b")])]),
+ );
+ assert.equal(index.text.length, 3);
+ assert.equal(segmentAt(index.segments, 1), -1);
+ assert.equal(startPositionAt(index.segments, 1), null);
+});
+
+test("dotted I folds to a plain i, and the offsets still hold", () => {
+ // Its default fold is two code units, which one index character cannot stand for. The Turkic fold
+ // is a bare `i`, which fits and is what a search wants: the platform's own find matches all four
+ // spellings of Istanbul against a visible dotted one, and now so does this.
+ assert.equal("İ".toLowerCase().length, 2, "premise: the default fold grows");
+ assert.equal(foldText("İ"), "i");
+
+ const spellings = buildTextIndex(
+ el("DIV", [el("P", [text("Welcome to İstanbul")])]),
+ );
+ for (const query of ["istanbul", "İstanbul", "ISTANBUL", "Istanbul"]) {
+ assert.equal(findMatches(spellings, query).length, 1, query);
+ }
+
+ // And the offsets stay true, which is what folding it in place buys.
+ const marker = text("İ");
+ const after = text("Unsloth");
+ const index = buildTextIndex(el("DIV", [el("P", [marker, after])]));
+ const [match] = findMatches(index, "unsloth");
+ assert.ok(match);
+ const start = startPositionAt(index.segments, match.start);
+ assert.equal(start?.node, after);
+ assert.equal(start?.offset, 0);
+});
+
+test("an expanding fold does not change the letters around it", () => {
+ // Greek final sigma is decided by what follows it, so the fold of a run is not the folds of its
+ // code points strung together. One expanding character in a node used to force the per-code-point
+ // path for the whole run, turning every sigma in it into the wrong letter: text plainly on screen
+ // then matched nothing.
+ const dottedI = String.fromCharCode(0x0130); // Turkish dotted I, whose fold is two units
+ const greek = `\u039f\u0394\u039f\u03a3 ${dottedI} \u039f\u03a3`; // "ΟΔΟΣ İ ΟΣ"
+ const index = buildTextIndex(el("DIV", [el("P", [text(greek)])]));
+ // The length has to hold, or every offset after it maps to the wrong character.
+ assert.equal(index.text.length, greek.length);
+ assert.equal(index.segments[0].length, greek.length);
+ // Both sigmas are word-final here, and both fold to the one form a query folds to.
+ assert.equal(findMatches(index, "\u039f\u03a3").length, 2);
+ assert.equal(findMatches(index, "\u039f\u0394\u039f\u03a3").length, 1);
+ // And the character that would have grown is one plain `i`, still one wide.
+ assert.equal(index.text, "\u03bf\u03b4\u03bf\u03c3 i \u03bf\u03c3");
+});
+
+test("casing context carries across inline markup", () => {
+ // Split by an `<em>`, a word-final sigma folds medial per node and final over the run, so the two
+ // used to disagree about a word plainly on screen. Both sigmas now fold to one letter, which
+ // settles it whichever way the flatten arrives at the run.
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text("\u039f"), el("EM", [text("\u03a3")])])]),
+ );
+ assert.equal(index.text, "\u03bf\u03c3");
+ assert.equal(findMatches(index, "\u039f\u03a3").length, 1);
+ // The offset map still lands on the right nodes, which is what folding in place buys.
+ assert.equal(index.segments.length, 2);
+ assert.equal(index.segments[1].start, 1);
+});
+
+test("several dotted I in a run fold without drift", () => {
+ const dottedI = String.fromCharCode(0x0130);
+ const raw = `${dottedI}a${dottedI}\u039f\u03a3${dottedI}b`;
+ const index = buildTextIndex(el("DIV", [el("P", [text(raw)])]));
+ assert.equal(index.text.length, raw.length);
+ // Each one is a plain `i`, and the sigma between them still reads its own context: a cased letter
+ // follows it, so it stays medial.
+ assert.equal(index.text, "iai\u03bf\u03c3ib");
+});
+
+test("either sigma finds the other, whichever one is on screen", () => {
+ // `toLowerCase` picks the final form by position, so uppercase Greek ending in sigma folded one
+ // way and a query typed with the medial sigma folded the other, and half the spellings a reader
+ // can produce found nothing. Measured: chromium, firefox and webkit all match `ΟΣ` from either.
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text("\u039f\u0394\u039f\u03a3 \u039f\u03a3")])]),
+ );
+ for (const query of [
+ "\u03bf\u03c3", // medial, which is what a keyboard gives mid-word
+ "\u03bf\u03c2", // final, which is what it gives at the end of one
+ "\u039f\u03a3", // and the uppercase the document itself is written in
+ ]) {
+ assert.equal(
+ findMatches(index, query).length,
+ 2,
+ `${escape(query)} found nothing`,
+ );
+ }
+ // One letter in the index, so the offsets still stand for what is written.
+ const run = "\u03a3\u03a3\u03a3";
+ const sigmas = buildTextIndex(el("DIV", [el("P", [text(run)])]));
+ assert.equal(sigmas.text, "\u03c3\u03c3\u03c3");
+ assert.equal(sigmas.text.length, run.length);
+});
+
+test("a non-breaking space answers to the space key", () => {
+ // Spelled with a char code rather than pasted: a literal U+00A0 in a source file looks like a
+ // space to every reader and every diff, which is the confusion this guards against.
+ const nbsp = String.fromCharCode(0x00a0);
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text(`Unsloth${nbsp}Studio`)])]),
+ );
+ assert.equal(findMatches(index, "unsloth studio").length, 1);
+ // Substituted one for one, so every offset after it is untouched.
+ assert.equal(index.text.length, "Unsloth Studio".length);
+ assert.equal(index.text.includes(nbsp), false);
+});
+
+test("a dotted I does not make the rest of its run case-sensitive", () => {
+ // Its default fold grows, and giving up on the whole run for that left ordinary words in the
+ // same node unmatchable.
+ const index = buildTextIndex(el("DIV", [el("P", [text("HELLO İ")])]));
+ assert.equal(findMatches(index, "hello").length, 1);
+ // And the offsets still line up, which is what the whole-run fallback was protecting.
+ const [match] = findMatches(index, "hello");
+ assert.equal(startPositionAt(index.segments, match.start)?.offset, 0);
+});
+
+test("a text node bigger than its share contributes its prefix", () => {
+ // One Bash step's log arrives as one text node. Dropping it whole indexed nothing at all.
+ const node = text(`unsloth ${"x".repeat(MAX_NODE_CHARS + 10)}`);
+ const index = buildTextIndex(el("DIV", [el("P", [node])]));
+ assert.equal(index.truncated, true);
+ assert.equal(index.text.length, MAX_NODE_CHARS);
+ assert.equal(findMatches(index, "unsloth").length, 1);
+ // The prefix maps back to the node it came from, so a match in it is reachable.
+ assert.equal(startPositionAt(index.segments, 0)?.node, node);
+});
+
+test("an oversized node does not take the whole budget with it", () => {
+ // It used to: the node claimed every remaining character, the walk stopped, and the messages the
+ // reader was looking at were not in the index at all. A share each, and the walk goes on.
+ const log = el("PRE", [text("x".repeat(MAX_INDEX_CHARS + 1000))]);
+ const onScreen = el("P", [
+ text("the message in front of the reader says unsloth"),
+ ]);
+ const index = buildTextIndex(el("DIV", [log, onScreen]));
+ assert.equal(index.truncated, true);
+ assert.equal(findMatches(index, "in front of the reader").length, 1);
+ // The log is still there, up to its share.
+ assert.equal(index.text.startsWith("x".repeat(MAX_NODE_CHARS)), true);
+});
+
+test("a popover over a document at the ceiling is still searchable", () => {
+ // The workspace filling the budget used to end the walk, and the portal roots come after it, so
+ // the one surface the reader is actually looking at fell out of the index entirely. That is the
+ // case portal support exists for, so it gets a reserve rather than the leftovers.
+ const filler = Array.from({ length: 50 }, () =>
+ el("P", [text("x".repeat(MAX_NODE_CHARS))]),
+ );
+ const popover = el("DIV", [el("P", [text("a model named unsloth zephyr")])]);
+ const index = buildTextIndex(el("DIV", filler), [popover]);
+ assert.equal(index.truncated, true);
+ assert.equal(findMatches(index, "unsloth zephyr").length, 1);
+});
+
+test("the reserve is only held back when there is a portal to hold it for", () => {
+ // With nothing portaled the workspace gets the whole budget, so the ceiling means what it says.
+ const filler = Array.from({ length: 50 }, () =>
+ el("P", [text("x".repeat(MAX_NODE_CHARS))]),
+ );
+ const alone = buildTextIndex(el("DIV", filler));
+ assert.equal(alone.text.length, MAX_INDEX_CHARS);
+ // And with one, the workspace gives up only the reserve, not more.
+ const withPopover = buildTextIndex(el("DIV", filler), [
+ el("DIV", [el("P", [text("unsloth")])]),
+ ]);
+ assert.ok(
+ withPopover.text.length > MAX_INDEX_CHARS - PORTAL_RESERVE_CHARS,
+ `index was ${withPopover.text.length}`,
+ );
+ assert.ok(withPopover.text.length <= MAX_INDEX_CHARS);
+});
+
+test("an element the engine is not painting is skipped", () => {
+ // Attributes miss the common case: a responsive `hidden lg:flex` is a class.
+ const hidden = {
+ ...el("DIV", [text("buried")]),
+ checkVisibility: () => false,
+ };
+ const shown = { ...el("DIV", [text("shown")]), checkVisibility: () => true };
+ const index = buildTextIndex(el("DIV", [hidden, shown]));
+ assert.equal(index.text.includes("buried"), false);
+ assert.equal(index.text.includes("shown"), true);
+});
+
+// --- the search --------------------------------------------------------------------------------
+
+test("matching ignores case in both directions", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("Unsloth STUDIO")])]));
+ assert.equal(findMatches(index, "unsloth").length, 1);
+ assert.equal(findMatches(index, "Studio").length, 1);
+ assert.equal(findMatches(index, "sTuDiO").length, 1);
+});
+
+test("matches do not overlap", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("aaaa")])]));
+ assert.deepEqual(findMatches(index, "aa"), [
+ { start: 0, end: 2 },
+ { start: 2, end: 4 },
+ ]);
+});
+
+test("the match list stops at the limit it was given", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("aaaaaaaa")])]));
+ assert.equal(findMatches(index, "a", 3).length, 3);
+});
+
+test("an empty query matches nothing", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("unsloth")])]));
+ assert.deepEqual(findMatches(index, ""), []);
+ assert.equal(normalizeQuery(""), null);
+});
+
+test("a pasted separator cannot match across a block boundary", () => {
+ // Not typeable, but a paste could carry one, and it would otherwise match the very boundary the
+ // separator is there to keep closed.
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text("a")]), el("P", [text("b")])]),
+ );
+ assert.equal(normalizeQuery(`a${BLOCK_SEPARATOR}b`), null);
+ assert.deepEqual(findMatches(index, `a${BLOCK_SEPARATOR}b`), []);
+});
+
+test("content-visibility skipping is not treated as invisibility", () => {
+ // A `content-visibility: auto` subtree the reader has not scrolled to is SKIPPED, not hidden,
+ // and asking `checkVisibility` about that would drop the far half of a Hub README from the
+ // index. Nothing would put it back: scrolling renders the subtree without mutating the DOM.
+ const asked: unknown[] = [];
+ const probe = {
+ ...el("DIV", [text("readme")]),
+ checkVisibility: (options?: unknown) => {
+ asked.push(options);
+ return true;
+ },
+ };
+ const index = buildTextIndex(el("DIV", [probe]));
+ assert.equal(index.text.includes("readme"), true);
+ assert.equal(asked.length, 1);
+ assert.deepEqual(asked[0], {
+ contentVisibilityAuto: false,
+ opacityProperty: false,
+ checkOpacity: false,
+ visibilityProperty: true,
+ checkVisibilityCSS: true,
+ });
+});
+
+test("both spellings of every visibility option are asked for", () => {
+ // `visibilityProperty`/`opacityProperty` are renames of `checkVisibilityCSS`/`checkOpacity`, an
+ // engine reads only the name it knows, and Web IDL drops an unknown member silently. The modern
+ // name alone is a no-op on Chrome 105-120 and Firefox 106-121, which would then index and
+ // highlight `visibility: hidden` text.
+ const seen: Record<string, unknown>[] = [];
+ const probe = {
+ ...el("DIV", [text("readme")]),
+ checkVisibility: (options?: Record<string, unknown>) => {
+ if (options) seen.push(options);
+ return true;
+ },
+ };
+ buildTextIndex(el("DIV", [probe]));
+ assert.equal(seen.length, 1);
+ const options = seen[0];
+ for (const [modern, historic] of [
+ ["visibilityProperty", "checkVisibilityCSS"],
+ ["opacityProperty", "checkOpacity"],
+ ]) {
+ assert.equal(modern in options, true, `${modern} is missing`);
+ assert.equal(historic in options, true, `${historic} is missing`);
+ // The two names mean the same thing, so they must never disagree.
+ assert.equal(
+ options[modern],
+ options[historic],
+ `${modern} != ${historic}`,
+ );
+ }
+});
+
+test("an engine that honours only the historic option names still hides hidden text", () => {
+ // Simulates Chrome 105-120 / Firefox 106-121: `checkVisibility` exists, but the modern option
+ // names are unknown to it and therefore ignored.
+ const legacyEngine = (style: { visibility?: string }) => ({
+ checkVisibility: (options?: Record<string, unknown>) =>
+ !(options?.checkVisibilityCSS === true && style.visibility === "hidden"),
+ });
+ const hidden = {
+ ...el("SPAN", [text("invisible")]),
+ ...legacyEngine({ visibility: "hidden" }),
+ };
+ const index = buildTextIndex(el("DIV", [hidden]));
+ assert.equal(index.text.includes("invisible"), false);
+});
+
+test("an inline SVG is skipped despite reporting a lowercase tag", () => {
+ // Only HTML elements report their tag uppercased. SVG and MathML keep their source casing, so a
+ // Mermaid diagram's `<svg>` answers "svg" and walked past a set spelled in HTML casing, putting
+ // its labels in the index as matches a Range cannot reliably paint.
+ const svg = el("svg", [el("text", [text("mermaid label")])]);
+ const index = buildTextIndex(el("DIV", [svg, el("P", [text("prose")])]));
+ assert.equal(index.text.includes("mermaid"), false);
+ assert.equal(index.text.includes("prose"), true);
+});
+
+test("a portaled surface is indexed after the scope, behind a boundary", () => {
+ // A popover renders to the body, outside the scope, and a reader sees it as part of the page.
+ const scope = el("DIV", [el("P", [text("in the thread")])]);
+ const portal = el("DIV", [el("P", [text("in the popover")])]);
+ const index = buildTextIndex(scope, [portal]);
+ assert.equal(index.text, `in the thread${BLOCK_SEPARATOR}in the popover`);
+ assert.equal(findMatches(index, "in the popover").length, 1);
+ // Separate surfaces, so nothing runs out of one and into the other.
+ assert.deepEqual(findMatches(index, "thread in"), []);
+});
+
+test("every portaled surface is separated from the one before it", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("a")])]), [
+ el("DIV", [text("b")]),
+ el("DIV", [text("c")]),
+ ]);
+ assert.equal(index.text, `a${BLOCK_SEPARATOR}b${BLOCK_SEPARATOR}c`);
+});
+
+test("a portaled surface with nothing to contribute leaves no separator behind", () => {
+ // The boundary is pending until text follows it, so a surface that is skipped, or empty, does
+ // not leave a gap at the end of the index for a match to be measured against.
+ const scope = el("DIV", [el("P", [text("only")])]);
+ const index = buildTextIndex(scope, [
+ el("DIV", [text("parked")], { inert: "" }),
+ el("DIV"),
+ ]);
+ assert.equal(index.text, "only");
+});
+
+/** Run `body` with `getComputedStyle` answering from `styles`, and `{}` for anything else. */
+function withStyles(
+ styles: Map<
+ unknown,
+ {
+ display?: string;
+ visibility?: string;
+ whiteSpace?: string;
+ clip?: string;
+ clipPath?: string;
+ }
+ >,
+ body: () => void,
+): void {
+ const view = globalThis as { getComputedStyle?: unknown };
+ const saved = view.getComputedStyle;
+ view.getComputedStyle = (element: unknown) => styles.get(element) ?? {};
+ try {
+ body();
+ } finally {
+ view.getComputedStyle = saved;
+ }
+}
+
+// --- the observer's own filter -----------------------------------------------------------------
+
+/** The two bits of `Element` the filter touches, so a record can be handed over without a DOM. */
+function skipNode(options: {
+ skipped?: boolean;
+ /** Whatever takes this element out of the index, spelled as the selector spells it. */
+ mark?: string;
+ parent?: ReturnType<typeof skipNode> | null;
+}): {
+ nodeType: number;
+ parentElement: Element | null;
+ closest: (s: string) => Element | null;
+} {
+ const node = {
+ nodeType: 1,
+ mark:
+ options.mark ??
+ (options.skipped === true ? `[${FIND_SKIP_ATTRIBUTE}]` : null),
+ parent: options.parent ?? null,
+ get parentElement() {
+ return node.parent as unknown as Element | null;
+ },
+ closest(selector: string): Element | null {
+ let at: typeof node | null = node;
+ while (at) {
+ if (at.mark !== null && selector.includes(at.mark)) {
+ return at as unknown as Element;
+ }
+ at = at.parent as typeof node | null;
+ }
+ return null;
+ },
+ };
+ return node as unknown as ReturnType<typeof skipNode>;
+}
+
+function record(
+ target: ReturnType<typeof skipNode>,
+ type = "childList",
+ attributeName: string | null = null,
+) {
+ return { target, type, attributeName } as unknown as Parameters<
+ typeof mutatesSearchableText
+ >[0];
+}
+
+test("the selection fallback hands the caret back to the field", async () => {
+ // Moving the selection into ordinary text takes the caret with it on WebKit and Blink: the field
+ // still reports as active but every keystroke is swallowed, so the query freezes at one
+ // character. Measured with the registry removed, the field held "u" and never grew. This matters
+ // exactly where the fallback runs: Firefox below 140, or the desktop build's WebKitGTK.
+ const engine = await readFile(
+ new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),
+ "utf8",
+ );
+ const fallback = engine.slice(
+ engine.indexOf("export function selectRangeFallback"),
+ );
+ const body = fallback.slice(0, fallback.indexOf("\n}"));
+ assert.match(body, /holdCaret\(\)/);
+ assert.match(body, /releaseCaret\(/);
+ // The caret has to be taken BEFORE the selection moves and given back after, or there is nothing
+ // left to restore.
+ assert.ok(
+ body.indexOf("holdCaret()") < body.indexOf("selection.addRange"),
+ "the caret must be captured before the selection is moved",
+ );
+ assert.ok(
+ body.indexOf("releaseCaret(") > body.indexOf("selection.addRange"),
+ "the caret must be restored after the selection is moved",
+ );
+});
+
+test("a workspace generating off-route does not rebuild the index", () => {
+ // `__root.tsx` keeps Chat, Images, Video and Audio mounted under `hidden` and `inert` precisely
+ // so a long generation is not cancelled by navigating away, and they sit INSIDE the scope. Every
+ // character such a reply streams is a mutation the bar used to answer with a full flatten, which
+ // then correctly excluded that text: the whole rebuild was for nothing, once per throttle for as
+ // long as the generation ran.
+ for (const mark of ["[inert]", "[hidden]", '[aria-hidden="true"]']) {
+ const parked = skipNode({ mark });
+ const streamed = skipNode({ parent: parked });
+ assert.equal(
+ mutatesSearchableText(record(streamed, "characterData")),
+ false,
+ `a reply streaming under ${mark} still asked for a rebuild`,
+ );
+ }
+ // And an ordinary reply in the workspace on screen still does.
+ const live = skipNode({ parent: skipNode({}) });
+ assert.equal(mutatesSearchableText(record(live, "characterData")), true);
+});
+
+test("parking a workspace is itself a change, whichever attribute says so", () => {
+ // The same trap as the skip attribute below: `closest` matches the element it starts at, so the
+ // record announcing that a workspace just went `inert` would answer "inside skipped content" and
+ // be dropped, leaving the workspace the reader just left in the count.
+ for (const mark of ["[inert]", "[hidden]", '[aria-hidden="true"]']) {
+ const parked = skipNode({ mark, parent: skipNode({}) });
+ assert.equal(
+ mutatesSearchableText(record(parked, "attributes", "inert")),
+ true,
+ `${mark} being added was filtered out`,
+ );
+ }
+});
+
+test("adding the skip attribute is what reindexes, not only removing it", () => {
+ // `closest` matches where it starts, so the record announcing that an element became skippable
+ // answers "inside skipped content" and is thrown away, leaving the region counted and painted
+ // until some unrelated mutation happens by. Removal always worked, which is what hid this.
+ const parent = skipNode({});
+ const marked = skipNode({ skipped: true, parent });
+ assert.equal(
+ mutatesSearchableText(record(marked, "attributes", FIND_SKIP_ATTRIBUTE)),
+ true,
+ "gaining the attribute must schedule a rebuild",
+ );
+
+ const unmarked = skipNode({ skipped: false, parent });
+ assert.equal(
+ mutatesSearchableText(record(unmarked, "attributes", FIND_SKIP_ATTRIBUTE)),
+ true,
+ "losing the attribute must still schedule a rebuild",
+ );
+});
+
+test("ordinary mutations inside skipped content are still ignored", () => {
+ // The point of the filter: the bar floats inside the region it searches, so its own counter
+ // re-rendering must not order a re-index of itself.
+ const bar = skipNode({ skipped: true });
+ const inside = skipNode({ parent: bar });
+ assert.equal(mutatesSearchableText(record(inside)), false);
+ assert.equal(mutatesSearchableText(record(bar)), false);
+});
+
+test("a mutation in ordinary content always reindexes", () => {
+ const thread = skipNode({});
+ const message = skipNode({ parent: thread });
+ assert.equal(mutatesSearchableText(record(message)), true);
+ assert.equal(mutatesSearchableText(record(message, "characterData")), true);
+});
+
+test("a detached target counts as a change rather than being dropped", () => {
+ // No parent to ask, so the conservative answer is the safe one.
+ const orphan = skipNode({ skipped: true, parent: null });
+ assert.equal(
+ mutatesSearchableText(record(orphan, "attributes", FIND_SKIP_ATTRIBUTE)),
+ true,
+ );
+});
+
+test("an attribute that is not the skip flag is judged from the target itself", () => {
+ // Chrome stays chrome: `inert` flipping inside a skipped region is still skipped.
+ const bar = skipNode({ skipped: true });
+ const inside = skipNode({ parent: bar });
+ assert.equal(
+ mutatesSearchableText(record(inside, "attributes", "inert")),
+ false,
+ );
+});
+
+test("a display:contents wrapper that is itself invisible keeps its own text out", () => {
+ // `skipsSubtree` lets a boxless wrapper through on purpose, since `checkVisibility` calls
+ // anything with no box invisible and the shell wraps visible content in one. But `visibility`
+ // inherits and only ELEMENT children are re-checked, so a direct text child of a hidden
+ // `contents` wrapper was indexed, counted and painted while nobody could see it.
+ const ghost = el("SPAN", [text("invisible")]);
+ (ghost as { checkVisibility?: () => boolean }).checkVisibility = () => false;
+ withStyles(
+ new Map([[ghost, { display: "contents", visibility: "hidden" }]]),
+ () => {
+ const index = buildTextIndex(el("DIV", [ghost]));
+ assert.equal(index.text.includes("invisible"), false);
+ assert.deepEqual(findMatches(index, "invisible"), []);
+ },
+ );
+});
+
+test("a visible display:contents wrapper is still searched", () => {
+ // The other half: the rescue has to keep working, or most of what there is to search goes.
+ const wrapper = el("SPAN", [text("findable")]);
+ (wrapper as { checkVisibility?: () => boolean }).checkVisibility = () =>
+ false;
+ withStyles(new Map([[wrapper, { display: "contents" }]]), () => {
+ const index = buildTextIndex(el("DIV", [wrapper]));
+ assert.equal(index.text.includes("findable"), true);
+ assert.equal(findMatches(index, "findable").length, 1);
+ });
+});
+
+test("an element child that restores visibility inside a hidden contents wrapper is kept", () => {
+ // Scoped to the wrapper's OWN text: `visibility: visible` paints again and the walk does not
+ // turn back, so that child has to survive.
+ const inner = el("SPAN", [text("restored")]);
+ const ghost = el("SPAN", [text("invisible"), inner]);
+ (ghost as { checkVisibility?: () => boolean }).checkVisibility = () => false;
+ withStyles(
+ new Map<unknown, { display?: string; visibility?: string }>([
+ [ghost, { display: "contents", visibility: "hidden" }],
+ [inner, { display: "inline", visibility: "visible" }],
+ ]),
+ () => {
+ const index = buildTextIndex(el("DIV", [ghost]));
+ assert.equal(index.text.includes("invisible"), false);
+ assert.equal(index.text.includes("restored"), true);
+ },
+ );
+});
+
+test("the match window anchor is resolved only once the cap bites", () => {
+ // `viewportOffset` reads layout, and an argument is evaluated whether or not the callee wants
+ // it, so inline it ran on every keystroke however few matches there were. As a thunk it is paid
+ // only where it changes the answer: when the cap actually cuts the list short.
+ const index = buildTextIndex(el("P", [text("a a a a a a a a")]));
+
+ let asked = 0;
+ const anchor = () => {
+ asked += 1;
+ return 6;
+ };
+
+ const underCap = findMatches(index, "a", 100, anchor);
+ assert.equal(underCap.length, 8);
+ assert.equal(asked, 0, "an under-cap query must not read layout");
+
+ const capped = findMatches(index, "a", 3, anchor);
+ assert.equal(asked, 1, "a capped query resolves the anchor exactly once");
+ // A thunk and the number it returns must pick the same window.
+ assert.deepEqual(capped, findMatches(index, "a", 3, 6));
+});
+
+test("a decomposed dotted I is found by the ordinary query", () => {
+ // U+0130 decomposes to `I` + a combining dot, which folds to `i` + that dot. `i` + dot has no
+ // precomposed form, so NFC cannot put it back and the plain query missed a word on screen while
+ // the precomposed spelling of the same word matched.
+ const decomposed = "\u0049\u0307stanbul";
+ // The fold is what strands it: `I` + dot lowercases to `i` + dot, and THAT has no precomposed
+ // form, so no amount of normalizing the query reaches it.
+ assert.equal("\u0069\u0307".normalize("NFC"), "\u0069\u0307");
+ const index = buildTextIndex(el("P", [text(`Welcome to ${decomposed}`)]));
+ for (const query of ["istanbul", "ISTANBUL", "\u0130stanbul"]) {
+ assert.equal(findMatches(index, query).length, 1, query);
+ }
+});
+
+test("the dotted variant costs nothing on a document without combining marks", () => {
+ // It is only offered when the index carries a combining dot, so an ordinary thread keeps the
+ // single-variant `indexOf` path.
+ const index = buildTextIndex(el("P", [text("indexing is fine here")]));
+ assert.equal(findMatches(index, "indexing").length, 1);
+ assert.equal(findMatches(index, "i").length, 4);
+});
+
+test("a query too large to compile falls back instead of throwing", () => {
+ // Every engine caps the pattern size it will compile and the spec sets none, so there is no
+ // length that is right everywhere. Measured on V8: a whitespace-bearing query throws at 15,651
+ // characters, and the throw came out through the keystroke and took the bar down with it.
+ const index = buildTextIndex(el("P", [text("a small thread about unsloth")]));
+ const huge = "some log line with spaces ".repeat(4000);
+ assert.ok(huge.length > 15_651, "premise: past the measured V8 ceiling");
+ assert.doesNotThrow(() => findMatches(index, huge));
+ assert.deepEqual(findMatches(index, huge), []);
+});
+
+test("a needle longer than the haystack is rejected before any of the work", () => {
+ const index = buildTextIndex(el("P", [text("short")]));
+ assert.deepEqual(findMatches(index, "x".repeat(500)), []);
+ // Measured against the shortest spelling: a decomposed query is longer than the precomposed
+ // text it is meant to find, so the raw length is the wrong thing to test.
+ const cafe = buildTextIndex(el("P", [text("caf\u00e9")]));
+ assert.equal(findMatches(cafe, "cafe\u0301").length, 1);
+ // And a needle that still fits is unaffected.
+ assert.equal(findMatches(index, "short").length, 1);
+});
+
+test("a numeric anchor still means what it always did", () => {
+ // The thunk is additive. Every existing caller passes a number and must be unaffected.
+ const index = buildTextIndex(el("P", [text("b b b b b b b b")]));
+ assert.deepEqual(findMatches(index, "b", 3, 0), findMatches(index, "b", 3));
+ assert.deepEqual(
+ findMatches(index, "b", 3, 10),
+ findMatches(index, "b", 3, () => 10),
+ );
+});
+
+test("a word matches whichever way either side spells it", () => {
+ // The same word composed and decomposed. macOS hands back decomposed filenames while a model
+ // writes composed prose, so one thread holds both, and the platform's own find matches either
+ // from either. Measured: all four pairings hit.
+ const composed = "caf\u00e9";
+ const decomposed = "cafe\u0301";
+ assert.notEqual(composed, decomposed);
+ for (const written of [composed, decomposed]) {
+ for (const typed of [composed, decomposed]) {
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text(`a ${written} b`)])]),
+ );
+ const matches = findMatches(index, typed);
+ assert.equal(
+ matches.length,
+ 1,
+ `text ${escape(written)} and query ${escape(typed)} did not meet`,
+ );
+ // And the offsets are the document's, not a normalized copy's: the match has to cover
+ // exactly the characters that were written, whatever length that spelling is.
+ assert.deepEqual(matches[0], { start: 2, end: 2 + written.length });
+ assert.equal(index.text.slice(matches[0].start, matches[0].end), written);
+ }
+ }
+});
+
+test("an occurrence that mixes the two spellings is still one word", () => {
+ // Alternating whole spellings of the query only reaches text that is all-composed or
+ // all-decomposed. Joining two text nodes joins two sources, so one visible word can be neither,
+ // and then no spelling the query CAN be written in matches it. Every engine's own find reaches
+ // this: measured `true` on chromium, firefox and webkit for both all-composed and all-decomposed
+ // queries against a mixed occurrence.
+ const composed = "é";
+ const decomposed = "é";
+ const mixed = `caf${composed}caf${decomposed}`;
+ for (const typed of [
+ `caf${composed}caf${composed}`,
+ `caf${decomposed}caf${decomposed}`,
+ mixed,
+ ]) {
+ const index = buildTextIndex(el("DIV", [el("P", [text(`a ${mixed} b`)])]));
+ const matches = findMatches(index, typed);
+ assert.equal(
+ matches.length,
+ 1,
+ `query ${escape(typed)} missed a mixed word`,
+ );
+ // Still the document's own offsets, so the highlight covers what was written.
+ assert.deepEqual(matches[0], { start: 2, end: 2 + mixed.length });
+ assert.equal(index.text.slice(matches[0].start, matches[0].end), mixed);
+ }
+
+ // The shape that produces it here: one word, two inline nodes, one source each.
+ const split = buildTextIndex(
+ el("DIV", [el("P", [text(`caf${composed}`), text(`caf${decomposed}`)])]),
+ );
+ assert.equal(findMatches(split, `caf${composed}caf${composed}`).length, 1);
+});
+
+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.
+ const decomposed = "cafe\u0301";
+ const index = buildTextIndex(el("DIV", [el("P", [text(decomposed)])]));
+ assert.equal(index.text, decomposed);
+ assert.equal(index.text.length, decomposed.length);
+});
+
+test("spelling variants do not loosen whitespace inside a fence", () => {
+ // The variants share the pattern path with the flexible-whitespace one, and inside a `<pre>` the
+ // whitespace on screen is the whitespace in the node. A variant is exact; a flexed run is not.
+ const fence = el("PRE", [text("caf\u00e9 au lait")]);
+ withStyles(new Map([[fence, { whiteSpace: "pre" }]]), () => {
+ const index = buildTextIndex(el("DIV", [fence]));
+ assert.equal(findMatches(index, "caf\u00e9 au lait").length, 0);
+ assert.equal(findMatches(index, "cafe\u0301 au lait").length, 1);
+ });
+});
+
+test("an engine with no checkVisibility falls back to the computed properties", () => {
+ // `checkVisibility` landed in Safari 17.4, and WebKitGTK is already supported here: it is the
+ // engine `selectRangeFallback` exists for. The optional call answers undefined there, and read as
+ // "not false" that put every `display: none` subtree in the app back into the index.
+ for (const style of [
+ { display: "none" },
+ { visibility: "hidden" },
+ { visibility: "collapse" },
+ ]) {
+ const buried = el("DIV", [text("buried")]);
+ const root = el("DIV", [el("P", [text("visible")]), buried]);
+ withStyles(new Map([[buried, style]]), () => {
+ const index = buildTextIndex(root);
+ assert.equal(
+ index.text.includes("buried"),
+ false,
+ `${JSON.stringify(style)} leaked into the index`,
+ );
+ assert.equal(index.text.includes("visible"), true);
+ });
+ }
+});
+
+test("with no checkVisibility, a hidden boxless wrapper is still descended into", () => {
+ // Where the two mechanisms meet. `display: contents` is boxless rather than hidden, so the
+ // fallback must not skip it whole; `hidesOwnText` drops the text it holds directly, and a child
+ // that turns visibility back on is painted and still has to be found.
+ const shown = el("SPAN", [text("turned back on")]);
+ const wrapper = el("DIV", [text("the wrapper's own text"), shown]);
+ withStyles(
+ new Map([
+ [wrapper, { display: "contents", visibility: "hidden" }],
+ [shown, { visibility: "visible" }],
+ ]),
+ () => {
+ const index = buildTextIndex(el("DIV", [wrapper]));
+ assert.equal(index.text.includes("the wrapper"), false);
+ assert.equal(index.text.includes("turned back on"), true);
+ },
+ );
+});
+
+test("the fallback does not mistake a boxless wrapper for a hidden one", () => {
+ // `display: contents` is the case the whole visibility branch was written around: it has no box
+ // and is not hidden, and the shell hands a grid its children through one.
+ const wrapper = el("DIV", [el("P", [text("inside a wrapper")])]);
+ withStyles(new Map([[wrapper, { display: "contents" }]]), () => {
+ assert.equal(buildTextIndex(el("DIV", [wrapper])).text, "inside a wrapper");
+ });
+});
+
+test("two spans the CSS renders as blocks do not run together", () => {
+ // No tag name says these are blocks, and Tailwind stacks them all over the app: a source's title
+ // over its URL in the research panel is exactly this shape. Run together they invent a word that
+ // is on screen nowhere, under one highlight spanning two rows.
+ const first = el("SPAN", [text("Open")]);
+ const second = el("SPAN", [text("AI models")]);
+ withStyles(
+ new Map([
+ [first, { display: "block" }],
+ [second, { display: "block" }],
+ ]),
+ () => {
+ const index = buildTextIndex(el("DIV", [first, second]));
+ assert.equal(index.text.includes("openai"), false);
+ assert.deepEqual(findMatches(index, "openai"), []);
+ // Each row still matches on its own.
+ assert.equal(findMatches(index, "open").length, 1);
+ assert.equal(findMatches(index, "ai models").length, 1);
+ },
+ );
+ // An inline span is not a boundary, so markup inside a sentence still reads as one word.
+ const inline = el("SPAN", [text("slo")]);
+ withStyles(new Map([[inline, { display: "inline" }]]), () => {
+ const index = buildTextIndex(el("P", [text("un"), inline, text("th")]));
+ assert.equal(findMatches(index, "unsloth").length, 1);
+ });
+});
+
+test("whitespace is only flexible where the page collapses it", () => {
+ // The flexible run exists for prose, where a markdown soft wrap puts a newline in the node that
+ // renders as a space. In a code fence the whitespace on screen IS the whitespace in the node, so
+ // a query typed with one space must not land on three. The platform's own find draws the same
+ // line: matching across a wrap in a paragraph, and not inside a `<pre>`.
+ const fence = el("PRE", [text("unsloth fast")]);
+ const prose = el("P", [text("unsloth\n fast")]);
+ withStyles(
+ new Map([
+ [fence, { whiteSpace: "pre" }],
+ [prose, { whiteSpace: "normal" }],
+ ]),
+ () => {
+ const fenced = buildTextIndex(el("DIV", [fence]));
+ const wrapped = buildTextIndex(el("DIV", [prose]));
+ assert.deepEqual(findMatches(fenced, "unsloth fast"), []);
+ assert.equal(findMatches(fenced, "unsloth fast").length, 1);
+ // Prose is unchanged: one space still crosses the wrap.
+ assert.equal(findMatches(wrapped, "unsloth fast").length, 1);
+ // And the flag rides on the segment, not the element, so it survives the offset map.
+ assert.equal(fenced.segments[0].preserved, true);
+ assert.equal(wrapped.segments[0].preserved, false);
+ },
+ );
+});
+
+test("preserved whitespace is inherited by the nodes inside it", () => {
+ const fence = el("PRE", [el("CODE", [text("a b")])]);
+ withStyles(new Map([[fence, { whiteSpace: "pre" }]]), () => {
+ const index = buildTextIndex(el("DIV", [fence]));
+ // `CODE` gets `{}` from the fake, so this only passes if the walk carries the mode down.
+ assert.equal(index.segments[0].preserved, true);
+ assert.deepEqual(findMatches(index, "a b"), []);
+ });
+});
+
+test("a boxless wrapper is walked through, not skipped", () => {
+ // `display: contents` generates no box, and no box is the first thing `checkVisibility` calls
+ // invisible. The shell (sidebar.tsx) and the training page (studio-page.tsx) each wrap their
+ // content in one, so reading that answer as hidden empties the index for most of the app.
+ const wrapper = {
+ ...el("DIV", [el("P", [text("training")])]),
+ checkVisibility: () => false,
+ };
+ const collapsed = {
+ ...el("DIV", [el("P", [text("offscreen")])]),
+ checkVisibility: () => false,
+ };
+ const display = new Map<unknown, string>([
+ [wrapper, "contents"],
+ [collapsed, "none"],
+ ]);
+ const view = globalThis as { getComputedStyle?: unknown };
+ const saved = view.getComputedStyle;
+ view.getComputedStyle = (element: unknown) => ({
+ display: display.get(element) ?? "block",
+ });
+ try {
+ const index = buildTextIndex(el("DIV", [wrapper, collapsed]));
+ assert.equal(index.text.includes("training"), true);
+ // A wrapper with a box that says invisible is still hidden.
+ assert.equal(index.text.includes("offscreen"), false);
+ } finally {
+ view.getComputedStyle = saved;
+ }
+});
+
+test("a query spanning whitespace matches the phrase as it renders", () => {
+ // HTML collapses runs of whitespace, so a markdown paragraph soft-wrapped mid-sentence renders
+ // as one line while its text node still holds the newline.
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text("A soft wrapped\n phrase about unsloth.")])]),
+ );
+ assert.equal(findMatches(index, "wrapped phrase").length, 1);
+ // The match is as wide as the run it covered, so the highlight lands on the whole phrase.
+ const [match] = findMatches(index, "wrapped phrase");
+ assert.equal(match.end - match.start, "wrapped\n phrase".length);
+});
+
+test("a query spanning whitespace still cannot cross a block boundary", () => {
+ const index = buildTextIndex(
+ el("DIV", [el("P", [text("the end")]), el("P", [text("start here")])]),
+ );
+ assert.deepEqual(findMatches(index, "end start"), []);
+});
+
+test("a regex metacharacter in a query is a literal", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("a.b and axb c")])]));
+ // Only reaches the pattern path because of the space, which is the point.
+ assert.equal(findMatches(index, "a.b and").length, 1);
+ assert.deepEqual(findMatches(index, "axb and"), []);
+});
+
+// --- the bounds --------------------------------------------------------------------------------
+
+test("a document past the ceiling is flattened as far as it goes and says so", () => {
+ const chunk = "x".repeat(100_000);
+ const paragraphs = Array.from({ length: 60 }, () => el("P", [text(chunk)]));
+ const index = buildTextIndex(el("DIV", paragraphs));
+ assert.equal(index.truncated, true);
+ assert.ok(index.text.length <= MAX_INDEX_CHARS);
+ // What was read is still usable, which is the point of stopping rather than giving up.
+ assert.ok(index.segments.length > 0);
+ assert.ok(findMatches(index, "xxx").length > 0);
+});
+
+test("a clipped node does not run into the next one", () => {
+ // What the clip threw away is still in the document. Without a boundary the retained prefix and
+ // the next node touch, a query across the seam matches, and the Range it maps back to spans every
+ // discarded character in between: measured at 8503 characters of unrelated highlight.
+ const clipped = text(
+ `${"x".repeat(MAX_NODE_CHARS)}${"discarded ".repeat(500)}`,
+ );
+ const next = text("yz");
+ const index = buildTextIndex(el("DIV", [el("P", [clipped, next])]));
+ assert.equal(index.truncated, true);
+ assert.deepEqual(findMatches(index, "xy"), []);
+ // The separator is what closes it, and both sides are still findable on their own.
+ assert.equal(index.text.includes(BLOCK_SEPARATOR), true);
+ assert.equal(findMatches(index, "yz").length, 1);
+});
+
+test("the ceiling holds across a block boundary", () => {
+ // A node landing exactly on the ceiling used to let the next block's separator push `length`
+ // past it, and the negative `room` that followed made `slice(0, room)` take all but the last
+ // character of the following node: a 500,000 character overshoot on a 4,000,000 cap.
+ // Filled a node at a time now that no single one may take the lot, landing exactly on the cap.
+ const blocks = Array.from({ length: MAX_INDEX_CHARS / MAX_NODE_CHARS }, () =>
+ el("P", [text("x".repeat(MAX_NODE_CHARS))]),
+ );
+ const index = buildTextIndex(
+ el("DIV", [...blocks, el("P", [text("y".repeat(500_000))])]),
+ );
+ assert.equal(index.text.length, MAX_INDEX_CHARS);
+ assert.equal(index.truncated, true);
+ assert.deepEqual(findMatches(index, "yyy", 5), []);
+});
+
+test("nothing lands past the ceiling however the walk arrives at it", () => {
+ // Every shape that reaches the cap: one oversized node, many small ones, and a boundary in the
+ // middle. None may report an index longer than the cap it was given.
+ const shapes = [
+ [el("P", [text("x".repeat(MAX_INDEX_CHARS + 1_000))])],
+ Array.from({ length: 9 }, () => el("P", [text("x".repeat(500_000))])),
+ [
+ el("P", [text("x".repeat(MAX_INDEX_CHARS - 1))]),
+ el("P", [text("y".repeat(1_000))]),
+ ],
+ ];
+ for (const [i, children] of shapes.entries()) {
+ const index = buildTextIndex(el("DIV", children));
+ assert.ok(
+ index.text.length <= MAX_INDEX_CHARS,
+ `shape ${i} indexed ${index.text.length}, past the ${MAX_INDEX_CHARS} cap`,
+ );
+ assert.equal(index.truncated, true, `shape ${i} did not report truncation`);
+ }
+});
+
+test("a document inside the ceiling is not marked truncated", () => {
+ const index = buildTextIndex(el("DIV", [el("P", [text("unsloth")])]));
+ assert.equal(index.truncated, false);
+});
+
+// --- the probe over the cap --------------------------------------------------------------------
+
+/** One node holding `count` occurrences of "x", each at its own offset. */
+function documentOfMatches(count: number): FindElementLike {
+ return el("DIV", [text("x-".repeat(count))]);
+}
+
+/** What `search` does: ask for one over the cap, remember the anchor, then trim. */
+function walkAsTheHookDoes(
+ index: ReturnType<typeof buildTextIndex>,
+ at: number,
+) {
+ let anchoredAt: number | null = null;
+ const matches = findMatches(index, "x", MAX_MATCHES + 1, () => {
+ anchoredAt = at;
+ return at;
+ });
+ const capped = matches.length > MAX_MATCHES;
+ if (capped) dropProbeFurthestFrom(matches, anchoredAt);
+ return { matches, capped };
+}
+
+test("the last match in the document is reachable from the bottom of it", () => {
+ // The probe asked for over the cap used to come off the tail unconditionally. Once the reader is
+ // far enough down the window IS the tail, so that threw away the occurrence beside them.
+ const index = buildTextIndex(documentOfMatches(MAX_MATCHES + 1_000));
+ const all = findMatches(index, "x", Number.POSITIVE_INFINITY, 0);
+ const last = all[all.length - 1].start;
+
+ const { matches, capped } = walkAsTheHookDoes(index, index.text.length);
+ assert.equal(capped, true);
+ assert.equal(matches.length, MAX_MATCHES);
+ assert.ok(
+ matches.some((match) => match.start === last),
+ "the final occurrence must still be walkable",
+ );
+});
+
+test("the first match is still reachable from the top, which is the case that worked", () => {
+ const index = buildTextIndex(documentOfMatches(MAX_MATCHES + 1_000));
+ const { matches } = walkAsTheHookDoes(index, 0);
+ assert.equal(matches.length, MAX_MATCHES);
+ assert.equal(matches[0].start, 0);
+});
+
+test("the window holds the match nearest the reader, wherever they are", () => {
+ const index = buildTextIndex(documentOfMatches(MAX_MATCHES + 2_500));
+ const all = findMatches(index, "x", Number.POSITIVE_INFINITY, 0);
+ for (const fraction of [0, 0.25, 0.5, 0.75, 1]) {
+ const at = Math.floor(index.text.length * fraction);
+ const nearest =
+ all.find((match) => match.start >= at) ?? all[all.length - 1];
+ const { matches } = walkAsTheHookDoes(index, at);
+ assert.ok(
+ matches.some((match) => match.start === nearest.start),
+ `the match beside the reader is missing at ${fraction}`,
+ );
+ }
+});
+
+test("the trim takes the far end, and the tail when there is no anchor to judge by", () => {
+ const window = () => [
+ { start: 100, end: 101 },
+ { start: 200, end: 201 },
+ { start: 300, end: 301 },
+ ];
+ const above = window();
+ dropProbeFurthestFrom(above, 320, 2);
+ assert.deepEqual(
+ above.map((match) => match.start),
+ [200, 300],
+ "a reader past the window gives up the head",
+ );
+
+ const below = window();
+ dropProbeFurthestFrom(below, 90, 2);
+ assert.deepEqual(
+ below.map((match) => match.start),
+ [100, 200],
+ "a reader above the window gives up the tail",
+ );
+
+ const unanchored = window();
+ dropProbeFurthestFrom(unanchored, null, 2);
+ assert.deepEqual(
+ unanchored.map((match) => match.start),
+ [100, 200],
+ "no anchor resolved means the window started at the top",
+ );
+});
+
+// --- the paint window --------------------------------------------------------------------------
+
+test("every match is painted while there are few enough of them", () => {
+ assert.deepEqual(paintWindow(12, 4, 400), { from: 0, to: 12 });
+});
+
+test("the paint window is capped and always holds the active match", () => {
+ const total = 5_000;
+ for (const active of [0, 1, 199, 200, 2_500, 4_799, 4_998, 4_999]) {
+ const { from, to } = paintWindow(total, active, MAX_PAINTED_RANGES);
+ assert.equal(to - from, MAX_PAINTED_RANGES, `width at ${active}`);
+ assert.ok(from >= 0 && to <= total, `bounds at ${active}`);
+ assert.ok(
+ active >= from && active < to,
+ `active ${active} fell outside ${from}..${to}`,
+ );
+ }
+});
+
+/** The body of one CSS rule, for the tests that pin the bar to the composer. */
+function cssRule(css: string, selector: string): string {
+ const at = css.indexOf(`${selector} {`);
+ assert.notEqual(at, -1, `${selector} is gone`);
+ return css.slice(at, css.indexOf("}", at));
+}
+
+// --- the wiring --------------------------------------------------------------------------------
+
+test("the stylesheet paints the two highlights the code registers", async () => {
+ const css = await readFile(
+ new URL("../src/index.css", import.meta.url),
+ "utf8",
+ );
+ for (const name of [FIND_HIGHLIGHT, FIND_HIGHLIGHT_ACTIVE]) {
+ assert.ok(
+ css.includes(`::highlight(${name})`),
+ `${name} is registered but never painted`,
+ );
+ }
+});
+
+test("the bar keeps itself out of the region it searches", async () => {
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(bar, new RegExp(`${FIND_SKIP_ATTRIBUTE}=`));
+ // And the mutation filter reads the same attribute, so the counter re-rendering does not order a
+ // re-index of the conversation.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /FIND_SKIP_ATTRIBUTE/);
+});
+
+test("light mode is the chatbox's background, under a slightly heavier shadow", async () => {
+ const css = await readFile(
+ new URL("../src/index.css", import.meta.url),
+ "utf8",
+ );
+ const composer = cssRule(css, ".unsloth-composer-surface");
+ const bar = cssRule(css, ".find-bar-surface");
+
+ // The composer is the reference, not a copied colour: if it restyles, this fails rather than
+ // leaving the one floating panel a shade off from the one below it.
+ const background = /background-color:\s*(#[0-9a-f]{6});/i.exec(composer);
+ assert.ok(background);
+ assert.match(bar, new RegExp(`background-color:\\s*${background[1]};`, "i"));
+
+ // The shadow is the composer's, spread wider and softened: that one sits at the bottom of the
+ // page with nothing under it, this one floats over content and needs more to sit on, not more
+ // weight.
+ const shape = (rule: string) => {
+ const hit =
+ /box-shadow:\s*0 (\d+)px (\d+)px (-?\d+)px rgba\(0, 0, 0, ([\d.]+)\);/.exec(
+ rule,
+ );
+ assert.ok(hit, "box-shadow is not in the shape this test reads");
+ return {
+ y: Number(hit[1]),
+ blur: Number(hit[2]),
+ spread: Number(hit[3]),
+ alpha: Number(hit[4]),
+ };
+ };
+ const from = shape(composer);
+ const to = shape(bar);
+ assert.ok(
+ to.blur > from.blur,
+ `blur ${to.blur} is not wider than ${from.blur}`,
+ );
+ assert.ok(
+ to.spread > from.spread,
+ `spread ${to.spread} is not wider than ${from.spread}`,
+ );
+ // Wider, never heavier: the width is what lifts it off the page, not the ink.
+ assert.ok(
+ to.alpha < from.alpha,
+ `alpha ${to.alpha} is not softer than ${from.alpha}`,
+ );
+ // But still a shadow, and still in the composer's family.
+ assert.ok(
+ to.alpha >= from.alpha * 0.7,
+ `alpha ${to.alpha} has faded to nothing`,
+ );
+ assert.ok(
+ to.blur <= from.blur * 2,
+ `blur ${to.blur} is more than slightly wider`,
+ );
+ assert.ok(to.y >= from.y);
+});
+
+test("dark mode sits above the cards it floats over", async () => {
+ const css = await readFile(
+ new URL("../src/index.css", import.meta.url),
+ "utf8",
+ );
+ const value = (selector: string, property: string) => {
+ const hit = new RegExp(`${property}:\\s*([^;]+);`).exec(
+ cssRule(css, selector),
+ );
+ assert.ok(hit, `${selector} has no ${property}`);
+ return hit[1].trim();
+ };
+ const grey = (hex: string) => Number.parseInt(hex.slice(1, 3), 16);
+ // The thread's message cards are `--card`. A bar at that value dissolves into whatever scrolls
+ // under it, so it sits above them, and below `--border`, past which it reads as an edge.
+ const bar = grey(value(".dark .find-bar-surface", "background-color"));
+ const card = grey(value(".dark", "--card"));
+ const border = grey(value(".dark", "--border"));
+ assert.ok(bar > card, `bar ${bar} is not lighter than --card ${card}`);
+ assert.ok(bar < border, `bar ${bar} is not darker than --border ${border}`);
+ // And a halo in the page background, not a dark edge around a borderless panel.
+ assert.match(
+ value(".dark .find-bar-surface", "box-shadow"),
+ /var\(--background\)/,
+ );
+});
+
+test("the bar stays out of a backgrounded scope, and off the document origin", async () => {
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Every modal, not just Settings: Radix marks the shell aria-hidden for as long as one is up,
+ // and `enabled` is read at render, which a dialog opening need not cause.
+ assert.match(
+ bar,
+ /isSurfaceBackgrounded\(`\[\$\{FIND_SCOPE_ATTRIBUTE\}\]`\)/,
+ );
+ // Fixed, not absolute: on a route whose outer container scrolls, an absolutely positioned bar
+ // sits at the top of a scope taller than the window and scrolls out of reach.
+ const surface = /className="(find-bar-surface[^"]*)"/.exec(bar);
+ assert.ok(surface);
+ assert.match(surface[1], /\bfixed\b/);
+ 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\)\]/);
+});
+
+test("the reveal looks again while the scroll is still moving", async () => {
+ // A `content-visibility: auto` subtree contributes its placeholder height to scrollHeight until
+ // it renders, so the first scroll is clamped short and reaching toward the block is what makes it
+ // render. Measured in a real viewport: 3415px short on all three engines without this. The node
+ // suite cannot see a scroll, so what is pinned here is the shape the browser harness relies on.
+ const dom = await readFile(
+ new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),
+ "utf8",
+ );
+ // The scroll reports whether it moved anything, which is the whole signal.
+ assert.match(
+ dom,
+ /export function scrollRangeIntoView\(range: Range\): boolean/,
+ );
+ const reveal = dom.slice(dom.indexOf("function revealPass("));
+ const body = reveal.slice(0, reveal.indexOf("\n}\n"));
+ // Stops as soon as a pass moves nothing, and is bounded so nothing can spin.
+ assert.match(
+ body,
+ /if \(!scrollRangeIntoView\(range\) \|\| tries <= 1\) return;/,
+ );
+ assert.match(body, /tries - 1/);
+ assert.match(dom, /revealRangeWhenPainted\(range: Range, tries = \d\)/);
+ // Next frame, not a timer: what is being waited for is a paint.
+ assert.match(body, /requestAnimationFrame\(/);
+ // And a range whose nodes a streaming reply has replaced is dropped rather than scrolled to.
+ assert.match(body, /range\.startContainer\.isConnected/);
+ // The engine asks for the retrying one, or the second look never happens.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /revealRangeWhenPainted\(activeRange\)/);
+ assert.equal(/scrollRangeIntoView\(activeRange\)/.test(engine), false);
+});
+
+test("a dismissed or superseded search abandons its queued reveal passes", async () => {
+ // The reveal chain walks up to seven more frames after the first scroll. The workspace stays
+ // mounted when the bar closes, so `isConnected` stays true and the old chain would keep scrolling
+ // the reader toward a match they already dismissed. A generation token retires it.
+ const dom = await readFile(
+ new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),
+ "utf8",
+ );
+ // Every new reveal retires the previous one, so two navigations cannot scroll against each other.
+ const entry = dom.slice(
+ dom.indexOf("export function revealRangeWhenPainted"),
+ );
+ assert.match(
+ entry.slice(0, entry.indexOf("\n}\n")),
+ /cancelRevealPasses\(\)/,
+ );
+ // And the queued frame checks the token it was queued under before scrolling again.
+ const pass = dom.slice(dom.indexOf("function revealPass("));
+ assert.match(
+ pass.slice(0, pass.indexOf("\n}\n")),
+ /if \(generation !== revealGeneration\) return;/,
+ );
+ // Teardown retires the chain: closing the bar is exactly when the reader stops asking to move.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /cancelRevealPasses\(\);/);
+});
+
+test("a query too large to compile falls back instead of throwing on the first scan", () => {
+ // V8 compiles a regex lazily, so an oversized pattern is accepted by the constructor and throws
+ // `SyntaxError` on the first `exec` instead. Guarding only the constructor left the throw coming
+ // out through the keystroke that caused it, which tears the bar out of the DOM. Whitespace is
+ // what gets a query there: every run becomes `\\s+`, so a spaced paste doubles on the way in.
+ const index = buildTextIndex(el("DIV", [el("P", [text("b".repeat(60000))])]));
+ // Longer than the compiler will take once the whitespace flexes, shorter than the haystack, so
+ // the length guard cannot short-circuit it before the pattern is built.
+ const query = "a ".repeat(10000).trim();
+ assert.ok(query.length < index.text.length);
+ // The premise: this pattern really does survive construction and die on use.
+ const escaped = query.replace(/\s+/g, "\\s+");
+ let lazy = false;
+ try {
+ new RegExp(escaped, "g").exec("");
+ } catch {
+ lazy = true;
+ }
+ assert.equal(
+ lazy,
+ true,
+ "premise: the pattern throws at compile-on-first-use",
+ );
+ // No throw, and no matches: the literal scan is exact, so a spaced query simply finds nothing.
+ assert.deepEqual(findMatches(index, query, 10), []);
+});
+
+test("a match with no geometry is aimed at through its nearest laid-out ancestor", async () => {
+ const dom = await readFile(
+ new URL("../src/features/find-in-page/lib/find-dom.ts", import.meta.url),
+ "utf8",
+ );
+ // Text inside a skipped subtree has a collapsed rect while the subtree's own box keeps its
+ // placeholder geometry, so the walk aims at that instead of giving up.
+ assert.match(
+ dom,
+ /export function revealRect\(range: Range\): DOMRect \| null/,
+ );
+ assert.match(dom, /export function rangeTop\(range: Range\): number \| null/);
+ // And both readers go through it rather than reading the range rect directly.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /const top = rangeTop\(range\);/);
+ assert.equal(/range\.getBoundingClientRect\(\)/.test(engine), false);
+});
+
+test("a fresh query starts from the scroll container's top, not the window's", async () => {
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // The thread viewport starts below the navbar and the chat header, so a match clipped just off
+ // the top of it still has a positive window-relative `top`.
+ assert.match(engine, /top >= scrollViewportTop\(range\)/);
+ assert.equal(/top >= 0/.test(engine), false);
+});
+
+test("re-indexing while the document changes is a throttle, and says so", async () => {
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // A debounce would leave the count frozen and new text unfindable for as long as a reply takes
+ // to write. The name has to match the behaviour, which is what went wrong before.
+ assert.match(engine, /REINDEX_INTERVAL_MS/);
+ assert.equal(/REINDEX_DEBOUNCE_MS/.test(engine), false);
+ assert.match(engine, /A throttle rather than a debounce/);
+});
+
+test("the bar has no border, and its buttons have a hover that shows", async () => {
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const surface = /className="(find-bar-surface[^"]*)"/.exec(bar);
+ assert.ok(surface, "the bar no longer wears the shared surface class");
+ assert.equal(
+ /\bborder\b/.test(surface[1]),
+ false,
+ "the bar took a border back",
+ );
+ // The ghost variant's own `--muted/50` hover lands within a shade of this surface, so every
+ // button in the bar overrides it.
+ assert.match(bar, /hover:bg-black\/\[0\.06\] dark:hover:bg-white\/10/);
+ assert.equal((bar.match(/className=\{FIND_BUTTON_CLASS\}/g) ?? []).length, 3);
+});
+
+test("a long query rewinds to its first character when focus leaves", async () => {
+ // Typing past the width of the field scrolls it, and a bar left showing the tail of a word says
+ // nothing about what was searched for.
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(bar, /onBlur=\{rewindToStart\}/);
+ assert.match(bar, /input\.setSelectionRange\(0, 0\);/);
+ assert.match(bar, /input\.scrollLeft = 0;/);
+ // The walk buttons must not trigger it: they cancel their own mousedown, so the field never
+ // loses focus and the caret stays where the reader left it.
+ assert.match(bar, /onMouseDown=\{keepFocusInField\}/);
+});
+
+test("the observer watches the attributes a workspace switch flips", async () => {
+ // Chat and Images are both kept alive by the shell, so switching between them adds and removes
+ // nothing -- it flips `inert`. A childList observer would never hear it, and the bar would go on
+ // counting the workspace the user just left.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /attributeFilter: \[[^\]]*"inert"/);
+ // `open` too: toggling a `<details>` changes that and nothing else, while the body inside it
+ // goes from visible to not, so a collapsible opened after indexing would stay unfindable.
+ assert.match(engine, /attributeFilter: \[[^\]]*"open"/);
+ // And not the whole attribute stream: `class` changes on every hover. Scanned rather than
+ // matched, since the comments in between make a regex for this one backtrack badly.
+ const opensAttributes = engine.indexOf("attributes: true,");
+ const opensFilter = engine.indexOf("attributeFilter:", opensAttributes);
+ assert.ok(opensAttributes !== -1 && opensFilter > opensAttributes);
+ const between = engine.slice(
+ opensAttributes + "attributes: true,".length,
+ opensFilter,
+ );
+ assert.equal(
+ between
+ .split("\n")
+ .every((line) => line.trim() === "" || line.trim().startsWith("//")),
+ true,
+ "nothing else is being observed between the flag and its filter",
+ );
+ assert.equal(engine.includes('attributeFilter: ["class"'), false);
+});
+
+/** Stand in for the document `resolvePortalSurfaces` queries: node has no version of one. */
+function withPortals<T>(surfaces: Element[], body: () => T): T {
+ const view = globalThis as { document?: unknown };
+ const had = "document" in view;
+ const saved = view.document;
+ view.document = { querySelectorAll: () => surfaces };
+ try {
+ return body();
+ } finally {
+ if (had) view.document = saved;
+ else delete view.document;
+ }
+}
+
+/** A portaled surface, which is asked only what state it is in and what it contains. */
+function surface(state: string | null, children: Element[] = []): Element {
+ const node = {
+ getAttribute: (name: string) => (name === "data-state" ? state : null),
+ contains: (other: Element) => other === node || children.includes(other),
+ };
+ return node as unknown as Element;
+}
+
+test("a portaled surface is searched unless it is on its way out", () => {
+ const open = surface("open");
+ const closing = surface("closed");
+ // A plain menu, which says nothing about its state because it is only rendered while open.
+ const plain = surface(null);
+ const scope = { contains: () => false } as unknown as Element;
+ assert.deepEqual(
+ withPortals([open, closing, plain], () => resolvePortalSurfaces(scope)),
+ [open, plain],
+ );
+});
+
+test("a surface inside the scope, or inside one already taken, is not indexed twice", () => {
+ const inner = surface("open");
+ const outer = surface("open", [inner]);
+ const own = surface("open");
+ const scope = {
+ contains: (other: Element) => other === own,
+ } as unknown as Element;
+ assert.deepEqual(
+ withPortals([own, outer, inner], () => resolvePortalSurfaces(scope)),
+ [outer],
+ );
+});
+
+test("the observer watches the document, since a portal lands outside the scope", async () => {
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // A popover renders to the body: an observer on the scope alone never hears one open or close.
+ assert.match(engine, /scope\?\.ownerDocument\?\.body \?\? scope/);
+ // And `data-state` is the only thing a dismissed one changes. It keeps its box until the
+ // animation that follows finishes, so without this it stays in the count after it is gone.
+ assert.match(engine, /attributeFilter: \[[^\]]*"data-state"/);
+});
+
+test("the rows progressive completion adds are re-anchored, not renumbered", async () => {
+ // Streaming APPENDS, so keeping the ordinal is right there. Progressive completion PREPENDS the
+ // older half of a thread, and match 3 of the tail is not match 3 of the whole conversation:
+ // keeping the number moves the highlight to an older match off screen, and the next step from
+ // there walks the reader backwards.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ engine,
+ /completeProgressiveMounts\([\s\S]*?\.then\(\(\) => \{[\s\S]*?search\(false, reindex\(\)\);/,
+ );
+ // Through `reindex`, which answers false when the completion brought nothing in, so a settled
+ // thread's 400ms probe does not take back an Enter pressed while it ran.
+ assert.equal(engine.includes("rebuild("), false);
+});
+
+test("Escape closes the bar from the walk buttons, not just the field", async () => {
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // On the WINDOW, in the capture phase, for the lifetime of the open bar. A handler on the bar
+ // only reaches presses that started inside it, so clicking a message to read it left a bar
+ // Escape would not close -- and with a tool request waiting, that same unprevented Escape went
+ // on to `declineToolRequest`, which is bare Escape and is not shielded by `isTextEntryFocused`
+ // on a message body. Closing a find bar must not be able to answer a tool request.
+ const effect = bar.slice(bar.indexOf("const onEscape ="));
+ const body = effect.slice(0, effect.indexOf("window.addEventListener"));
+ assert.match(body, /event\.key !== "Escape"/);
+ assert.match(body, /event\.preventDefault\(\);/);
+ assert.match(body, /event\.stopPropagation\(\);/);
+ assert.match(body, /close\(\);/);
+ // Capture, so it runs ahead of the registry's own keydown listener rather than racing it.
+ assert.match(effect, /window\.addEventListener\("keydown", onEscape, true\)/);
+ assert.match(
+ effect,
+ /window\.removeEventListener\("keydown", onEscape, true\)/,
+ );
+ // 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\(/);
+ // 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(
+ landmark.slice(0, landmark.indexOf(">")).includes("onKeyDown"),
+ false,
+ );
+});
+
+test("only threads this search can read are forced to finish mounting", async () => {
+ // The shell keeps every workspace mounted and marks the off-route ones `inert`. Completing
+ // globally would make a retained conversation mount every row it withheld, on a route where the
+ // walk then skips all of it.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ engine,
+ /completeProgressiveMounts\(\(viewport\) =>\s*\n?\s*indexReaches\(scope, viewport\)/,
+ );
+ const progressive = await readFile(
+ new URL(
+ "../src/components/assistant-ui/progressive-messages.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // The loop's exit has to read the filtered set too, or a completer this caller declined holds it
+ // open forever.
+ assert.match(
+ progressive,
+ /if \(wanted\(\)\.length === 0 && \(observed \|\| Date\.now\(\) >= deadline\)\)/,
+ );
+});
+
+test("the chord is left to the browser when the scope is behind a modal", async () => {
+ // `useShortcut` prevents the event BEFORE calling the handler, so declining from inside the
+ // handler kills the chord for everyone: no bar, and no native find either.
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(bar, /claims: \(\) => !isSurfaceBackgrounded\(/);
+ const shortcut = await readFile(
+ new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),
+ "utf8",
+ );
+ const consume = shortcut.indexOf("event.preventDefault();");
+ assert.ok(consume > 0);
+ assert.ok(shortcut.lastIndexOf("latestRef.current.claims?.()", consume) > 0);
+});
+
+test("the Enter that commits an IME candidate is left alone", async () => {
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Ahead of preventDefault, or the composition is discarded before the guard is reached.
+ const enter = bar.slice(bar.indexOf('event.key === "Enter"'));
+ const guard = enter.indexOf("isImeComposing(event.nativeEvent)");
+ const prevent = enter.indexOf("event.preventDefault()");
+ assert.ok(guard > 0 && guard < prevent);
+});
+
+test("closing the bar hands focus back to where it came from", async () => {
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Captured above the effect that focuses the field, or it reads the field it is about to fill.
+ const capture = bar.indexOf("const active = document.activeElement");
+ const takeFocus = bar.indexOf("input.select();");
+ assert.ok(capture > 0 && capture < takeFocus);
+ assert.match(bar, /origin\.focus\(\);/);
+ // First answer only, and never the bar. StrictMode replays the effect in development, and by the
+ // second run the field has focus: read plainly, the bar would aim focus at its own input.
+ assert.match(bar, /originRef\.current === null &&/);
+ // Against the bar's own element, not `data-find-skip`. The composer carries that attribute, and
+ // it is the single most likely place the chord is pressed from: matching on it would refuse to
+ // record exactly the origin this exists to restore.
+ assert.match(bar, /barRef\.current\?\.contains\(active\) !== true/);
+ assert.equal(bar.includes("closest(`[${FIND_SKIP_ATTRIBUTE}]`)"), false);
+ // And only when closing dropped focus: the reader having moved it is not an invitation.
+ assert.match(
+ bar,
+ /if \(focused !== null && focused !== document\.body\) return;/,
+ );
+});
+
+test("the chat composer is out of the searchable scope", async () => {
+ // Its draft lives in a textarea the index cannot read, so all it leaves find is the pill labels:
+ // a search for "code" or "images" would land on the toolbar rather than the conversation.
+ const thread = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ const root = thread.slice(thread.indexOf("<ComposerPrimitive.Root"));
+ assert.match(
+ root.slice(0, root.indexOf(">")),
+ /\{\.\.\.\{ \[FIND_SKIP_ATTRIBUTE\]: "" \}\}/,
+ );
+});
+
+test("the reader is kept on the occurrence, not on the number", async () => {
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Written where the active match is settled, read where the next list is built.
+ assert.match(
+ engine,
+ /activeStartRef\.current = active >= 0 \? matches\[active\]\.start : null;/,
+ );
+ // Read BEFORE the new list is installed, or it is the new list's answer being read back.
+ const read = engine.indexOf("const wasAt = activeStartRef.current;");
+ const install = engine.indexOf("matchesRef.current = matches;", read - 400);
+ assert.ok(read > 0 && read < install);
+ assert.match(engine, /ordinalOfStart\(matches, wasAt\)/);
+ // And when the occurrence is gone, the reader's position decides rather than a stale number.
+ assert.match(
+ engine,
+ /at === -1 \? firstMatchFromViewport\(index, matches\) : at/,
+ );
+});
+
+test("the ordinal survives an append and nothing else", async () => {
+ // One rule decides who keeps their place. A streaming reply only adds at the tail, so match 20 is
+ // still match 20. History arriving above, a workspace switch flipping `inert`, a breakpoint
+ // revealing a column: each renumbers the list, and the reader's number then points at unrelated
+ // text. An unchanged document is an append of nothing, which is why a rebuild that finds no news
+ // leaves an Enter pressed while it ran alone.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ engine,
+ /const before = indexRef\.current\.text;[\s\S]*?return !indexRef\.current\.text\.startsWith\(before\);/,
+ );
+ // Every rebuild goes through it: no call site decides for itself that the numbering held.
+ assert.equal(engine.includes("search(false, false)"), false);
+ assert.equal((engine.match(/search\(false, reindex\(\)\)/g) ?? []).length, 2);
+ // Except a fresh open, which starts from the reader whatever the index says.
+ assert.match(
+ engine,
+ /reindex\(\);\n\s*\/\/[^\n]*\n\s*search\(false, 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.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /window\.addEventListener\("resize", invalidate\);/);
+ assert.match(engine, /window\.removeEventListener\("resize", invalidate\);/);
+ // Through the same throttle as a mutation, so dragging a window edge costs one rebuild an
+ // interval rather than one a frame.
+ assert.match(
+ engine,
+ /const invalidate = \(\) => \{[\s\S]*?REINDEX_INTERVAL_MS\);/,
+ );
+});
+
+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(
+ 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 \}\),/);
+});
+
+test("the capped window follows the reader, not the top of the document", () => {
+ // A single common letter in a long thread has far more matches than the cap. Keeping the first
+ // `limit` of them keeps only the top of the document, so a reader at the bottom is walked away
+ // from every occurrence beside them, to one they were not looking for.
+ const body = `${"q".repeat(20_000)} needle ${"q".repeat(20_000)}`;
+ const index = buildTextIndex(el("DIV", [el("P", [text(body)])]));
+ const anchor = index.text.indexOf("needle");
+ const limit = 100;
+
+ const fromTheTop = findMatches(index, "q", limit);
+ assert.equal(fromTheTop.length, limit);
+ assert.equal(fromTheTop[fromTheTop.length - 1].end <= anchor, true);
+
+ const aroundTheReader = findMatches(index, "q", limit, anchor);
+ assert.equal(aroundTheReader.length, limit);
+ // Half either side, so the walk goes forward from where the reader is and back the other way.
+ assert.equal(
+ aroundTheReader.some((match) => match.start < anchor),
+ true,
+ );
+ assert.equal(
+ aroundTheReader.some((match) => match.start > anchor),
+ true,
+ );
+ const nearest = aroundTheReader.find((match) => match.start > anchor);
+ assert.ok(nearest && nearest.start - anchor < 20);
+});
+
+test("a capped window slides as matches are appended", () => {
+ // Which is why an ordinal cannot be kept across a rebuild even when the document only grew. The
+ // window recentres, so the same number is a different occurrence.
+ // The reader near the end, which is where a reply streams in: too few matches after them to fill
+ // half the window, so the window is pinned to the end of the list and the end is what moves.
+ const limit = 100;
+ const before = `${"q".repeat(200)} needle ${"q".repeat(20)}`;
+ const after = `${before}${"q".repeat(200)}`;
+ const anchor = before.indexOf("needle");
+ const first = findMatches(
+ buildTextIndex(el("DIV", [el("P", [text(before)])])),
+ "q",
+ limit,
+ anchor,
+ );
+ const second = findMatches(
+ buildTextIndex(el("DIV", [el("P", [text(after)])])),
+ "q",
+ limit,
+ anchor,
+ );
+ assert.equal(first.length, limit);
+ assert.equal(second.length, limit);
+ // Same ordinal, different occurrence: the number moved under the reader.
+ assert.notEqual(first[limit - 1].start, second[limit - 1].start);
+ // The occurrence itself is still in the list, at a different index. That is what the engine
+ // follows instead of the number.
+ assert.equal(
+ second.some((match) => match.start === first[limit - 1].start),
+ true,
+ );
+});
+
+test("the window is only computed when the cap bites", () => {
+ // Under the cap this is the single pass it always was, whatever the anchor says.
+ const index = buildTextIndex(el("DIV", [el("P", [text("q q q q q")])]));
+ assert.deepEqual(
+ findMatches(index, "q", 100, 8),
+ findMatches(index, "q", 100, 0),
+ );
+});
+
+test("stopping the count early does not move the window", () => {
+ // `total` is only counted to keep the window off the end of the list, and it stops as soon as it
+ // is high enough to no longer do that. A stop that came too soon would drag the window back
+ // toward the top, which is the whole thing the anchor exists to prevent.
+ const body = "q".repeat(500);
+ const index = buildTextIndex(el("DIV", [el("P", [text(body)])]));
+ const at = 200;
+ const window = findMatches(index, "q", 50, at);
+ assert.equal(window.length, 50);
+ // Centred on the reader: 25 kept behind them, the rest ahead.
+ assert.equal(window[0].start, at - 25);
+ assert.equal(window[window.length - 1].end, at + 25);
+ // And the matches past the window, which the count stops before reaching, are really there.
+ assert.equal(findMatches(index, "q", 500, 0).length, 500);
+});
+
+test("the window stops at the ends of the list", () => {
+ const body = `needle ${"q".repeat(500)}`;
+ const index = buildTextIndex(el("DIV", [el("P", [text(body)])]));
+ // Anchored at the very start: nothing to keep before it, so the window is the first `limit`.
+ const atTheTop = findMatches(index, "q", 50, 1);
+ assert.equal(atTheTop[0].start, index.text.indexOf("q"));
+ // Anchored past the end: the window is the last `limit`, not a slice running off it.
+ const atTheEnd = findMatches(index, "q", 50, index.text.length);
+ assert.equal(atTheEnd.length, 50);
+ assert.equal(atTheEnd[atTheEnd.length - 1].end, index.text.length);
+});
+
+test("clipped accessibility text is not searchable", () => {
+ // Tailwind's `sr-only` keeps a real box at full opacity and clips it to nothing, so
+ // `checkVisibility` calls it visible. The app has 46 of them; counted, they are matches with a
+ // highlight clipped away along with the text.
+ const label = el("SPAN", [text("Data input")]);
+ const shown = el("SPAN", [text("Data output")]);
+ withStyles(
+ new Map([
+ [label, { clipPath: "inset(50%)" }],
+ [shown, { clipPath: "none" }],
+ ]),
+ () => {
+ const index = buildTextIndex(el("DIV", [label, shown]));
+ assert.equal(index.text.includes("data input"), false);
+ assert.equal(index.text.includes("data output"), true);
+ },
+ );
+ // The legacy spelling of the same idiom.
+ const legacy = el("SPAN", [text("Data input")]);
+ withStyles(new Map([[legacy, { clip: "rect(0px, 0px, 0px, 0px)" }]]), () => {
+ assert.equal(buildTextIndex(el("DIV", [legacy])).text, "");
+ });
+});
+
+test("the counter says '+' only when the cap actually cut something off", () => {
+ // `findMatches` stops at the limit it is given, so a count equal to the cap cannot say whether it
+ // is the total or a floor: a page holding exactly MAX_MATCHES read as "more than MAX_MATCHES".
+ // Asking for one past it is the whole difference; the extra match is thrown away.
+ const occurrences = (n: number) =>
+ findMatches(
+ buildTextIndex(el("DIV", [el("P", [text("a".repeat(n))])])),
+ "a",
+ MAX_MATCHES + 1,
+ ).length;
+ assert.equal(occurrences(MAX_MATCHES - 1) > MAX_MATCHES, false);
+ assert.equal(occurrences(MAX_MATCHES) > MAX_MATCHES, false);
+ assert.equal(occurrences(MAX_MATCHES + 1) > MAX_MATCHES, true);
+ // The count itself cannot tell the last two apart, which is why the flag exists.
+ assert.equal(
+ findMatches(
+ buildTextIndex(el("DIV", [el("P", [text("a".repeat(MAX_MATCHES))])])),
+ "a",
+ ).length,
+ findMatches(
+ buildTextIndex(el("DIV", [el("P", [text("a".repeat(MAX_MATCHES + 1))])])),
+ "a",
+ ).length,
+ );
+});
+
+test("the cap flag is what the bar renders, not the count", async () => {
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ engine,
+ /findMatches\(\s*\n\s*index,\s*\n\s*queryRef\.current,\s*\n\s*MAX_MATCHES \+ 1,/,
+ );
+ assert.match(engine, /cappedRef\.current = matches\.length > MAX_MATCHES;/);
+ // Trimmed back to the cap, so nothing downstream sees the probe match -- and trimmed from the
+ // end the reader is further from, since a window anchored near the bottom of a long thread ends
+ // at the document's last match rather than starting at its first.
+ assert.match(
+ engine,
+ /if \(cappedRef\.current\) dropProbeFurthestFrom\(matches, anchoredAt\);/,
+ );
+ // The anchor is captured as the thunk resolves it, so the trim costs no second layout read and
+ // still costs nothing under the cap, where the thunk is never called.
+ assert.match(engine, /let anchoredAt: number \| null = null;/);
+ assert.match(engine, /anchoredAt = viewportOffset\(index\);/);
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(bar, /\$\{capped \? "\+" : ""\}/);
+ assert.equal(bar.includes("count >= MAX_MATCHES"), false);
+});
+
+test("Escape is left to the IME while it is composing", async () => {
+ // Escape dismisses a candidate. Consumed here, it closes the bar out from under a word still
+ // being typed, and the candidate window never sees the key it was aimed at.
+ const bar = await readFile(
+ new URL(
+ "../src/features/find-in-page/components/find-in-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const escape = bar.slice(bar.indexOf("const onEscape ="));
+ const guard = escape.indexOf("isImeComposing(event)");
+ const consume = escape.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.
+ const shortcut = await readFile(
+ new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ shortcut,
+ /if \(isImeComposing\(event\)\) return;\n\s*const hit = bindings\.find/,
+ );
+});
+
+test("the selection fallback only clears what it put there", () => {
+ // The engines without a highlight registry get a selection instead, and the bar paints once on
+ // opening, before any query is typed. Clearing unconditionally there throws away whatever the
+ // reader had highlighted to copy, and closing cannot give it back.
+ // Boundary points, since engines differ on whether `getRangeAt` hands back the object that was
+ // added. Two distinct start containers stand in for two distinct selections.
+ const span = (name: string) =>
+ ({
+ startContainer: name,
+ startOffset: 0,
+ endContainer: name,
+ endOffset: 1,
+ }) as unknown as Range;
+ const ranges: Range[] = [];
+ const selection = {
+ get rangeCount(): number {
+ return ranges.length;
+ },
+ getRangeAt: (i: number): Range => ranges[i],
+ removeAllRanges: (): void => {
+ ranges.length = 0;
+ },
+ addRange: (range: Range): void => {
+ ranges.push(range);
+ },
+ };
+ const view = globalThis as { window?: unknown };
+ const saved = view.window;
+ view.window = { getSelection: () => selection };
+ try {
+ ranges.push(span("what the reader selected"));
+ selectRangeFallback(null);
+ assert.deepEqual(ranges, [span("what the reader selected")]);
+
+ selectRangeFallback(span("the active match"));
+ assert.deepEqual(ranges, [span("the active match")]);
+ selectRangeFallback(null);
+ // Annotated, or `deepEqual`'s assertion signature narrows `ranges` to `never[]` from here on.
+ assert.deepEqual(ranges, [] as Range[]);
+
+ // And a selection the reader made while the bar was open, over the match this had put there.
+ selectRangeFallback(span("the active match"));
+ ranges.length = 0;
+ ranges.push(span("dragged over something else"));
+ selectRangeFallback(null);
+ assert.deepEqual(ranges, [span("dragged over something else")]);
+ } finally {
+ view.window = saved;
+ }
+});
+
+test("the generated-image actions are out of the index too", async () => {
+ // Same shape as the badge below, and the same reason. From `sm` up the action bar over a
+ // generated image is transparent until the card is hovered, so its "Edit" was counted and walked
+ // to under a highlight nobody can see. Every place that mounts persistently transparent text has
+ // to say so, since the index cannot tell one from a message still fading in.
+ const tool = await readFile(
+ new URL(
+ "../src/components/assistant-ui/tool-ui-image-generation.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const at = tool.indexOf("sm:group-hover/generated-image:opacity-100");
+ assert.notEqual(at, -1);
+ assert.match(
+ tool.slice(Math.max(at - 700, 0), at),
+ /\{\.\.\.\{ \[FIND_SKIP_ATTRIBUTE\]: "" \}\}/,
+ );
+});
+
+test("a hover-only badge is out of the index", async () => {
+ // The response model label is mounted transparent and unclickable until the message is hovered.
+ // That is an affordance, not an entrance animation, so a match in it would be counted and walked
+ // to under a highlight nobody can see. Marked at the call site rather than by turning the opacity
+ // check on, which would drop a message still fading in.
+ const sheet = await readFile(
+ new URL(
+ "../src/components/assistant-ui/message-response-details-sheet.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const badge = sheet.slice(sheet.indexOf("aui-response-model-badge") - 400);
+ assert.match(
+ badge.slice(0, badge.indexOf("aui-response-model-badge")),
+ /\{\.\.\.\{ \[FIND_SKIP_ATTRIBUTE\]: "" \}\}/,
+ );
+ // The general rule stays off, so a fade-in is still findable.
+ const index = await readFile(
+ new URL(
+ "../src/features/find-in-page/lib/find-text-index.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(index, /opacityProperty: false/);
+});
+
+test("a container query resizing the scope invalidates the index", async () => {
+ // A container query does not need the window to change: Images is an `@container` with labels on
+ // `@[50rem]`, so pinning or collapsing the sidebar crosses that breakpoint with no window resize
+ // and no mutation inside the scope.
+ const engine = await readFile(
+ new URL(
+ "../src/features/find-in-page/hooks/use-find-in-page.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(engine, /new ResizeObserver\(\(\) => \{/);
+ assert.match(engine, /sized\.observe\(scope\);/);
+ assert.match(engine, /sized\?\.disconnect\(\);/);
+ // The first delivery reports the size the scope already had, which is not news and would cost a
+ // flatten on every open.
+ assert.match(
+ engine,
+ /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/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.ts
index 340793daa2d..fffa6572d9f 100644
--- a/studio/frontend/tests/keyboard-shortcuts.test.ts
+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts
@@ -522,6 +522,10 @@ test("no default takes a chord the browser owns without a reason", () => {
// the desktop build is where these are pressed.
"Mod+Shift+BracketLeft",
"Mod+Shift+BracketRight",
+ // Find in page: the one default that takes a browser chord on the web too,
+ // because the browser's own find is what it replaces. Reserving it is still
+ // right -- it is what warns a web user before they rebind onto it.
+ "Mod+KeyF",
]);
for (const def of SHORTCUT_DEFS) {
for (const slot of SHORTCUT_SLOTS) {
@@ -536,6 +540,15 @@ test("no default takes a chord the browser owns without a reason", () => {
}
}
}
+ // Being on the list has to MEAN the chord is flagged, or dropping a value from the reserved set
+ // silently turns an exception into an unwarned default and this test keeps passing.
+ for (const value of deliberate) {
+ assert.ok(
+ isBrowserReservedBinding(value, true) ||
+ isBrowserReservedBinding(value, false),
+ `${value} is listed as a deliberate exception but nothing flags it`,
+ );
+ }
});
test("recording a chord ignores a lone modifier", () => {
@@ -1580,6 +1593,7 @@ test("every action has a useShortcut call site", async () => {
"../src/features/chat/mcp-composer-button.tsx",
"../src/features/chat/components/chat-search-dialog.tsx",
"../src/features/api-monitor/api-monitor-overlay.tsx",
+ "../src/features/find-in-page/components/find-in-page.tsx",
];
const sources = await Promise.all(
files.map((file) => readFile(new URL(file, import.meta.url), "utf8")),
@@ -1613,7 +1627,7 @@ test("auto-repeat only reaches the actions that walk a list", async () => {
/event\.preventDefault\(\);\n(?:\s*\/\/[^\n]*\n)*\s*if \(event\.repeat && !repeats\) return;/,
);
// Off by default, so a new call site is one-shot until it says otherwise.
- assert.match(hook, /repeats = false,\n\s*\} = options;/);
+ assert.match(hook, /repeats = false,\n(?:\s*\w+,\n)*\s*\} = options;/);
assert.match(
hook,
/\[bindings, enabled, skipInTextFields, textFieldException, repeats\]/,
diff --git a/studio/frontend/tests/progressive-mount-glue.test.ts b/studio/frontend/tests/progressive-mount-glue.test.ts
index a7f038e9712..c346499ada9 100644
--- a/studio/frontend/tests/progressive-mount-glue.test.ts
+++ b/studio/frontend/tests/progressive-mount-glue.test.ts
@@ -288,16 +288,15 @@ test("the correction advances the intent bookkeeping with its write", () => {
test("the escape hatch exists, resolves after a paint, and is registered only while withholding", () => {
// A DOM read during the few frames a long thread takes to converge would silently see a short
// conversation, and a single rAF resolves before the commit it forced has painted.
- assert.match(
- GLUE,
- /export async function completeProgressiveMounts\(\): Promise<void>/,
- );
+ assert.match(GLUE, /export async function completeProgressiveMounts\(/);
+ // The filter is optional, so a caller that wants every thread still writes no argument.
+ assert.match(GLUE, /wants\?: \(viewport: HTMLElement \| null\) => boolean,/);
assert.match(
GLUE,
/requestAnimationFrame\(\(\) => requestAnimationFrame\(\(\) => resolve\(\)\)\)/,
);
assert.match(GLUE, /if \(!isWithholding\) return;/);
- assert.match(GLUE, /activeCompleters\.delete\(complete\)/);
+ assert.match(GLUE, /activeCompleters\.delete\(entry\)/);
});
test("the viewport comes from a ref, not a document-wide query", () => {
@@ -358,10 +357,14 @@ test("the escape hatch re-reads the completer set instead of sampling it once",
// the set empty (measured: returned in 0.1ms, 16 of 220 rows two frames later). Nor is an empty
// set believed straight away, since a settled thread and one still loading history look alike.
assert.match(GLUE, /let observed = false;/);
+ // Through `wanted()`, which reads `activeCompleters` on every call: the exit has to see the set as
+ // it is now, and it has to see the same FILTERED set the loop drains, or a completer this caller
+ // declined would hold it open forever.
assert.match(
GLUE,
- /activeCompleters\.size === 0 && \(observed \|\| Date\.now\(\) >= deadline\)/,
+ /wanted\(\)\.length === 0 && \(observed \|\| Date\.now\(\) >= deadline\)/,
);
+ assert.match(GLUE, /const wanted = \(\) =>[\s\S]*?activeCompleters/);
// The re-read is only worth anything if the deadline is in the FUTURE. A deadline of `Date.now()`
// keeps both lines above and still returns on the first pass, because a caller in the same task
// as the thread opening reaches the check before any completer has registered: the read-once
diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.json
index 374932571f8..296a36dd7e3 100644
--- a/studio/frontend/tsconfig.app.json
+++ b/studio/frontend/tsconfig.app.json
@@ -31,6 +31,7 @@
"include": [
"src",
"smoke-ansi-main.tsx",
+ "smoke-find-in-page-main.tsx",
"smoke-autoscroll-main.tsx",
"smoke-research-main.tsx",
"smoke-heavy-thread-main.tsx",
diff --git a/tests/studio/playwright_find_in_page.py b/tests/studio/playwright_find_in_page.py
new file mode 100644
index 00000000000..212d51276b2
--- /dev/null
+++ b/tests/studio/playwright_find_in_page.py
@@ -0,0 +1,627 @@
+# 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.
+
+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.
+
+ 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.
+"""
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ start_vite,
+ stop_process,
+)
+
+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"
+
+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"),
+ "Linux": ("Linux x86_64", "Mozilla/5.0 (X11; Linux x86_64) SmokeUA"),
+}
+MOD = {"macOS": "Meta", "Windows": "Control", "Linux": "Control"}
+
+# Drop the highlight registry before the app loads, so the bar takes the
+# selection fallback exactly as it does on an engine that never had one.
+NO_HIGHLIGHT_API = """
+delete window.Highlight;
+try { delete CSS.highlights; } catch (e) { /* getter-only on some engines */ }
+"""
+
+# An engine from before the option rename: it answers only checkVisibilityCSS
+# and checkOpacity, and ignores the modern spellings the way Web IDL does.
+LEGACY_CHECK_VISIBILITY = """
+const real = Element.prototype.checkVisibility;
+Element.prototype.checkVisibility = function (options) {
+ const legacy = {};
+ if (options && 'checkVisibilityCSS' in options) {
+ legacy.checkVisibilityCSS = options.checkVisibilityCSS;
+ }
+ if (options && 'checkOpacity' in options) {
+ legacy.checkOpacity = options.checkOpacity;
+ }
+ if (options && 'contentVisibilityAuto' in options) {
+ legacy.contentVisibilityAuto = options.contentVisibilityAuto;
+ }
+ return real.call(this, legacy);
+};
+"""
+
+# An engine with no checkVisibility at all, which is Safari below 17.4 and the
+# WebKitGTK the desktop build is handed. The optional call answers undefined
+# there, and read as "not false" it put every display: none subtree back in.
+NO_CHECK_VISIBILITY = """
+delete Element.prototype.checkVisibility;
+"""
+
+failures: list[str] = []
+passed = 0
+
+
+def check(
+ engine: str,
+ mode: str,
+ name: str,
+ ok: bool,
+ detail: str = "",
+) -> None:
+ global passed
+ if ok:
+ passed += 1
+ return
+ failures.append(f"{engine}/{mode}: {name}\n {detail}")
+
+
+def counter(page) -> str | None:
+ return page.evaluate("() => window.__findSmoke.counter()")
+
+
+def state(page) -> dict:
+ return page.evaluate("() => window.__findSmoke.store.getState()")
+
+
+def open_bar(page, mod: str) -> None:
+ page.keyboard.press(f"{mod}+f")
+ page.wait_for_timeout(250)
+
+
+def close_bar(page) -> None:
+ page.keyboard.press("Escape")
+ page.wait_for_timeout(250)
+
+
+def check_chord(page, engine: str, mode: str, mod: str) -> None:
+ """The chord opens the bar, and does so from a text field too."""
+ open_bar(page, mod)
+ check(engine, mode, "the chord opens the bar", state(page).get("open") is True)
+ check(
+ engine,
+ mode,
+ "the bar is a search landmark",
+ page.locator('[role="search"]').count() == 1,
+ )
+
+ # 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.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,
+ )
+ close_bar(page)
+ check(engine, mode, "Escape closes the bar", state(page).get("open") is False)
+
+
+def check_counting(page, engine: str, mode: str, mod: str) -> None:
+ open_bar(page, mod)
+ page.keyboard.type("unsloth")
+ page.wait_for_timeout(500)
+ shown = counter(page)
+ check(engine, mode, "a query is counted", bool(shown), f"counter={shown!r}")
+
+ # An off-route workspace is kept mounted under `inert`; its matches must not
+ # be counted or walked to.
+ page.evaluate("() => window.__findSmoke.setWorkspace('other')")
+ page.wait_for_timeout(700)
+ other = counter(page)
+ check(
+ engine,
+ mode,
+ "an inert workspace is out of the count",
+ other != shown,
+ f"{shown!r} -> {other!r}",
+ )
+ page.evaluate("() => window.__findSmoke.setWorkspace('chat')")
+ page.wait_for_timeout(700)
+ check(
+ engine,
+ mode,
+ "switching back restores the count",
+ counter(page) == shown,
+ f"{counter(page)!r} != {shown!r}",
+ )
+ close_bar(page)
+
+
+def check_walk(page, engine: str, mode: str, mod: str) -> None:
+ open_bar(page, mod)
+ page.keyboard.type("unsloth")
+ page.wait_for_timeout(500)
+ start = page.evaluate("() => window.__findSmoke.scrollTop()")
+ for _ in range(6):
+ page.keyboard.press("Enter")
+ page.wait_for_timeout(120)
+ moved = page.evaluate("() => window.__findSmoke.scrollTop()")
+ check(
+ engine,
+ mode,
+ "Enter walks the matches and scrolls to them",
+ moved != start,
+ f"scrollTop {start} -> {moved}",
+ )
+
+ # Shift+Enter walks back.
+ page.keyboard.press("Shift+Enter")
+ page.wait_for_timeout(200)
+ check(
+ engine,
+ mode,
+ "Shift+Enter walks backwards",
+ counter(page) is not None,
+ f"counter={counter(page)!r}",
+ )
+ close_bar(page)
+
+
+def check_streaming(page, engine: str, mode: str, mod: str) -> None:
+ open_bar(page, mod)
+ page.keyboard.type("unsloth")
+ page.wait_for_timeout(500)
+ for _ in range(4):
+ page.keyboard.press("Enter")
+ page.wait_for_timeout(120)
+ before_scroll = page.evaluate("() => window.__findSmoke.scrollTop()")
+ before_count = counter(page)
+ page.evaluate("() => window.__findSmoke.stream('a streamed unsloth reply', 5)")
+ page.wait_for_timeout(1600)
+ check(
+ engine,
+ mode,
+ "a streamed reply raises the count",
+ counter(page) != before_count,
+ f"{before_count!r} -> {counter(page)!r}",
+ )
+ check(
+ engine,
+ mode,
+ "a streamed reply does not move the reader",
+ page.evaluate("() => window.__findSmoke.scrollTop()") == before_scroll,
+ f"scrollTop {before_scroll} -> " f"{page.evaluate('() => window.__findSmoke.scrollTop()')}",
+ )
+ close_bar(page)
+
+
+def check_paint_and_teardown(page, engine: str, mode: str, mod: str) -> None:
+ """Whichever way this engine shows a match, opening paints and closing clears."""
+ has_api = page.evaluate("() => typeof CSS !== 'undefined' && !!CSS.highlights")
+ open_bar(page, mod)
+ page.keyboard.type("unsloth")
+ page.wait_for_timeout(500)
+
+ if has_api:
+ painted = page.evaluate(
+ "() => ({ all: CSS.highlights.has('unsloth-find'),"
+ " active: CSS.highlights.has('unsloth-find-active') })"
+ )
+ check(
+ engine,
+ mode,
+ "both highlight registries are painted",
+ painted["all"] and painted["active"],
+ str(painted),
+ )
+ else:
+ # No registry, so the bar falls back to selecting the active match. Whether that selection
+ # survives is the engine's call - Gecko keeps it, WebKit and Blink drop it to give the caret
+ # back - so the invariant here is the one that is not negotiable: the field still works.
+ # Moving the selection out from under a focused field used to swallow every keystroke after
+ # the first, which froze the query at one character on exactly the engines that land here.
+ typed = page.evaluate("() => document.querySelector('[role=\"search\"] input')?.value")
+ check(
+ engine,
+ mode,
+ "the field is still typable once the fallback has selected",
+ typed == "unsloth",
+ f"input value={typed!r}, expected 'unsloth'",
+ )
+ check(
+ engine,
+ mode,
+ "the fallback still counts every match",
+ bool(counter(page)),
+ f"counter={counter(page)!r}",
+ )
+
+ close_bar(page)
+ if has_api:
+ left = page.evaluate(
+ "() => CSS.highlights.has('unsloth-find')"
+ " || CSS.highlights.has('unsloth-find-active')"
+ )
+ check(engine, mode, "closing clears both registries", left is False)
+ else:
+ check(
+ engine,
+ mode,
+ "closing drops the fallback selection",
+ page.evaluate("() => (window.getSelection()?.toString() ?? '')") == "",
+ )
+
+
+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)
+ check(
+ engine,
+ mode,
+ "the chord is declined while a modal backgrounds the scope",
+ state(page).get("open") is False,
+ )
+ page.evaluate("() => window.__findSmoke.setModal(false)")
+ page.wait_for_timeout(250)
+ open_bar(page, mod)
+ check(
+ engine,
+ mode,
+ "the chord works again once the modal is gone",
+ state(page).get("open") is True,
+ )
+ close_bar(page)
+
+
+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.
+ """
+ page.evaluate(
+ """() => {
+ const scope = document.querySelector('[data-find-scope]') ?? document.body;
+ for (const id of ['probe-vis', 'probe-contents', 'probe-none']) {
+ document.getElementById(id)?.remove();
+ }
+ const gone = document.createElement('div');
+ gone.id = 'probe-none';
+ gone.style.display = 'none';
+ gone.textContent = 'zqxjkvbrmp';
+ scope.appendChild(gone);
+
+ const plain = document.createElement('div');
+ plain.id = 'probe-vis';
+ plain.style.visibility = 'hidden';
+ plain.textContent = 'zqxjkvbrmp';
+ scope.appendChild(plain);
+
+ const wrapper = document.createElement('span');
+ wrapper.id = 'probe-contents';
+ wrapper.style.display = 'contents';
+ wrapper.style.visibility = 'hidden';
+ wrapper.textContent = 'zqxjkvbrmp';
+ scope.appendChild(wrapper);
+ }"""
+ )
+ page.wait_for_timeout(500)
+ open_bar(page, mod)
+ page.keyboard.type("zqxjkvbrmp")
+ page.wait_for_timeout(700)
+ shown = counter(page)
+ check(
+ engine,
+ mode,
+ "hidden text is not findable",
+ shown in (None, "", "0/0"),
+ f"counter={shown!r} (a non-zero count means hidden text was indexed)",
+ )
+ close_bar(page)
+ page.evaluate(
+ """() => {
+ document.getElementById('probe-vis')?.remove();
+ document.getElementById('probe-contents')?.remove();
+ document.getElementById('probe-none')?.remove();
+ }"""
+ )
+
+
+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.
+ """
+ planted = page.evaluate(
+ """() => {
+ const conversation = document.querySelector('[data-find-scope] .mx-auto');
+ document.getElementById('cv-probe')?.remove();
+ const box = document.createElement('div');
+ box.id = 'cv-probe';
+ box.style.contentVisibility = 'auto';
+ box.style.containIntrinsicSize = 'auto 140px';
+ const lines = [];
+ for (let i = 0; i < 120; i++) lines.push('filler line ' + i);
+ lines.push('zqxjcvneedle at the very bottom');
+ box.innerHTML = lines.map((t) => '<p>' + t + '</p>').join('');
+ conversation.appendChild(box);
+ return Math.round(box.getBoundingClientRect().height);
+ }"""
+ )
+ check(
+ engine,
+ mode,
+ "the placeholder really is standing in for the block",
+ planted == 140,
+ f"placeholder height={planted}",
+ )
+ page.wait_for_timeout(600)
+ open_bar(page, mod)
+ # Inserted whole, the way a paste arrives, rather than typed. Typing hides this: every
+ # keystroke reveals again, and those repeats do by accident what the fix does on purpose.
+ # One change is what a paste, an Enter, or a click on the walk button each produce.
+ page.keyboard.insert_text("zqxjcvneedle")
+ page.wait_for_timeout(1200)
+ where = page.evaluate(
+ """() => {
+ const p = [...document.querySelectorAll('#cv-probe p')]
+ .find((n) => n.textContent.includes('zqxjcvneedle'));
+ const r = p.getBoundingClientRect();
+ return { top: Math.round(r.top), bottom: Math.round(r.bottom),
+ height: window.innerHeight,
+ real: Math.round(document.getElementById('cv-probe').getBoundingClientRect().height),
+ inViewport: r.top >= 0 && r.bottom <= window.innerHeight };
+ }"""
+ )
+ check(
+ engine,
+ mode,
+ "the block behind the placeholder rendered",
+ where["real"] > 1000,
+ f"height={where['real']} (still the placeholder)",
+ )
+ check(
+ engine,
+ mode,
+ "typing the query leaves the match on screen",
+ where["inViewport"] is True,
+ f"{where} (aimed at the placeholder and never looked again)",
+ )
+ close_bar(page)
+ page.evaluate("() => document.getElementById('cv-probe')?.remove()")
+
+
+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.
+ """
+ planted = page.evaluate(
+ """() => {
+ const scope = document.querySelector('[data-find-scope]') ?? document.body;
+ document.getElementById('probe-nfd')?.remove();
+ const row = document.createElement('div');
+ row.id = 'probe-nfd';
+ // cafe + combining acute, then " vbnmqz" to keep the query out of the prose.
+ row.textContent = 'cafe\u0301 vbnmqz';
+ scope.appendChild(row);
+ return row.textContent.normalize('NFC') !== row.textContent;
+ }"""
+ )
+ check(engine, mode, "the planted text really is decomposed", planted is True)
+ page.wait_for_timeout(500)
+ open_bar(page, mod)
+ # Typed composed, against text written decomposed.
+ page.keyboard.type("caf\u00e9 vbnmqz")
+ page.wait_for_timeout(700)
+ shown = counter(page)
+ check(
+ engine,
+ mode,
+ "a composed query finds decomposed text",
+ 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.
+ if page.evaluate("() => typeof CSS !== 'undefined' && !!CSS.highlights"):
+ covers = page.evaluate(
+ """() => {
+ const set = CSS.highlights.get('unsloth-find-active');
+ const range = set ? [...set][0] : null;
+ return range ? range.toString() : null;
+ }"""
+ )
+ check(
+ engine,
+ mode,
+ "the painted range covers what the document wrote",
+ covers == "cafe\u0301 vbnmqz",
+ f"painted={covers!r} (a drifted offset paints the wrong characters)",
+ )
+ close_bar(page)
+ page.evaluate("() => document.getElementById('probe-nfd')?.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(
+ """() => {
+ const scope = document.querySelector('[data-find-scope]') ?? document.body;
+ document.getElementById('probe-skip')?.remove();
+ const panel = document.createElement('div');
+ panel.id = 'probe-skip';
+ panel.textContent = 'wqzlmxtvbn wqzlmxtvbn';
+ scope.appendChild(panel);
+ }"""
+ )
+ page.wait_for_timeout(500)
+ open_bar(page, mod)
+ page.keyboard.type("wqzlmxtvbn")
+ page.wait_for_timeout(700)
+ before = counter(page)
+ check(engine, mode, "the planted panel is counted", bool(before), f"{before!r}")
+
+ # Adding the attribute is the direction that used to be filtered out of the
+ # observer's own batch, leaving the region counted until something else
+ # happened to mutate.
+ page.evaluate("() => document.getElementById('probe-skip')?.setAttribute('data-find-skip', '')")
+ page.wait_for_timeout(900)
+ after = counter(page)
+ check(
+ engine,
+ mode,
+ "marking a region data-find-skip reindexes and drops it",
+ after != before,
+ f"{before!r} -> {after!r} (unchanged means the mutation was filtered out)",
+ )
+ close_bar(page)
+ page.evaluate("() => document.getElementById('probe-skip')?.remove()")
+
+
+def run_page(page, engine: str, mode: str, mod: str) -> None:
+ for probe in (
+ check_chord,
+ check_counting,
+ check_walk,
+ check_streaming,
+ check_paint_and_teardown,
+ check_modal_gate,
+ check_hidden_text,
+ check_content_visibility_reveal,
+ check_spelling_variants,
+ check_skip_attribute,
+ ):
+ try:
+ probe(page, engine, mode, mod)
+ except Exception as exc: # noqa: BLE001
+ check(
+ engine,
+ mode,
+ f"{probe.__name__} ran to completion",
+ False,
+ f"{type(exc).__name__}: {str(exc)[:300]}",
+ )
+
+
+def new_page(context):
+ page = context.new_page()
+ for attempt in range(30):
+ try:
+ page.goto(URL, wait_until = "domcontentloaded", timeout = 30000)
+ break
+ except Exception:
+ if attempt == 29:
+ raise
+ time.sleep(2)
+ page.wait_for_function("() => !!window.__findSmoke", timeout = 120000)
+ return page
+
+
+def run_engine(pw, engine: str) -> None:
+ launch = {"args": chromium_launch_args()} if engine == "chromium" else {}
+ browser = getattr(pw, engine).launch(**launch)
+ try:
+ # The platform sweep, on the engine's own capabilities.
+ for platform, (nav_platform, agent) in PLATFORMS.items():
+ context = browser.new_context(user_agent = agent)
+ context.add_init_script(
+ "Object.defineProperty(navigator, 'platform', "
+ f"{{ get: () => {json.dumps(nav_platform)} }});"
+ )
+ page = new_page(context)
+ run_page(page, engine, platform, MOD[platform])
+ context.close()
+
+ # The two degraded engines, on one platform each: what they exercise is
+ # the capability, and the platform sweep above already covered the chord.
+ for mode, script in (
+ ("no-highlight-api", NO_HIGHLIGHT_API),
+ ("legacy-checkVisibility", LEGACY_CHECK_VISIBILITY),
+ ("no-checkVisibility", NO_CHECK_VISIBILITY),
+ ):
+ context = browser.new_context(user_agent = PLATFORMS["Linux"][1])
+ context.add_init_script(
+ "Object.defineProperty(navigator, 'platform', { get: () => 'Linux x86_64' });"
+ )
+ context.add_init_script(script)
+ page = new_page(context)
+ run_page(page, engine, mode, "Control")
+ context.close()
+ finally:
+ browser.close()
+
+
+def main() -> int:
+ server = start_vite(PORT)
+ try:
+ with sync_playwright() as pw:
+ for engine in ENGINES:
+ run_engine(pw, engine)
+ finally:
+ stop_process(server)
+
+ total = passed + len(failures)
+ print(f"[find-in-page] {passed}/{total} checks passed across {', '.join(ENGINES)}")
+ for failure in failures:
+ print(f"[find-in-page] FAIL {failure}")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())