TypeScript
refactor(web): thread find state lives in one store instead of event buses and mirrors (#25073)
Julius Marmingef16ae12bb6ed
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 6251e14bbbe..afbc10204c5 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -19,7 +19,8 @@ import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChimport { useComposerSend } from "./chat/useComposerSend";import { useComposerResume } from "./chat/useComposerResume";import { useImplementPlanInNewThread } from "./chat/useProposedPlanSend";-import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";+import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider";+import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore";import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";import { resolveDraftHeroState } from "./ChatView.logic";@@ -2656,10 +2657,9 @@ export default function ChatView(props: ChatViewProps) {const timelineSkills = activeProviderStatus? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd): EMPTY_PROVIDER_SKILLS;- const threadFindControlsRef = useRef<ThreadFindControls | null>(null);- const [isThreadFindActive, setIsThreadFindActive] = useState(false);- const openThreadFind = () => threadFindControlsRef.current?.open();- const closeThreadFind = () => threadFindControlsRef.current?.close();+ const threadFindEnabled =+ isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline;+ const isThreadFindActive = useThreadFindOpen(activeThreadRef, threadFindEnabled);useChatShortcuts({enabled: activeThreadId !== null && !backgroundThread,@@ -2681,8 +2681,9 @@ export default function ChatView(props: ChatViewProps) {if (!event.repeat) copyActiveThreadReference();},"chat.find": () => {- if (!isServerThread || serverConfig?.threadFind !== true) return false;- openThreadFind();+ if (!isServerThread || serverConfig?.threadFind !== true || activeThreadKey === null)+ return false;+ openThreadFind(activeThreadKey);},"composer.cycleHost": ({ event }) => {if (!canChangeEnvironment) return false;@@ -3208,11 +3209,8 @@ export default function ChatView(props: ChatViewProps) {skills: timelineSkills,progressive: serverConfig?.threadFindProgressive === true,thread: activeThreadRef,- enabled:- isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline,+ enabled: threadFindEnabled,}}- controlsRef={threadFindControlsRef}- onOpenChange={setIsThreadFindActive}detailsCardTopInset={isThreadFindActive ? THREAD_FIND_BAR_RESERVED_HEIGHT : 0}composerOverlayElement={isDraftHeroState ? null : composerOverlayElement}data-chat-workspace-drop-target="true"diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex 7951655a2da..21883a49f12 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -1,7 +1,11 @@import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";-import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";+import {+ scopedThreadKey,+ scopeProjectRef,+ scopeThreadRef,+} from "@t3tools/client-runtime/environment";import {canCreateProjectInEnvironment,getCloneDestinationBrowsePath,@@ -66,7 +70,7 @@ import {TextSearchIcon,UserPlusIcon,} from "lucide-react";-import { requestThreadFindOpen } from "./chat/threadFindActionBus";+import { openThreadFind } from "./chat/threadFindStore";import {useDeferredValue,useEffect,@@ -729,7 +733,9 @@ function OpenCommandPaletteDialog(props: {const { projectCwdById, projectByKey, projectTitleById } = useProjectLookups();- const activeThreadId = activeThread?.id;+ const activeThreadKey = activeThread+ ? scopedThreadKey(scopeThreadRef(activeThread.environmentId, activeThread.id))+ : null;const supportsThreadFind =environments.find((environment) => environment.environmentId === activeThread?.environmentId)?.serverConfig?.threadFind === true;@@ -1256,7 +1262,7 @@ function OpenCommandPaletteDialog(props: {});}- if (activeThreadId && supportsThreadFind) {+ if (activeThreadKey !== null && supportsThreadFind) {actionItems.push({kind: "action",value: "find-current-thread",@@ -1265,7 +1271,7 @@ function OpenCommandPaletteDialog(props: {icon: <TextSearchIcon className={ITEM_ICON_CLASS} />,shortcutCommand: "chat.find",run: async () => {- requestThreadFindOpen();+ openThreadFind(activeThreadKey);},});}@@ -2411,11 +2417,17 @@ function OpenCommandPaletteDialog(props: {return;}// ChatView ignores shortcuts while the palette is open, so intercept find here.- if (command === "chat.find" && activeThreadId && !event.nativeEvent.isComposing) {+ if (command === "chat.find" && activeThreadKey !== null && !event.nativeEvent.isComposing) {event.preventDefault();event.stopPropagation();setOpen(false);- requestThreadFindOpen();+ if (supportsThreadFind) openThreadFind(activeThreadKey);+ else+ toastManager.add({+ id: "thread-find-unavailable",+ title: "Thread search is unavailable on this server.",+ description: "Update the server to enable it.",+ });return;}diff --git a/apps/web/src/components/CommandPaletteThreadItems.tsx b/apps/web/src/components/CommandPaletteThreadItems.tsxindex 7f3238d199a..5312e13893b 100644--- a/apps/web/src/components/CommandPaletteThreadItems.tsx+++ b/apps/web/src/components/CommandPaletteThreadItems.tsx@@ -1,5 +1,5 @@import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";-import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";+import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";import {claimThreadOpen,nextShownOrder,@@ -218,7 +218,7 @@ export function useCommandPaletteThreadItems(input: {// Opens the thread with find on the word at the matched message, so it is in view.run: async () => {await item.run();- requestThreadFindQuery(+ openThreadFindOnQuery(scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)),findForMessageMatch(match, messageSearch.query),);diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex db839a675fb..e139efffeb2 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -40,7 +40,7 @@ import {type ShownOrder,} from "@t3tools/client-runtime/state/thread-search";import { foldSearchQuery, rankMessageMatches } from "@t3tools/shared/paletteSearch";-import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";+import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";import {threadRuntimeCanArchive,type EnvironmentThreadShell,@@ -1305,7 +1305,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveconst query = threadSearch.query;clearThreadSearch();navigateToThread(ref);- if (match) requestThreadFindQuery(scopedThreadKey(ref), findForMessageMatch(match, query));+ if (match) openThreadFindOnQuery(scopedThreadKey(ref), findForMessageMatch(match, query));};const handleThreadSearchKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {if (event.nativeEvent.isComposing || event.keyCode === 229) return;diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 7ba6f4ea840..f7fdef05baf 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -74,7 +74,6 @@ import {} from "./MessagesTimeline.logic";import { type ThreadFindMatch } from "./threadFind";import { useThreadFindNavigation } from "./useThreadFindNavigation";-import type { ThreadFindPositionReader } from "./threadFind";import { TooltipScrollDismissArea } from "../ui/tooltip";import { WorktreeSetupCard } from "./WorktreeSetupCard";import { useOpenPrLink } from "~/lib/openPullRequestLink";@@ -267,7 +266,6 @@ interface MessagesTimelineProps {topFadeEnabled?: boolean;historyControls?: MessagesTimelineHistoryControls | undefined;loadEarlier?: CitationHistoryPage | null;- findPositionReaderRef?: React.RefObject<ThreadFindPositionReader | null>;findExpanded?: boolean;findQuery?: string;activeFindMatch?: ThreadFindMatch | null;@@ -315,7 +313,6 @@ const ConversationTimeline = memo(function ConversationTimeline({findQuery = "",activeFindMatch = null,findNavigationId = 0,- findPositionReaderRef,latestRun,announcedRun = null,detailBehindShell = false,@@ -1024,7 +1021,7 @@ const ConversationTimeline = memo(function ConversationTimeline({};useThreadFindPositionReader({- findPositionReaderRef,+ threadKey: listIdentityKey,timelineViewportElement,findFoldRunIds,timelineEntries,diff --git a/apps/web/src/components/chat/ThreadFindProvider.tsx b/apps/web/src/components/chat/ThreadFindProvider.tsxindex 2a13e64f0b6..af5a5d7067f 100644--- a/apps/web/src/components/chat/ThreadFindProvider.tsx+++ b/apps/web/src/components/chat/ThreadFindProvider.tsx@@ -1,33 +1,20 @@-import {- createContext,- use,- useImperativeHandle,- useLayoutEffect,- type ReactNode,- type ComponentProps,- type Ref,-} from "react";+import { createContext, use, type ReactNode, type ComponentProps } from "react";import { useThreadFind } from "./useThreadFind";import { ThreadFindBar } from "./ThreadFindBar";import { ChatCanvas } from "./ChatCanvas";type Find = ReturnType<typeof useThreadFind>;-export type ThreadFindControls = Pick<Find, "open" | "close">;export const ThreadFindTimelineContext = createContext<Find["timelineProps"] | null>(null);const ThreadFindBarContext = createContext<Find["barProps"] | null>(null);export function ThreadFindCanvas({findOptions,- controlsRef,- onOpenChange,...canvasProps}: ComponentProps<typeof ChatCanvas> & {findOptions: Parameters<typeof useThreadFind>[0];- controlsRef: Ref<ThreadFindControls>;- onOpenChange: (open: boolean) => void;}) {return (- <ThreadFindProvider {...findOptions} controlsRef={controlsRef} onOpenChange={onOpenChange}>+ <ThreadFindProvider {...findOptions}><ChatCanvas {...canvasProps} /></ThreadFindProvider>);@@ -35,21 +22,10 @@ export function ThreadFindCanvas({/** Owns search updates below the chat view so cycling does not rerender the composer and panels. */function ThreadFindProvider({- controlsRef,- onOpenChange,children,...options-}: Parameters<typeof useThreadFind>[0] & {- controlsRef: Ref<ThreadFindControls>;- onOpenChange: (open: boolean) => void;- children: ReactNode;-}) {+}: Parameters<typeof useThreadFind>[0] & { children: ReactNode }) {const find = useThreadFind(options);- useImperativeHandle(controlsRef, () => ({ open: find.open, close: find.close }), [- find.open,- find.close,- ]);- useLayoutEffect(() => onOpenChange(find.isOpen), [find.isOpen, onOpenChange]);return (<ThreadFindBarContext value={find.barProps}><ThreadFindTimelineContext value={find.timelineProps}>{children}</ThreadFindTimelineContext>diff --git a/apps/web/src/components/chat/threadFindActionBus.test.ts b/apps/web/src/components/chat/threadFindActionBus.test.tsdeleted file mode 100644index 85079deb0a7..00000000000--- a/apps/web/src/components/chat/threadFindActionBus.test.ts+++ /dev/null@@ -1,22 +0,0 @@-import { MessageId } from "@t3tools/contracts";-import { describe, expect, it } from "vite-plus/test";--import { findForMessageMatch } from "./threadFindActionBus";--describe("findForMessageMatch", () => {- it("opens find on the longest word as the snippet writes it, at the matched message", () => {- expect(- findForMessageMatch(- { snippet: "The cafeteria, then the Café", messageId: MessageId.make("message-1") },- "cafe",- ),- ).toEqual({ query: "Café", start: { entryId: "message-1", occurrence: 0 } });- expect(findForMessageMatch({ snippet: "fix the sidebar lag" }, "fix sidebar")).toEqual({- query: "sidebar",- });- // The whole query, when the snippet holds it as typed.- expect(findForMessageMatch({ snippet: "then Vp run dev again" }, "vp run dev")).toEqual({- query: "Vp run dev",- });- });-});diff --git a/apps/web/src/components/chat/threadFindActionBus.ts b/apps/web/src/components/chat/threadFindActionBus.tsdeleted file mode 100644index 9230e5fbd69..00000000000--- a/apps/web/src/components/chat/threadFindActionBus.ts+++ /dev/null@@ -1,80 +0,0 @@-import type { OrchestrationThreadSearchMatch } from "@t3tools/contracts";-import {- findSearchTokenRanges,- messagePhrase,- messageSearchTokens,-} from "@t3tools/shared/paletteSearch";-import type { ThreadFindStart } from "./threadFind";--const THREAD_FIND_OPEN_EVENT = "t3:thread-find-open";--export function requestThreadFindOpen(): void {- window.dispatchEvent(new Event(THREAD_FIND_OPEN_EVENT));-}--export function subscribeThreadFindOpen(listener: () => void): () => void {- window.addEventListener(THREAD_FIND_OPEN_EVENT, listener);- return () => window.removeEventListener(THREAD_FIND_OPEN_EVENT, listener);-}--const THREAD_FIND_QUERY_EVENT = "t3:thread-find-query";-interface PendingFind {- readonly query: string;- /** Where find starts, such as the message a palette result came from. */- readonly start?: ThreadFindStart;-}-// A find a palette message result asked for, until that thread's view takes-// it. One the view never took (the navigation failed) lets go after a while,-// so a later visit does not open an old find.-const PENDING_FIND_MS = 30_000;-let pendingFind: (PendingFind & { readonly threadKey: string; readonly at: number }) | null = null;--/** Opens find on `query` in the thread's view, now or once it mounts. */-export function requestThreadFindQuery(threadKey: string, find: PendingFind): void {- pendingFind = { threadKey, at: Date.now(), ...find };- window.dispatchEvent(new Event(THREAD_FIND_QUERY_EVENT));-}--/** The find waiting for this thread's view; answers once. */-export function takeThreadFindQuery(threadKey: string): PendingFind | null {- if (pendingFind?.threadKey !== threadKey) return null;- const { at, threadKey: _threadKey, ...find } = pendingFind;- pendingFind = null;- return Date.now() - at < PENDING_FIND_MS ? find : null;-}--/**- * The find a message search result opens, at the matched message: the whole- * query when the snippet holds it as typed ("vp run dev"), else its longest- * word, as the most telling ("sidebar" in "fix sidebar"), written as the- * snippet writes it ("Café" for "cafe", since find matches accents).- */-export function findForMessageMatch(- match: Pick<OrchestrationThreadSearchMatch, "snippet" | "messageId">,- query: string,-): PendingFind {- const start = match.messageId ? { start: { entryId: match.messageId, occurrence: 0 } } : {};- // Apostrophes are straight in the query; straightening keeps offsets.- const together = messagePhrase(query)?.exec(match.snippet.replace(/[\u2018\u2019]/g, "'"));- if (together) {- return {- query: match.snippet.slice(together.index, together.index + together[0].length),- ...start,- };- }- const word =- messageSearchTokens(query).long.reduce(- (longest, token) => (token.length > longest.length ? token : longest),- "",- ) || query;- const ranges = findSearchTokenRanges(match.snippet, word);- // A whole word first, as search ranked it: "Café", not "Cafe" in "Cafeteria".- const shown =- ranges.find((range) => !/[\p{L}\p{N}]/u.test(match.snippet[range.end] ?? "")) ?? ranges[0];- return { query: shown ? match.snippet.slice(shown.start, shown.end) : word, ...start };-}--export function subscribeThreadFindQuery(listener: () => void): () => void {- window.addEventListener(THREAD_FIND_QUERY_EVENT, listener);- return () => window.removeEventListener(THREAD_FIND_QUERY_EVENT, listener);-}diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.tsindex 26d134b31ad..55d0647c9a8 100644--- a/apps/web/src/components/chat/threadFindHighlights.ts+++ b/apps/web/src/components/chat/threadFindHighlights.ts@@ -1,5 +1,5 @@import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";-import { useEffect, useLayoutEffect, useRef } from "react";+import { useEffect, useEffectEvent, useRef } from "react";import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText";const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find";@@ -119,14 +119,12 @@ export function useThreadFindHighlights(input: {const rangesRef = useRef<readonly ThreadFindRange[]>([]);const paintRef = useRef<ReturnType<typeof makeThreadFindHighlightPainter> | null>(null);- const selectionRef = useRef({ activeRowId, activeOccurrence, onActiveRange });- useLayoutEffect(() => {- selectionRef.current = { activeRowId, activeOccurrence, onActiveRange };- }, [activeRowId, activeOccurrence, onActiveRange]);+ // The observer repaints with whichever match is selected when text changes.+ const readSelection = useEffectEvent(() => ({ activeRowId, activeOccurrence, onActiveRange }));useEffect(() => {if (typeof CSS === "undefined" || !CSS.highlights || typeof Highlight === "undefined") {- selectionRef.current.onActiveRange(null);+ readSelection().onActiveRange(null);return;}const clearHighlights = () => {@@ -135,7 +133,7 @@ export function useThreadFindHighlights(input: {};rangesRef.current = [];if (!container || query.length === 0) {- selectionRef.current.onActiveRange(null);+ readSelection().onActiveRange(null);clearHighlights();return;}@@ -161,7 +159,7 @@ export function useThreadFindHighlights(input: {}for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);rangesRef.current = ranges;- paint(ranges, selectionRef.current);+ paint(ranges, readSelection());};let frame: number | null = null;const observer = new MutationObserver((mutations) => {@@ -208,9 +206,15 @@ export function useThreadFindHighlights(input: {};}, [container, query]);+ // onActiveRange is read at paint time: its identity follows the caller's+ // layout inputs, and repainting the active highlight for those is wasted work.useEffect(() => {- paintRef.current?.(rangesRef.current, { activeRowId, activeOccurrence, onActiveRange });- }, [activeOccurrence, activeRowId, onActiveRange]);+ paintRef.current?.(rangesRef.current, {+ activeRowId,+ activeOccurrence,+ onActiveRange: readSelection().onActiveRange,+ });+ }, [activeOccurrence, activeRowId]);}function makeThreadFindHighlightPainter(container: HTMLElement) {diff --git a/apps/web/src/components/chat/threadFindStore.test.ts b/apps/web/src/components/chat/threadFindStore.test.tsnew file mode 100644index 00000000000..f6620e77180--- /dev/null+++ b/apps/web/src/components/chat/threadFindStore.test.ts@@ -0,0 +1,94 @@+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";++import {+ attachThreadFindTimeline,+ closeThreadFind,+ findForMessageMatch,+ openThreadFind,+ openThreadFindOnQuery,+ retainThreadFindForRoute,+ setThreadFindQuery,+ useThreadFindStore,+} from "./threadFindStore";++const threadRef = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));+const otherRef = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-2"));+const threadKey = "env-1:thread-1";++function setup() {+ closeThreadFind();+ const readPosition = vi.fn(() => ({ entryId: "entry-9", occurrence: 1 }));+ return { readPosition, timeline: { threadKey, readPosition } };+}++describe("thread find store", () => {+ it("restarts an open query from the viewport of the timeline showing the thread", () => {+ const { readPosition, timeline } = setup();+ const detach = attachThreadFindTimeline(timeline);+ openThreadFind(threadKey);+ expect(useThreadFindStore.getState()).toMatchObject({ threadKey, focusRequestId: 1 });++ setThreadFindQuery(threadKey, " needle ");+ expect(readPosition).toHaveBeenLastCalledWith("needle");+ // Opening again refocuses and restarts the search from where the viewport is.+ openThreadFind(threadKey);+ expect(useThreadFindStore.getState()).toMatchObject({+ query: " needle ",+ focusRequestId: 2,+ start: { entryId: "entry-9", occurrence: 1 },+ navigationId: 2,+ requestId: 2,+ });+ detach();+ });++ it("opens a search result's find for a thread before its timeline shows it", () => {+ const { readPosition, timeline } = setup();+ const detach = attachThreadFindTimeline({ ...timeline, threadKey: "env-1:thread-2" });+ openThreadFindOnQuery(threadKey, { query: "Café", start: { entryId: "m", occurrence: 0 } });+ expect(useThreadFindStore.getState()).toMatchObject({+ threadKey,+ query: "Café",+ start: { entryId: "m", occurrence: 0 },+ });+ // Another thread's timeline does not answer for this one.+ setThreadFindQuery(threadKey, "Caf");+ expect(readPosition).not.toHaveBeenCalled();+ detach();+ });++ it("keeps find over Settings and Usage, and closes it on any other route", () => {+ setup();+ openThreadFindOnQuery(threadKey, { query: "x" });+ retainThreadFindForRoute({ modalPage: false, threadRef });+ retainThreadFindForRoute({ modalPage: true, threadRef: null });+ expect(useThreadFindStore.getState()).toMatchObject({ threadKey, query: "x" });++ retainThreadFindForRoute({ modalPage: false, threadRef: otherRef });+ expect(useThreadFindStore.getState()).toMatchObject({ threadKey: null, query: "" });++ openThreadFindOnQuery(threadKey, { query: "x" });+ retainThreadFindForRoute({ modalPage: false, threadRef: null });+ expect(useThreadFindStore.getState().threadKey).toBeNull();+ });+});++describe("findForMessageMatch", () => {+ it("opens find on the longest word as the snippet writes it, at the matched message", () => {+ expect(+ findForMessageMatch(+ { snippet: "The cafeteria, then the Café", messageId: MessageId.make("message-1") },+ "cafe",+ ),+ ).toEqual({ query: "Café", start: { entryId: "message-1", occurrence: 0 } });+ expect(findForMessageMatch({ snippet: "fix the sidebar lag" }, "fix sidebar")).toEqual({+ query: "sidebar",+ });+ // The whole query, when the snippet holds it as typed.+ expect(findForMessageMatch({ snippet: "then Vp run dev again" }, "vp run dev")).toEqual({+ query: "Vp run dev",+ });+ });+});diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.tsnew file mode 100644index 00000000000..d2ed7cd0403--- /dev/null+++ b/apps/web/src/components/chat/threadFindStore.ts@@ -0,0 +1,184 @@+import type {+ OrchestrationThreadSearchMatch,+ OrchestrationV2SearchThreadResult,+ ScopedThreadRef,+} from "@t3tools/contracts";+import { scopedThreadKey } from "@t3tools/client-runtime/environment";+import {+ findSearchTokenRanges,+ messagePhrase,+ messageSearchTokens,+} from "@t3tools/shared/paletteSearch";+import { create } from "zustand";+import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind";++export interface ThreadFindLocalSelection {+ readonly base: OrchestrationV2SearchThreadResult;+ readonly baseNavigationId: number;+ readonly activeIndex: number;+ readonly match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;+ readonly navigationId: number;+}++/** Find is open in at most one thread: the one the chat view shows. */+export interface ThreadFindState {+ readonly threadKey: string | null;+ readonly query: string;+ readonly offset: number;+ readonly start: ThreadFindStart | undefined;+ readonly focusRequestId: number;+ readonly navigationId: number;+ readonly requestId: number;+ readonly localSelection: ThreadFindLocalSelection | null;+}++export const CLOSED_THREAD_FIND: ThreadFindState = {+ threadKey: null,+ query: "",+ offset: 0,+ start: undefined,+ focusRequestId: 0,+ navigationId: 0,+ requestId: 0,+ localSelection: null,+};++export const useThreadFindStore = create<ThreadFindState>(() => CLOSED_THREAD_FIND);++/** What find needs from the timeline that shows a thread. */+interface ThreadFindTimeline {+ readonly threadKey: string;+ readonly readPosition: ThreadFindPositionReader;+}++let attachedTimeline: ThreadFindTimeline | null = null;++function timelineFor(threadKey: string): ThreadFindTimeline | null {+ return attachedTimeline?.threadKey === threadKey ? attachedTimeline : null;+}++/** Attaches the timeline showing a thread; returns the detach. */+export function attachThreadFindTimeline(timeline: ThreadFindTimeline): () => void {+ attachedTimeline = timeline;+ return () => {+ if (attachedTimeline === timeline) attachedTimeline = null;+ };+}++function readThreadFindPosition(threadKey: string, query: string): ThreadFindStart | undefined {+ return timelineFor(threadKey)?.readPosition(query);+}++/** Opens find, or refocuses it and restarts its search from the viewport when already open. */+export function openThreadFind(threadKey: string): void {+ const previous = useThreadFindStore.getState();+ const current = previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND;+ const query = current.query.trim();+ const start = query ? readThreadFindPosition(threadKey, query) : undefined;+ useThreadFindStore.setState({+ ...current,+ threadKey,+ focusRequestId: previous.focusRequestId + 1,+ ...(query+ ? {+ start,+ offset: 0,+ localSelection: null,+ navigationId: current.navigationId + 1,+ requestId: current.navigationId + 1,+ }+ : {}),+ });+}++export interface PendingThreadFind {+ readonly query: string;+ /** Where find starts, such as the message a palette result came from. */+ readonly start?: ThreadFindStart;+}++/**+ * Opens find on `query` in the thread, such as at the message a search result+ * came from. The thread's view shows it once it is on screen.+ */+export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind): void {+ const previous = useThreadFindStore.getState();+ useThreadFindStore.setState({+ ...(previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND),+ threadKey,+ query: find.query,+ offset: 0,+ start: find.start,+ localSelection: null,+ focusRequestId: previous.focusRequestId + 1,+ navigationId: previous.navigationId + 1,+ requestId: previous.navigationId + 1,+ });+}++export function setThreadFindQuery(threadKey: string, query: string): void {+ const start = readThreadFindPosition(threadKey, query.trim());+ useThreadFindStore.setState((previous) => ({+ query,+ offset: 0,+ start,+ localSelection: null,+ navigationId: previous.navigationId + 1,+ requestId: previous.navigationId + 1,+ }));+}++export function closeThreadFind(): void {+ useThreadFindStore.setState(CLOSED_THREAD_FIND);+}++/**+ * Find belongs to the thread it was opened in: a route showing anything else+ * closes it. Settings and Usage draw over the thread, so they keep it.+ */+export function retainThreadFindForRoute(route: {+ readonly modalPage: boolean;+ readonly threadRef: ScopedThreadRef | null;+}): void {+ if (route.modalPage) return;+ const { threadKey } = useThreadFindStore.getState();+ const shownKey = route.threadRef ? scopedThreadKey(route.threadRef) : null;+ if (threadKey !== null && threadKey !== shownKey) closeThreadFind();+}++/** Whether find is open in `thread`, as long as find is available there. */+export function useThreadFindOpen(thread: ScopedThreadRef | null, enabled: boolean): boolean {+ const openThreadKey = useThreadFindStore((state) => state.threadKey);+ return enabled && thread !== null && openThreadKey === scopedThreadKey(thread);+}++/**+ * The find a message search result opens, at the matched message: the whole+ * query when the snippet holds it as typed ("vp run dev"), else its longest+ * word, as the most telling ("sidebar" in "fix sidebar"), written as the+ * snippet writes it ("Café" for "cafe", since find matches accents).+ */+export function findForMessageMatch(+ match: Pick<OrchestrationThreadSearchMatch, "snippet" | "messageId">,+ query: string,+): PendingThreadFind {+ const start = match.messageId ? { start: { entryId: match.messageId, occurrence: 0 } } : {};+ // Apostrophes are straight in the query; straightening keeps offsets.+ const together = messagePhrase(query)?.exec(match.snippet.replace(/[\u2018\u2019]/g, "'"));+ if (together) {+ return {+ query: match.snippet.slice(together.index, together.index + together[0].length),+ ...start,+ };+ }+ const word =+ messageSearchTokens(query).long.reduce(+ (longest, token) => (token.length > longest.length ? token : longest),+ "",+ ) || query;+ const ranges = findSearchTokenRanges(match.snippet, word);+ // A whole word first, as search ranked it: "Café", not "Cafe" in "Cafeteria".+ const shown =+ ranges.find((range) => !/[\p{L}\p{N}]/u.test(match.snippet[range.end] ?? "")) ?? ranges[0];+ return { query: shown ? match.snippet.slice(shown.start, shown.end) : word, ...start };+}diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.tsindex ed0d011c8fc..a5b1423b414 100644--- a/apps/web/src/components/chat/useThreadFind.ts+++ b/apps/web/src/components/chat/useThreadFind.ts@@ -1,43 +1,24 @@import type { InlineSkill } from "@t3tools/shared/inlineSkills";import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tools/contracts";import { scopedThreadKey } from "@t3tools/client-runtime/environment";-import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";-import { useStableCallback } from "~/hooks/useStableCallback";+import { useEffect, useEffectEvent, useRef, useState } from "react";import { orchestrationEnvironment } from "~/state/orchestration";import { useThreadProjection } from "~/state/entities";import { useEnvironmentQuery } from "~/state/query";import { useDebouncedValue } from "~/state/queries";+import { type ThreadFindMatch, type ThreadFindStart, stepThreadFindIndex } from "./threadFind";import {- type ThreadFindPositionReader,- type ThreadFindStart,- stepThreadFindIndex,-} from "./threadFind";-import {- subscribeThreadFindOpen,- subscribeThreadFindQuery,- takeThreadFindQuery,-} from "./threadFindActionBus";-import { toastManager } from "../ui/toast";+ CLOSED_THREAD_FIND,+ closeThreadFind,+ setThreadFindQuery,+ useThreadFindOpen,+ useThreadFindStore,+ type ThreadFindLocalSelection,+ type ThreadFindState,+} from "./threadFindStore";const EMPTY_SKILLS: readonly InlineSkill[] = [];-const CLOSED_FIND = {- threadKey: null as string | null,- query: "",- offset: 0,- start: undefined as ThreadFindStart | undefined,- focusRequestId: 0,- navigationId: 0,- requestId: 0,- localSelection: null as {- base: OrchestrationV2SearchThreadResult;- baseNavigationId: number;- activeIndex: number;- match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;- navigationId: number;- } | null,-};-export function useThreadFind({thread,enabled,@@ -52,77 +33,17 @@ export function useThreadFind({// Read here rather than passed in: a streamed delta re-renders only the find// provider, which refreshes open results from it.const content = useThreadProjection(enabled ? thread : null)?.projection;- // Held in state so the timeline props that carry it can be stored in state too.- const [positionReader] = useState<RefObject<ThreadFindPositionReader | null>>(() => ({- current: null,- }));const lastContentRef = useRef(content);const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const refreshAfterSearchRef = useRef(false);const threadKey = thread ? scopedThreadKey(thread) : null;- const [state, setState] = useState(CLOSED_FIND);- if (state.threadKey !== null && (!enabled || state.threadKey !== threadKey))- setState(CLOSED_FIND);- const isOpen = enabled && threadKey !== null && state.threadKey === threadKey;- const open = useStableCallback(() => {- if (threadKey === null) return;- if (!enabled) {- toastManager.add({- id: "thread-find-unavailable",- title: "Thread search is unavailable on this server.",- description: "Update the server to enable it.",- });- return;- }- const start =- state.threadKey === threadKey && state.query.trim()- ? positionReader.current?.(state.query.trim())- : undefined;- setState((previous) => {- const current = previous.threadKey === threadKey ? previous : CLOSED_FIND;- return {- ...current,- threadKey,- focusRequestId: previous.focusRequestId + 1,- ...(current.query.trim()- ? {- start,- offset: 0,- localSelection: null,- navigationId: current.navigationId + 1,- requestId: current.navigationId + 1,- }- : {}),- };- });- });- const close = useStableCallback(() => setState(CLOSED_FIND));- useEffect(() => subscribeThreadFindOpen(open), [open]);- const openOnQuery = useStableCallback((query: string, start?: ThreadFindStart) => {- if (threadKey === null) return;- setState((previous) => ({- ...(previous.threadKey === threadKey ? previous : CLOSED_FIND),- threadKey,- query,- offset: 0,- start,- localSelection: null,- focusRequestId: previous.focusRequestId + 1,- navigationId: previous.navigationId + 1,- requestId: previous.navigationId + 1,- }));- });- // A palette message result opens find on its query, at its message, once- // this thread shows.- useEffect(() => {- if (threadKey === null || !enabled) return;- const take = () => {- const find = takeThreadFindQuery(threadKey);- if (find !== null) openOnQuery(find.query, find.start);- };- take();- return subscribeThreadFindQuery(take);- }, [enabled, openOnQuery, threadKey]);+ const isOpen = useThreadFindOpen(thread, enabled);+ const stored = useThreadFindStore();+ const state = isOpen ? stored : CLOSED_THREAD_FIND;+ const setState = (update: (previous: ThreadFindState) => Partial<ThreadFindState>) =>+ useThreadFindStore.setState((previous) =>+ previous.threadKey === threadKey ? update(previous) : previous,+ );const remote = useServerResults(isOpen ? thread : null,@@ -153,7 +74,7 @@ export function useThreadFind({const navigationId = localSelection?.navigationId ?? remote.navigationId;const findExpanded = isOpen && state.query.trim().length > 0;const findQuery = isOpen && remote.data?.match ? state.query : "";- const nextTimeline = {+ const nextTimeline: TimelineFields = {findOpen: isOpen,findExpanded,findQuery,@@ -164,19 +85,13 @@ export function useThreadFind({findNavigationId: navigationId,};// Keep timeline identity stable during count and response updates to avoid extra jumps.- const [storedTimeline, setTimeline] = useState(() => ({- fields: nextTimeline,- props: { ...nextTimeline, findPositionReaderRef: positionReader },- }));+ const [storedTimeline, setTimeline] = useState(nextTimeline);let timeline = storedTimeline;- if (!sameTimeline(timeline.fields, nextTimeline)) {- timeline = {- fields: nextTimeline,- props: { ...nextTimeline, findPositionReaderRef: positionReader },- };+ if (!sameTimeline(timeline, nextTimeline)) {+ timeline = nextTimeline;setTimeline(timeline);}- const match = timeline.fields.activeFindMatch;+ const match = timeline.activeFindMatch;const step = (delta: number) => {if (count === 0 || counting) return;setState((previous) => {@@ -235,41 +150,40 @@ export function useThreadFind({});};- const refreshLiveResultsRef = useRef(() => {});- useLayoutEffect(() => {- refreshLiveResultsRef.current = () => {- if (!isOpen || !state.query.trim()) return;- // Coalesce paging updates while the server counts to avoid restarting scans.- if (progressive && remote.isPending) {- refreshAfterSearchRef.current = true;- return;- }- if (!match || state.navigationId !== navigationId) {- remote.refresh();- return;- }- const start = { entryId: match.entryId, occurrence: match.occurrence };- if (- state.offset === 0 &&- state.start?.entryId === start.entryId &&- state.start.occurrence === start.occurrence &&- state.requestId === state.navigationId- ) {- remote.refresh();- } else {- setState((previous) => ({- ...previous,- start,- offset: 0,- requestId: previous.navigationId,- }));- }- };+ // Runs from the refresh timer and after a coalesced search settles, against+ // the results and selection showing by then.+ const refreshLiveResults = useEffectEvent(() => {+ if (!isOpen || !state.query.trim()) return;+ // Coalesce paging updates while the server counts to avoid restarting scans.+ if (progressive && remote.isPending) {+ refreshAfterSearchRef.current = true;+ return;+ }+ if (!match || state.navigationId !== navigationId) {+ remote.refresh();+ return;+ }+ const start = { entryId: match.entryId, occurrence: match.occurrence };+ if (+ state.offset === 0 &&+ state.start?.entryId === start.entryId &&+ state.start.occurrence === start.occurrence &&+ state.requestId === state.navigationId+ ) {+ remote.refresh();+ } else {+ setState((previous) => ({+ ...previous,+ start,+ offset: 0,+ requestId: previous.navigationId,+ }));+ }});useEffect(() => {if (!refreshAfterSearchRef.current || remote.isPending) return;refreshAfterSearchRef.current = false;- if (!remote.error) refreshLiveResultsRef.current();+ if (!remote.error) refreshLiveResults();}, [remote.isPending, remote.error]);useEffect(() => {if (lastContentRef.current === content) return;@@ -277,7 +191,7 @@ export function useThreadFind({if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;refreshTimerRef.current = setTimeout(() => {refreshTimerRef.current = null;- refreshLiveResultsRef.current();+ refreshLiveResults();}, 300);}, [content, isOpen, state.query]);useEffect(() => {@@ -290,9 +204,6 @@ export function useThreadFind({}, [threadKey, isOpen, state.query]);return {- isOpen,- open,- close,barProps: {open: isOpen,query: state.query,@@ -303,29 +214,23 @@ export function useThreadFind({focusRequestId: state.focusRequestId,onRetry: remote.refresh,onQueryChange: (query: string) => {- const start = positionReader.current?.(query.trim());- setState((previous) => ({- ...previous,- query,- offset: 0,- start,- localSelection: null,- navigationId: previous.navigationId + 1,- requestId: previous.navigationId + 1,- }));+ if (threadKey !== null) setThreadFindQuery(threadKey, query);},onNext: () => step(1),onPrevious: () => step(-1),- onClose: close,+ onClose: closeThreadFind,},- timelineProps: timeline.props,+ timelineProps: timeline,};}-type TimelineFields = Omit<- ReturnType<typeof useThreadFind>["timelineProps"],- "findPositionReaderRef"->;+interface TimelineFields {+ readonly findOpen: boolean;+ readonly findExpanded: boolean;+ readonly findQuery: string;+ readonly activeFindMatch: ThreadFindMatch | null;+ readonly findNavigationId: number;+}function sameTimeline(a: TimelineFields, b: TimelineFields) {const aMatch = a.activeFindMatch;@@ -344,7 +249,7 @@ function sameTimeline(a: TimelineFields, b: TimelineFields) {}function rebaseLocalSelection(- selection: typeof CLOSED_FIND.localSelection,+ selection: ThreadFindLocalSelection | null,data: OrchestrationV2SearchThreadResult | null,navigationId: number,) {diff --git a/apps/web/src/components/chat/useThreadFindNavigation.ts b/apps/web/src/components/chat/useThreadFindNavigation.tsindex 259b02ed9cd..4bedf88b026 100644--- a/apps/web/src/components/chat/useThreadFindNavigation.ts+++ b/apps/web/src/components/chat/useThreadFindNavigation.ts@@ -1,10 +1,176 @@import type { LegendListRef } from "@legendapp/list/react";-import { useEffect, useLayoutEffect, useRef, type RefObject } from "react";+import { useEffect, useEffectEvent, useRef, type RefObject } from "react";import type { ThreadFindMatch } from "./threadFind";import { useThreadFindHighlights } from "./threadFindHighlights";const FIND_MATCH_VIEW_MARGIN = 96;+type FindEntries = readonly { readonly id: string }[];++interface RevealInputs {+ readonly matchKey: string | null;+ readonly rowIndex: number;+ readonly entries: FindEntries;+ readonly listReady: boolean;+ readonly historyLoading: boolean;+ readonly historyError: string | null;+ readonly contentInsetEndAdjustment: number;+ readonly container: HTMLElement | null;+}++/** Positioning bookkeeping that outlives a render: pending jumps and the pinned match during paging. */+interface RevealState {+ positioning: { key: string; rowIndex: number; entries: FindEntries } | null;+ settledMatch: string | null;+ activeRange: Range | null;+ pagingPosition: { key: string; entries: FindEntries; top: number } | null;+ revealedMatch: string | null;+ positionedEntries: FindEntries | null;+}++/**+ * Brings the active match into view. Async continuations re-enter with the+ * inputs current by then, and stop once the match changes or the list unmounts.+ */+function revealThreadFindMatch(+ range: Range | null,+ inputs: RevealInputs,+ context: {+ readonly state: RevealState;+ readonly listRef: RefObject<LegendListRef | null>;+ readonly readInputs: () => RevealInputs;+ },+): void {+ const { state, listRef, readInputs } = context;+ const {+ matchKey,+ rowIndex,+ entries,+ listReady,+ historyLoading,+ historyError,+ contentInsetEndAdjustment,+ container,+ } = inputs;+ state.activeRange = range;+ if (!matchKey) {+ state.positioning = null;+ state.settledMatch = null;+ state.revealedMatch = null;+ state.pagingPosition = null;+ return;+ }+ const list = listRef.current;+ const stillCurrent = () =>+ list !== null && listRef.current === list && readInputs().matchKey === matchKey;+ const revealAgain = () => revealThreadFindMatch(state.activeRange, readInputs(), context);+ const pagingPosition = state.pagingPosition;+ if (pagingPosition && pagingPosition.key !== matchKey) state.pagingPosition = null;+ if (+ range?.startContainer.isConnected &&+ pagingPosition?.key === matchKey &&+ pagingPosition.entries !== entries+ ) {+ const restore = () => {+ const pinned = state.pagingPosition;+ const currentRange = state.activeRange;+ if (!stillCurrent() || !pinned || !currentRange?.startContainer.isConnected) return;+ const delta = currentRange.getBoundingClientRect().top - pinned.top;+ const scroll = listRef.current?.getState?.().scroll;+ if (Math.abs(delta) >= 1 && typeof scroll === "number")+ listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });+ };+ pagingPosition.entries = entries;+ restore();+ // The list measures newly inserted activity after the first layout pass.+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ restore();+ if (!readInputs().historyLoading && state.pagingPosition === pagingPosition)+ state.pagingPosition = null;+ }),+ );+ }+ if (historyError) state.pagingPosition = null;+ if (state.revealedMatch === matchKey) return;+ if (!listReady || rowIndex < 0) return;+ const materialize = () => {+ const previous = state.positioning;+ if (+ !list ||+ (previous?.key === matchKey && previous.rowIndex === rowIndex && previous.entries === entries)+ )+ return;+ // Activity can insert rows during LegendList layout; retarget pending jumps.+ const request = { key: matchKey, rowIndex, entries };+ state.positioning = request;++ void list+ .scrollToIndex({+ index: rowIndex,+ animated: false,+ viewOffset: FIND_MATCH_VIEW_MARGIN,+ })+ .then(() => {+ if (state.positioning !== request || !stillCurrent()) return;++ state.positionedEntries = entries;+ state.settledMatch = matchKey;+ revealAgain();+ });+ };+ if (!range) {+ if (container) materialize();+ return;+ }++ const codeScroller = range.startContainer.parentElement?.closest("pre");+ if (codeScroller) {+ const rect = range.getBoundingClientRect();+ const viewport = codeScroller.getBoundingClientRect();+ if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;+ else if (rect.right > viewport.right)+ codeScroller.scrollLeft += rect.right - viewport.right + 16;+ }+ const rect = range.getBoundingClientRect();+ const viewport = container?.getBoundingClientRect();+ if (!viewport || rect.height === 0) return;+ const margin = Math.min(+ FIND_MATCH_VIEW_MARGIN,+ Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),+ );+ const top = viewport.top + margin;+ const bottom = viewport.bottom - margin - contentInsetEndAdjustment;+ const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;+ // DOM text can precede settled row sizes; wait before measuring offscreen matches.+ if (+ Math.abs(delta) >= 1 &&+ state.positionedEntries !== entries &&+ state.settledMatch !== matchKey+ ) {+ materialize();+ return;+ }+ const scroll = list?.getState?.().scroll;+ state.positionedEntries = entries;++ state.revealedMatch = matchKey;+ if (historyLoading) state.pagingPosition = { key: matchKey, entries, top: rect.top - delta };+ if (Math.abs(delta) >= 1 && typeof scroll === "number") {+ list?.scrollToOffset({ offset: scroll + delta, animated: false });+ requestAnimationFrame(() => {+ if (!stillCurrent()) return;+ if (+ listRef.current?.getState?.().scroll === scroll &&+ range.getBoundingClientRect().top === rect.top+ )+ return;+ state.revealedMatch = null;+ revealAgain();+ });+ }+}+export function useThreadFindNavigation({container,query,@@ -22,7 +188,7 @@ export function useThreadFindNavigation({match: ThreadFindMatch | null;navigationId: number;rowIndex: number;- entries: readonly { readonly id: string }[];+ entries: FindEntries;listRef: RefObject<LegendListRef | null>;contentInsetEndAdjustment: number;listReady: boolean;@@ -36,50 +202,50 @@ export function useThreadFindNavigation({| undefined;}) {const matchKey = match ? `${navigationId}:${query}:${match.entryId}:${match.occurrence}` : null;- const positioningRef = useRef<{- key: string;- rowIndex: number;- entries: typeof entries;- } | null>(null);- const settledMatchRef = useRef<string | null>(null);- const currentMatchKeyRef = useRef(matchKey);- const activeRangeRef = useRef<Range | null>(null);- const pagingPositionRef = useRef<{ key: string; entries: typeof entries; top: number } | null>(- null,- );- const currentEntriesRef = useRef(entries);- useLayoutEffect(() => {- currentEntriesRef.current = entries;- }, [entries]);+ const historyLoading = historyControls?.loading ?? false;+ const historyError = historyControls?.error ?? null;+ const stateRef = useRef<RevealState>({+ positioning: null,+ settledMatch: null,+ activeRange: null,+ pagingPosition: null,+ revealedMatch: null,+ positionedEntries: null,+ });+ const readInputs = useEffectEvent((): RevealInputs => ({+ matchKey,+ rowIndex,+ entries,+ listReady,+ historyLoading,+ historyError,+ contentInsetEndAdjustment,+ container,+ }));+ // H/Z: stays an effect. The listener compares against the entries rendered at+ // scroll time; the viewport ref callback in MessagesTimeline cannot read+ // them without a latest-ref mirror, and capturing them would re-attach the+ // viewport (observers, citation dismissal) on every streamed entry.useEffect(() => {if (!container) return;const onScroll = () => {- const position = pagingPositionRef.current;- const range = activeRangeRef.current;+ const state = stateRef.current;+ const position = state.pagingPosition;+ const range = state.activeRange;if (!position ||- position.entries !== currentEntriesRef.current ||+ position.entries !== readInputs().entries ||!range?.startContainer.isConnected)return;const rect = range.getBoundingClientRect();const viewport = container.getBoundingClientRect();- if (rect.bottom < viewport.top || rect.top > viewport.bottom)- pagingPositionRef.current = null;+ if (rect.bottom < viewport.top || rect.top > viewport.bottom) state.pagingPosition = null;else position.top = rect.top;};container.addEventListener("scroll", onScroll, { passive: true });return () => container.removeEventListener("scroll", onScroll);}, [container]);- const revealRef = useRef<(range: Range | null) => void>(() => {});- useLayoutEffect(() => {- currentMatchKeyRef.current = matchKey;- return () => {- currentMatchKeyRef.current = null;- };- }, [matchKey]);- const revealedMatchRef = useRef<string | null>(null);- const positionedEntriesRef = useRef<typeof entries | null>(null);const requestedPagesRef = useRef<{ key: string | null; pages: Set<string> }>({key: null,pages: new Set(),@@ -102,140 +268,39 @@ export function useThreadFindNavigation({historyControls.onLoadEarlier(match.entryId);}, [entries, historyControls, listReady, match, matchKey, rowIndex]);- const reveal = (range: Range | null) => {- activeRangeRef.current = range;- if (!matchKey) {- positioningRef.current = null;- settledMatchRef.current = null;- revealedMatchRef.current = null;- pagingPositionRef.current = null;- return;- }- const pagingPosition = pagingPositionRef.current;- if (pagingPosition && pagingPosition.key !== matchKey) pagingPositionRef.current = null;- if (- range?.startContainer.isConnected &&- pagingPosition?.key === matchKey &&- pagingPosition.entries !== entries- ) {- const restore = () => {- const pinned = pagingPositionRef.current;- const currentRange = activeRangeRef.current;- if (- currentMatchKeyRef.current !== matchKey ||- !pinned ||- !currentRange?.startContainer.isConnected- )- return;- const delta = currentRange.getBoundingClientRect().top - pinned.top;- const scroll = listRef.current?.getState?.().scroll;- if (Math.abs(delta) >= 1 && typeof scroll === "number")- listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });- };- pagingPosition.entries = entries;- restore();- // The list measures newly inserted activity after the first layout pass.- requestAnimationFrame(() =>- requestAnimationFrame(() => {- restore();- if (!historyControls?.loading && pagingPositionRef.current === pagingPosition)- pagingPositionRef.current = null;- }),- );- }- if (historyControls?.error) pagingPositionRef.current = null;- if (revealedMatchRef.current === matchKey) return;- if (!listReady || rowIndex < 0) return;- const materialize = () => {- const list = listRef.current;- const previous = positioningRef.current;- if (- !list ||- (previous?.key === matchKey &&- previous.rowIndex === rowIndex &&- previous.entries === entries)- )- return;- // Activity can insert rows during LegendList layout; retarget pending jumps.- const request = { key: matchKey, rowIndex, entries };- positioningRef.current = request;-- void list- .scrollToIndex({- index: rowIndex,- animated: false,- viewOffset: FIND_MATCH_VIEW_MARGIN,- })- .then(() => {- if (positioningRef.current !== request || currentMatchKeyRef.current !== matchKey) return;-- positionedEntriesRef.current = entries;- settledMatchRef.current = matchKey;- revealRef.current(activeRangeRef.current);- });- };- if (!range) {- if (container) materialize();- return;- }-- const codeScroller = range.startContainer.parentElement?.closest("pre");- if (codeScroller) {- const rect = range.getBoundingClientRect();- const viewport = codeScroller.getBoundingClientRect();- if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;- else if (rect.right > viewport.right)- codeScroller.scrollLeft += rect.right - viewport.right + 16;- }- const rect = range.getBoundingClientRect();- const viewport = container?.getBoundingClientRect();- if (!viewport || rect.height === 0) return;- const margin = Math.min(- FIND_MATCH_VIEW_MARGIN,- Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),- );- const top = viewport.top + margin;- const bottom = viewport.bottom - margin - contentInsetEndAdjustment;- const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;- // DOM text can precede settled row sizes; wait before measuring offscreen matches.- if (- Math.abs(delta) >= 1 &&- positionedEntriesRef.current !== entries &&- settledMatchRef.current !== matchKey- ) {- materialize();- return;- }- const scroll = listRef.current?.getState?.().scroll;- positionedEntriesRef.current = entries;-- revealedMatchRef.current = matchKey;- if (historyControls?.loading)- pagingPositionRef.current = { key: matchKey, entries, top: rect.top - delta };- if (Math.abs(delta) >= 1 && typeof scroll === "number") {- listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });- requestAnimationFrame(() => {- if (currentMatchKeyRef.current !== matchKey) return;- if (- listRef.current?.getState?.().scroll === scroll &&- range.getBoundingClientRect().top === rect.top- )- return;- revealedMatchRef.current = null;- revealRef.current(activeRangeRef.current);- });- }- };-- useLayoutEffect(() => {- revealRef.current = reveal;- }, [reveal]);+ const reveal = useEffectEvent((range: Range | null, inputs: RevealInputs) =>+ revealThreadFindMatch(range, inputs, { state: stateRef.current, listRef, readInputs }),+ );useThreadFindHighlights({container,query,activeRowId: match?.entryId ?? null,activeOccurrence: match?.occurrence ?? 0,- onActiveRange: reveal,+ onActiveRange: (range) => reveal(range, readInputs()),});+ // Positioning also depends on the list: a loaded page or a shifted row must+ // retry the jump for the same selection. Declared after the highlight+ // effects so it reuses the range they just resolved.+ useEffect(() => {+ reveal(stateRef.current.activeRange, {+ matchKey,+ rowIndex,+ entries,+ listReady,+ historyLoading,+ historyError,+ contentInsetEndAdjustment,+ container,+ });+ }, [+ container,+ matchKey,+ rowIndex,+ entries,+ listReady,+ historyLoading,+ historyError,+ contentInsetEndAdjustment,+ ]);}diff --git a/apps/web/src/components/chat/useThreadFindPositionReader.ts b/apps/web/src/components/chat/useThreadFindPositionReader.tsindex 5afc9ca2548..c64a910487f 100644--- a/apps/web/src/components/chat/useThreadFindPositionReader.ts+++ b/apps/web/src/components/chat/useThreadFindPositionReader.ts@@ -7,11 +7,12 @@ import {type TimelineLatestRun,} from "./MessagesTimeline.logic";import type { ThreadFindPositionReader } from "./threadFind";+import { attachThreadFindTimeline } from "./threadFindStore";import { readThreadFindPosition } from "./threadFindPosition";-/** Publishes how to read the find position of the timeline's current viewport. */+/** Hands thread find how to read the find position of this timeline's viewport. */export function useThreadFindPositionReader({- findPositionReaderRef,+ threadKey,timelineViewportElement,findFoldRunIds,timelineEntries,@@ -22,7 +23,7 @@ export function useThreadFindPositionReader({rows,contentInsetEndAdjustment,}: {- readonly findPositionReaderRef: React.RefObject<ThreadFindPositionReader | null> | undefined;+ readonly threadKey: string;readonly timelineViewportElement: HTMLDivElement | null;readonly findFoldRunIds: ReadonlyMap<string, RunId> | null;readonly timelineEntries: ReadonlyArray<TimelineEntry>;@@ -33,8 +34,9 @@ export function useThreadFindPositionReader({readonly rows: MessagesTimelineRow[];readonly contentInsetEndAdjustment: number;}) {+ // Layout effect so a find opened right after a thread switch reads this viewport.useLayoutEffect(() => {- if (!findPositionReaderRef || !timelineViewportElement) return;+ if (!timelineViewportElement) return;const read: ThreadFindPositionReader = (query) => {const foldRunIds =findFoldRunIds ??@@ -81,15 +83,12 @@ export function useThreadFindPositionReader({contentInsetEndAdjustment,);};- findPositionReaderRef.current = read;- return () => {- if (findPositionReaderRef.current === read) findPositionReaderRef.current = null;- };+ return attachThreadFindTimeline({ threadKey, readPosition: read });}, [contentInsetEndAdjustment,findFoldRunIds,- findPositionReaderRef,isWorking,+ threadKey,latestRun,rows,runlessWorkActive,diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsxindex f8727d59c7e..d965760e827 100644--- a/apps/web/src/routes/_chat.tsx+++ b/apps/web/src/routes/_chat.tsx@@ -8,7 +8,8 @@ import { isCommandPaletteOpen } from "../commandPaletteBus";import { ThreadRouteView } from "../components/ThreadRouteView";import { isAppModalPage } from "../components/sidebar/mainAppLocation";import { SidebarInset } from "../components/ui/sidebar";-import type { ThreadRouteTarget } from "../threadRoutes";+import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../threadRoutes";+import { retainThreadFindForRoute } from "../components/chat/threadFindStore";import { ThreadLinkPrompt } from "../components/promptLinks/ThreadLinkPrompt";import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";import { openCommandPalette } from "../commandPaletteBus";@@ -234,13 +235,29 @@ function ChatRouteLayout() {}export const Route = createFileRoute("/_chat")({- beforeLoad: async ({ context }) => {+ beforeLoad: async ({ context, location }) => {if (context.authGateState.status !== "authenticated" &&context.authGateState.status !== "hosted-static") {throw redirect({ to: "/pair", replace: true });}+ return { appModalPage: isAppModalPage(location.pathname) };},component: ChatRouteLayout,+ // Every match carries the whole location's params, so this layout sees the thread route's too.+ onEnter: ({ context, params }) => retainThreadFindForRouteMatch(context.appModalPage, params),+ onStay: ({ context, params }) => retainThreadFindForRouteMatch(context.appModalPage, params),+ onLeave: () => retainThreadFindForRoute({ modalPage: false, threadRef: null }),});++function retainThreadFindForRouteMatch(+ modalPage: boolean,+ params: Partial<Record<"environmentId" | "threadId", string>>,+) {+ const target = resolveThreadRouteTarget(params);+ retainThreadFindForRoute({+ modalPage,+ threadRef: target?.kind === "server" ? target.threadRef : null,+ });+}