The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
refactor(web): thread find state lives in one store instead of event buses and mirrors (#25073)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 18:13 UTC
f16ae12bb6ed6e50dcaffff79c4205ca0f2169ad
15 files changed
+644
-495
apps/web/src/components/ChatView.tsx
+9
-11
@@ -19,7 +19,8 @@ import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useCh
19
import { useComposerSend } from "./chat/useComposerSend";
20
import { useComposerResume } from "./chat/useComposerResume";
21
import { useImplementPlanInNewThread } from "./chat/useProposedPlanSend";
22
-import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";
22
+import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider";
23
+import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore";
24
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
25
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
26
import { resolveDraftHeroState } from "./ChatView.logic";
@@ -2656,10 +2657,9 @@ export default function ChatView(props: ChatViewProps) {
2657
const timelineSkills = activeProviderStatus
2658
? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)
2659
: EMPTY_PROVIDER_SKILLS;
2659
- const threadFindControlsRef = useRef<ThreadFindControls | null>(null);
2660
- const [isThreadFindActive, setIsThreadFindActive] = useState(false);
2661
- const openThreadFind = () => threadFindControlsRef.current?.open();
2662
- const closeThreadFind = () => threadFindControlsRef.current?.close();
2660
+ const threadFindEnabled =
2661
+ isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline;
2662
+ const isThreadFindActive = useThreadFindOpen(activeThreadRef, threadFindEnabled);
2663
2664
useChatShortcuts({
2665
enabled: activeThreadId !== null && !backgroundThread,
@@ -2681,8 +2681,9 @@ export default function ChatView(props: ChatViewProps) {
2681
if (!event.repeat) copyActiveThreadReference();
2682
},
2683
"chat.find": () => {
2684
- if (!isServerThread || serverConfig?.threadFind !== true) return false;
2685
- openThreadFind();
2684
+ if (!isServerThread || serverConfig?.threadFind !== true || activeThreadKey === null)
2685
+ return false;
2686
+ openThreadFind(activeThreadKey);
2687
},
2688
"composer.cycleHost": ({ event }) => {
2689
if (!canChangeEnvironment) return false;
@@ -3208,11 +3209,8 @@ export default function ChatView(props: ChatViewProps) {
3209
skills: timelineSkills,
3210
progressive: serverConfig?.threadFindProgressive === true,
3211
thread: activeThreadRef,
3211
- enabled:
3212
- isServerThread && serverConfig?.threadFind === true && !paintOnlyDisplayedTimeline,
3212
+ enabled: threadFindEnabled,
3213
}}
3214
- controlsRef={threadFindControlsRef}
3215
- onOpenChange={setIsThreadFindActive}
3214
detailsCardTopInset={isThreadFindActive ? THREAD_FIND_BAR_RESERVED_HEIGHT : 0}
3215
composerOverlayElement={isDraftHeroState ? null : composerOverlayElement}
3216
data-chat-workspace-drop-target="true"
apps/web/src/components/CommandPalette.tsx
+19
-7
@@ -1,7 +1,11 @@
1
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
2
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
3
4
-import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
4
+import {
5
+ scopedThreadKey,
6
+ scopeProjectRef,
7
+ scopeThreadRef,
8
+} from "@t3tools/client-runtime/environment";
9
import {
10
canCreateProjectInEnvironment,
11
getCloneDestinationBrowsePath,
@@ -66,7 +70,7 @@ import {
70
TextSearchIcon,
71
UserPlusIcon,
72
} from "lucide-react";
69
-import { requestThreadFindOpen } from "./chat/threadFindActionBus";
73
+import { openThreadFind } from "./chat/threadFindStore";
74
import {
75
useDeferredValue,
76
useEffect,
@@ -729,7 +733,9 @@ function OpenCommandPaletteDialog(props: {
733
734
const { projectCwdById, projectByKey, projectTitleById } = useProjectLookups();
735
732
- const activeThreadId = activeThread?.id;
736
+ const activeThreadKey = activeThread
737
+ ? scopedThreadKey(scopeThreadRef(activeThread.environmentId, activeThread.id))
738
+ : null;
739
const supportsThreadFind =
740
environments.find((environment) => environment.environmentId === activeThread?.environmentId)
741
?.serverConfig?.threadFind === true;
@@ -1256,7 +1262,7 @@ function OpenCommandPaletteDialog(props: {
1262
});
1263
}
1264
1259
- if (activeThreadId && supportsThreadFind) {
1265
+ if (activeThreadKey !== null && supportsThreadFind) {
1266
actionItems.push({
1267
kind: "action",
1268
value: "find-current-thread",
@@ -1265,7 +1271,7 @@ function OpenCommandPaletteDialog(props: {
1271
icon: <TextSearchIcon className={ITEM_ICON_CLASS} />,
1272
shortcutCommand: "chat.find",
1273
run: async () => {
1268
- requestThreadFindOpen();
1274
+ openThreadFind(activeThreadKey);
1275
},
1276
});
1277
}
@@ -2411,11 +2417,17 @@ function OpenCommandPaletteDialog(props: {
2417
return;
2418
}
2419
// ChatView ignores shortcuts while the palette is open, so intercept find here.
2414
- if (command === "chat.find" && activeThreadId && !event.nativeEvent.isComposing) {
2420
+ if (command === "chat.find" && activeThreadKey !== null && !event.nativeEvent.isComposing) {
2421
event.preventDefault();
2422
event.stopPropagation();
2423
setOpen(false);
2418
- requestThreadFindOpen();
2424
+ if (supportsThreadFind) openThreadFind(activeThreadKey);
2425
+ else
2426
+ toastManager.add({
2427
+ id: "thread-find-unavailable",
2428
+ title: "Thread search is unavailable on this server.",
2429
+ description: "Update the server to enable it.",
2430
+ });
2431
return;
2432
}
2433
apps/web/src/components/CommandPaletteThreadItems.tsx
+2
-2
@@ -1,5 +1,5 @@
1
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
-import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";
2
+import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";
3
import {
4
claimThreadOpen,
5
nextShownOrder,
@@ -218,7 +218,7 @@ export function useCommandPaletteThreadItems(input: {
218
// Opens the thread with find on the word at the matched message, so it is in view.
219
run: async () => {
220
await item.run();
221
- requestThreadFindQuery(
221
+ openThreadFindOnQuery(
222
scopedThreadKey(scopeThreadRef(match.environmentId, match.threadId)),
223
findForMessageMatch(match, messageSearch.query),
224
);
apps/web/src/components/Sidebar.tsx
+2
-2
@@ -40,7 +40,7 @@ import {
40
type ShownOrder,
41
} from "@t3tools/client-runtime/state/thread-search";
42
import { foldSearchQuery, rankMessageMatches } from "@t3tools/shared/paletteSearch";
43
-import { findForMessageMatch, requestThreadFindQuery } from "./chat/threadFindActionBus";
43
+import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";
44
import {
45
threadRuntimeCanArchive,
46
type EnvironmentThreadShell,
@@ -1305,7 +1305,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
1305
const query = threadSearch.query;
1306
clearThreadSearch();
1307
navigateToThread(ref);
1308
- if (match) requestThreadFindQuery(scopedThreadKey(ref), findForMessageMatch(match, query));
1308
+ if (match) openThreadFindOnQuery(scopedThreadKey(ref), findForMessageMatch(match, query));
1309
};
1310
const handleThreadSearchKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
1311
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
apps/web/src/components/chat/MessagesTimeline.tsx
+1
-4
@@ -74,7 +74,6 @@ import {
74
} from "./MessagesTimeline.logic";
75
import { type ThreadFindMatch } from "./threadFind";
76
import { useThreadFindNavigation } from "./useThreadFindNavigation";
77
-import type { ThreadFindPositionReader } from "./threadFind";
77
import { TooltipScrollDismissArea } from "../ui/tooltip";
78
import { WorktreeSetupCard } from "./WorktreeSetupCard";
79
import { useOpenPrLink } from "~/lib/openPullRequestLink";
@@ -267,7 +266,6 @@ interface MessagesTimelineProps {
266
topFadeEnabled?: boolean;
267
historyControls?: MessagesTimelineHistoryControls | undefined;
268
loadEarlier?: CitationHistoryPage | null;
270
- findPositionReaderRef?: React.RefObject<ThreadFindPositionReader | null>;
269
findExpanded?: boolean;
270
findQuery?: string;
271
activeFindMatch?: ThreadFindMatch | null;
@@ -315,7 +313,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
313
findQuery = "",
314
activeFindMatch = null,
315
findNavigationId = 0,
318
- findPositionReaderRef,
316
latestRun,
317
announcedRun = null,
318
detailBehindShell = false,
@@ -1024,7 +1021,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1021
};
1022
1023
useThreadFindPositionReader({
1027
- findPositionReaderRef,
1024
+ threadKey: listIdentityKey,
1025
timelineViewportElement,
1026
findFoldRunIds,
1027
timelineEntries,
apps/web/src/components/chat/ThreadFindProvider.tsx
+3
-27
@@ -1,33 +1,20 @@
1
-import {
2
- createContext,
3
- use,
4
- useImperativeHandle,
5
- useLayoutEffect,
6
- type ReactNode,
7
- type ComponentProps,
8
- type Ref,
9
-} from "react";
1
+import { createContext, use, type ReactNode, type ComponentProps } from "react";
2
import { useThreadFind } from "./useThreadFind";
3
import { ThreadFindBar } from "./ThreadFindBar";
4
import { ChatCanvas } from "./ChatCanvas";
5
6
type Find = ReturnType<typeof useThreadFind>;
15
-export type ThreadFindControls = Pick<Find, "open" | "close">;
7
export const ThreadFindTimelineContext = createContext<Find["timelineProps"] | null>(null);
8
const ThreadFindBarContext = createContext<Find["barProps"] | null>(null);
9
10
export function ThreadFindCanvas({
11
findOptions,
21
- controlsRef,
22
- onOpenChange,
12
...canvasProps
13
}: ComponentProps<typeof ChatCanvas> & {
14
findOptions: Parameters<typeof useThreadFind>[0];
26
- controlsRef: Ref<ThreadFindControls>;
27
- onOpenChange: (open: boolean) => void;
15
}) {
16
return (
30
- <ThreadFindProvider {...findOptions} controlsRef={controlsRef} onOpenChange={onOpenChange}>
17
+ <ThreadFindProvider {...findOptions}>
18
<ChatCanvas {...canvasProps} />
19
</ThreadFindProvider>
20
);
@@ -35,21 +22,10 @@ export function ThreadFindCanvas({
22
23
/** Owns search updates below the chat view so cycling does not rerender the composer and panels. */
24
function ThreadFindProvider({
38
- controlsRef,
39
- onOpenChange,
25
children,
26
...options
42
-}: Parameters<typeof useThreadFind>[0] & {
43
- controlsRef: Ref<ThreadFindControls>;
44
- onOpenChange: (open: boolean) => void;
45
- children: ReactNode;
46
-}) {
27
+}: Parameters<typeof useThreadFind>[0] & { children: ReactNode }) {
28
const find = useThreadFind(options);
48
- useImperativeHandle(controlsRef, () => ({ open: find.open, close: find.close }), [
49
- find.open,
50
- find.close,
51
- ]);
52
- useLayoutEffect(() => onOpenChange(find.isOpen), [find.isOpen, onOpenChange]);
29
return (
30
<ThreadFindBarContext value={find.barProps}>
31
<ThreadFindTimelineContext value={find.timelineProps}>{children}</ThreadFindTimelineContext>
apps/web/src/components/chat/threadFindActionBus.test.ts
deleted
-22
@@ -1,22 +0,0 @@
1
-import { MessageId } from "@t3tools/contracts";
2
-import { describe, expect, it } from "vite-plus/test";
3
-
4
-import { findForMessageMatch } from "./threadFindActionBus";
5
-
6
-describe("findForMessageMatch", () => {
7
- it("opens find on the longest word as the snippet writes it, at the matched message", () => {
8
- expect(
9
- findForMessageMatch(
10
- { snippet: "The cafeteria, then the Café", messageId: MessageId.make("message-1") },
11
- "cafe",
12
- ),
13
- ).toEqual({ query: "Café", start: { entryId: "message-1", occurrence: 0 } });
14
- expect(findForMessageMatch({ snippet: "fix the sidebar lag" }, "fix sidebar")).toEqual({
15
- query: "sidebar",
16
- });
17
- // The whole query, when the snippet holds it as typed.
18
- expect(findForMessageMatch({ snippet: "then Vp run dev again" }, "vp run dev")).toEqual({
19
- query: "Vp run dev",
20
- });
21
- });
22
-});
apps/web/src/components/chat/threadFindActionBus.ts
deleted
-80
@@ -1,80 +0,0 @@
1
-import type { OrchestrationThreadSearchMatch } from "@t3tools/contracts";
2
-import {
3
- findSearchTokenRanges,
4
- messagePhrase,
5
- messageSearchTokens,
6
-} from "@t3tools/shared/paletteSearch";
7
-import type { ThreadFindStart } from "./threadFind";
8
-
9
-const THREAD_FIND_OPEN_EVENT = "t3:thread-find-open";
10
-
11
-export function requestThreadFindOpen(): void {
12
- window.dispatchEvent(new Event(THREAD_FIND_OPEN_EVENT));
13
-}
14
-
15
-export function subscribeThreadFindOpen(listener: () => void): () => void {
16
- window.addEventListener(THREAD_FIND_OPEN_EVENT, listener);
17
- return () => window.removeEventListener(THREAD_FIND_OPEN_EVENT, listener);
18
-}
19
-
20
-const THREAD_FIND_QUERY_EVENT = "t3:thread-find-query";
21
-interface PendingFind {
22
- readonly query: string;
23
- /** Where find starts, such as the message a palette result came from. */
24
- readonly start?: ThreadFindStart;
25
-}
26
-// A find a palette message result asked for, until that thread's view takes
27
-// it. One the view never took (the navigation failed) lets go after a while,
28
-// so a later visit does not open an old find.
29
-const PENDING_FIND_MS = 30_000;
30
-let pendingFind: (PendingFind & { readonly threadKey: string; readonly at: number }) | null = null;
31
-
32
-/** Opens find on `query` in the thread's view, now or once it mounts. */
33
-export function requestThreadFindQuery(threadKey: string, find: PendingFind): void {
34
- pendingFind = { threadKey, at: Date.now(), ...find };
35
- window.dispatchEvent(new Event(THREAD_FIND_QUERY_EVENT));
36
-}
37
-
38
-/** The find waiting for this thread's view; answers once. */
39
-export function takeThreadFindQuery(threadKey: string): PendingFind | null {
40
- if (pendingFind?.threadKey !== threadKey) return null;
41
- const { at, threadKey: _threadKey, ...find } = pendingFind;
42
- pendingFind = null;
43
- return Date.now() - at < PENDING_FIND_MS ? find : null;
44
-}
45
-
46
-/**
47
- * The find a message search result opens, at the matched message: the whole
48
- * query when the snippet holds it as typed ("vp run dev"), else its longest
49
- * word, as the most telling ("sidebar" in "fix sidebar"), written as the
50
- * snippet writes it ("Café" for "cafe", since find matches accents).
51
- */
52
-export function findForMessageMatch(
53
- match: Pick<OrchestrationThreadSearchMatch, "snippet" | "messageId">,
54
- query: string,
55
-): PendingFind {
56
- const start = match.messageId ? { start: { entryId: match.messageId, occurrence: 0 } } : {};
57
- // Apostrophes are straight in the query; straightening keeps offsets.
58
- const together = messagePhrase(query)?.exec(match.snippet.replace(/[\u2018\u2019]/g, "'"));
59
- if (together) {
60
- return {
61
- query: match.snippet.slice(together.index, together.index + together[0].length),
62
- ...start,
63
- };
64
- }
65
- const word =
66
- messageSearchTokens(query).long.reduce(
67
- (longest, token) => (token.length > longest.length ? token : longest),
68
- "",
69
- ) || query;
70
- const ranges = findSearchTokenRanges(match.snippet, word);
71
- // A whole word first, as search ranked it: "Café", not "Cafe" in "Cafeteria".
72
- const shown =
73
- ranges.find((range) => !/[\p{L}\p{N}]/u.test(match.snippet[range.end] ?? "")) ?? ranges[0];
74
- return { query: shown ? match.snippet.slice(shown.start, shown.end) : word, ...start };
75
-}
76
-
77
-export function subscribeThreadFindQuery(listener: () => void): () => void {
78
- window.addEventListener(THREAD_FIND_QUERY_EVENT, listener);
79
- return () => window.removeEventListener(THREAD_FIND_QUERY_EVENT, listener);
80
-}
apps/web/src/components/chat/threadFindHighlights.ts
+14
-10
@@ -1,5 +1,5 @@
1
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
2
-import { useEffect, useLayoutEffect, useRef } from "react";
2
+import { useEffect, useEffectEvent, useRef } from "react";
3
import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText";
4
5
const THREAD_FIND_HIGHLIGHT_NAME = "t3-thread-find";
@@ -119,14 +119,12 @@ export function useThreadFindHighlights(input: {
119
120
const rangesRef = useRef<readonly ThreadFindRange[]>([]);
121
const paintRef = useRef<ReturnType<typeof makeThreadFindHighlightPainter> | null>(null);
122
- const selectionRef = useRef({ activeRowId, activeOccurrence, onActiveRange });
123
- useLayoutEffect(() => {
124
- selectionRef.current = { activeRowId, activeOccurrence, onActiveRange };
125
- }, [activeRowId, activeOccurrence, onActiveRange]);
122
+ // The observer repaints with whichever match is selected when text changes.
123
+ const readSelection = useEffectEvent(() => ({ activeRowId, activeOccurrence, onActiveRange }));
124
125
useEffect(() => {
126
if (typeof CSS === "undefined" || !CSS.highlights || typeof Highlight === "undefined") {
129
- selectionRef.current.onActiveRange(null);
127
+ readSelection().onActiveRange(null);
128
return;
129
}
130
const clearHighlights = () => {
@@ -135,7 +133,7 @@ export function useThreadFindHighlights(input: {
133
};
134
rangesRef.current = [];
135
if (!container || query.length === 0) {
138
- selectionRef.current.onActiveRange(null);
136
+ readSelection().onActiveRange(null);
137
clearHighlights();
138
return;
139
}
@@ -161,7 +159,7 @@ export function useThreadFindHighlights(input: {
159
}
160
for (const row of cache.keys()) if (!rows.has(row)) cache.delete(row);
161
rangesRef.current = ranges;
164
- paint(ranges, selectionRef.current);
162
+ paint(ranges, readSelection());
163
};
164
let frame: number | null = null;
165
const observer = new MutationObserver((mutations) => {
@@ -208,9 +206,15 @@ export function useThreadFindHighlights(input: {
206
};
207
}, [container, query]);
208
209
+ // onActiveRange is read at paint time: its identity follows the caller's
210
+ // layout inputs, and repainting the active highlight for those is wasted work.
211
useEffect(() => {
212
- paintRef.current?.(rangesRef.current, { activeRowId, activeOccurrence, onActiveRange });
213
- }, [activeOccurrence, activeRowId, onActiveRange]);
212
+ paintRef.current?.(rangesRef.current, {
213
+ activeRowId,
214
+ activeOccurrence,
215
+ onActiveRange: readSelection().onActiveRange,
216
+ });
217
+ }, [activeOccurrence, activeRowId]);
218
}
219
220
function makeThreadFindHighlightPainter(container: HTMLElement) {
apps/web/src/components/chat/threadFindStore.test.ts
new
+94
@@ -0,0 +1,94 @@
1
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
+
5
+import {
6
+ attachThreadFindTimeline,
7
+ closeThreadFind,
8
+ findForMessageMatch,
9
+ openThreadFind,
10
+ openThreadFindOnQuery,
11
+ retainThreadFindForRoute,
12
+ setThreadFindQuery,
13
+ useThreadFindStore,
14
+} from "./threadFindStore";
15
+
16
+const threadRef = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-1"));
17
+const otherRef = scopeThreadRef(EnvironmentId.make("env-1"), ThreadId.make("thread-2"));
18
+const threadKey = "env-1:thread-1";
19
+
20
+function setup() {
21
+ closeThreadFind();
22
+ const readPosition = vi.fn(() => ({ entryId: "entry-9", occurrence: 1 }));
23
+ return { readPosition, timeline: { threadKey, readPosition } };
24
+}
25
+
26
+describe("thread find store", () => {
27
+ it("restarts an open query from the viewport of the timeline showing the thread", () => {
28
+ const { readPosition, timeline } = setup();
29
+ const detach = attachThreadFindTimeline(timeline);
30
+ openThreadFind(threadKey);
31
+ expect(useThreadFindStore.getState()).toMatchObject({ threadKey, focusRequestId: 1 });
32
+
33
+ setThreadFindQuery(threadKey, " needle ");
34
+ expect(readPosition).toHaveBeenLastCalledWith("needle");
35
+ // Opening again refocuses and restarts the search from where the viewport is.
36
+ openThreadFind(threadKey);
37
+ expect(useThreadFindStore.getState()).toMatchObject({
38
+ query: " needle ",
39
+ focusRequestId: 2,
40
+ start: { entryId: "entry-9", occurrence: 1 },
41
+ navigationId: 2,
42
+ requestId: 2,
43
+ });
44
+ detach();
45
+ });
46
+
47
+ it("opens a search result's find for a thread before its timeline shows it", () => {
48
+ const { readPosition, timeline } = setup();
49
+ const detach = attachThreadFindTimeline({ ...timeline, threadKey: "env-1:thread-2" });
50
+ openThreadFindOnQuery(threadKey, { query: "Café", start: { entryId: "m", occurrence: 0 } });
51
+ expect(useThreadFindStore.getState()).toMatchObject({
52
+ threadKey,
53
+ query: "Café",
54
+ start: { entryId: "m", occurrence: 0 },
55
+ });
56
+ // Another thread's timeline does not answer for this one.
57
+ setThreadFindQuery(threadKey, "Caf");
58
+ expect(readPosition).not.toHaveBeenCalled();
59
+ detach();
60
+ });
61
+
62
+ it("keeps find over Settings and Usage, and closes it on any other route", () => {
63
+ setup();
64
+ openThreadFindOnQuery(threadKey, { query: "x" });
65
+ retainThreadFindForRoute({ modalPage: false, threadRef });
66
+ retainThreadFindForRoute({ modalPage: true, threadRef: null });
67
+ expect(useThreadFindStore.getState()).toMatchObject({ threadKey, query: "x" });
68
+
69
+ retainThreadFindForRoute({ modalPage: false, threadRef: otherRef });
70
+ expect(useThreadFindStore.getState()).toMatchObject({ threadKey: null, query: "" });
71
+
72
+ openThreadFindOnQuery(threadKey, { query: "x" });
73
+ retainThreadFindForRoute({ modalPage: false, threadRef: null });
74
+ expect(useThreadFindStore.getState().threadKey).toBeNull();
75
+ });
76
+});
77
+
78
+describe("findForMessageMatch", () => {
79
+ it("opens find on the longest word as the snippet writes it, at the matched message", () => {
80
+ expect(
81
+ findForMessageMatch(
82
+ { snippet: "The cafeteria, then the Café", messageId: MessageId.make("message-1") },
83
+ "cafe",
84
+ ),
85
+ ).toEqual({ query: "Café", start: { entryId: "message-1", occurrence: 0 } });
86
+ expect(findForMessageMatch({ snippet: "fix the sidebar lag" }, "fix sidebar")).toEqual({
87
+ query: "sidebar",
88
+ });
89
+ // The whole query, when the snippet holds it as typed.
90
+ expect(findForMessageMatch({ snippet: "then Vp run dev again" }, "vp run dev")).toEqual({
91
+ query: "Vp run dev",
92
+ });
93
+ });
94
+});
apps/web/src/components/chat/threadFindStore.ts
new
+184
@@ -0,0 +1,184 @@
1
+import type {
2
+ OrchestrationThreadSearchMatch,
3
+ OrchestrationV2SearchThreadResult,
4
+ ScopedThreadRef,
5
+} from "@t3tools/contracts";
6
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
7
+import {
8
+ findSearchTokenRanges,
9
+ messagePhrase,
10
+ messageSearchTokens,
11
+} from "@t3tools/shared/paletteSearch";
12
+import { create } from "zustand";
13
+import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind";
14
+
15
+export interface ThreadFindLocalSelection {
16
+ readonly base: OrchestrationV2SearchThreadResult;
17
+ readonly baseNavigationId: number;
18
+ readonly activeIndex: number;
19
+ readonly match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;
20
+ readonly navigationId: number;
21
+}
22
+
23
+/** Find is open in at most one thread: the one the chat view shows. */
24
+export interface ThreadFindState {
25
+ readonly threadKey: string | null;
26
+ readonly query: string;
27
+ readonly offset: number;
28
+ readonly start: ThreadFindStart | undefined;
29
+ readonly focusRequestId: number;
30
+ readonly navigationId: number;
31
+ readonly requestId: number;
32
+ readonly localSelection: ThreadFindLocalSelection | null;
33
+}
34
+
35
+export const CLOSED_THREAD_FIND: ThreadFindState = {
36
+ threadKey: null,
37
+ query: "",
38
+ offset: 0,
39
+ start: undefined,
40
+ focusRequestId: 0,
41
+ navigationId: 0,
42
+ requestId: 0,
43
+ localSelection: null,
44
+};
45
+
46
+export const useThreadFindStore = create<ThreadFindState>(() => CLOSED_THREAD_FIND);
47
+
48
+/** What find needs from the timeline that shows a thread. */
49
+interface ThreadFindTimeline {
50
+ readonly threadKey: string;
51
+ readonly readPosition: ThreadFindPositionReader;
52
+}
53
+
54
+let attachedTimeline: ThreadFindTimeline | null = null;
55
+
56
+function timelineFor(threadKey: string): ThreadFindTimeline | null {
57
+ return attachedTimeline?.threadKey === threadKey ? attachedTimeline : null;
58
+}
59
+
60
+/** Attaches the timeline showing a thread; returns the detach. */
61
+export function attachThreadFindTimeline(timeline: ThreadFindTimeline): () => void {
62
+ attachedTimeline = timeline;
63
+ return () => {
64
+ if (attachedTimeline === timeline) attachedTimeline = null;
65
+ };
66
+}
67
+
68
+function readThreadFindPosition(threadKey: string, query: string): ThreadFindStart | undefined {
69
+ return timelineFor(threadKey)?.readPosition(query);
70
+}
71
+
72
+/** Opens find, or refocuses it and restarts its search from the viewport when already open. */
73
+export function openThreadFind(threadKey: string): void {
74
+ const previous = useThreadFindStore.getState();
75
+ const current = previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND;
76
+ const query = current.query.trim();
77
+ const start = query ? readThreadFindPosition(threadKey, query) : undefined;
78
+ useThreadFindStore.setState({
79
+ ...current,
80
+ threadKey,
81
+ focusRequestId: previous.focusRequestId + 1,
82
+ ...(query
83
+ ? {
84
+ start,
85
+ offset: 0,
86
+ localSelection: null,
87
+ navigationId: current.navigationId + 1,
88
+ requestId: current.navigationId + 1,
89
+ }
90
+ : {}),
91
+ });
92
+}
93
+
94
+export interface PendingThreadFind {
95
+ readonly query: string;
96
+ /** Where find starts, such as the message a palette result came from. */
97
+ readonly start?: ThreadFindStart;
98
+}
99
+
100
+/**
101
+ * Opens find on `query` in the thread, such as at the message a search result
102
+ * came from. The thread's view shows it once it is on screen.
103
+ */
104
+export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind): void {
105
+ const previous = useThreadFindStore.getState();
106
+ useThreadFindStore.setState({
107
+ ...(previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND),
108
+ threadKey,
109
+ query: find.query,
110
+ offset: 0,
111
+ start: find.start,
112
+ localSelection: null,
113
+ focusRequestId: previous.focusRequestId + 1,
114
+ navigationId: previous.navigationId + 1,
115
+ requestId: previous.navigationId + 1,
116
+ });
117
+}
118
+
119
+export function setThreadFindQuery(threadKey: string, query: string): void {
120
+ const start = readThreadFindPosition(threadKey, query.trim());
121
+ useThreadFindStore.setState((previous) => ({
122
+ query,
123
+ offset: 0,
124
+ start,
125
+ localSelection: null,
126
+ navigationId: previous.navigationId + 1,
127
+ requestId: previous.navigationId + 1,
128
+ }));
129
+}
130
+
131
+export function closeThreadFind(): void {
132
+ useThreadFindStore.setState(CLOSED_THREAD_FIND);
133
+}
134
+
135
+/**
136
+ * Find belongs to the thread it was opened in: a route showing anything else
137
+ * closes it. Settings and Usage draw over the thread, so they keep it.
138
+ */
139
+export function retainThreadFindForRoute(route: {
140
+ readonly modalPage: boolean;
141
+ readonly threadRef: ScopedThreadRef | null;
142
+}): void {
143
+ if (route.modalPage) return;
144
+ const { threadKey } = useThreadFindStore.getState();
145
+ const shownKey = route.threadRef ? scopedThreadKey(route.threadRef) : null;
146
+ if (threadKey !== null && threadKey !== shownKey) closeThreadFind();
147
+}
148
+
149
+/** Whether find is open in `thread`, as long as find is available there. */
150
+export function useThreadFindOpen(thread: ScopedThreadRef | null, enabled: boolean): boolean {
151
+ const openThreadKey = useThreadFindStore((state) => state.threadKey);
152
+ return enabled && thread !== null && openThreadKey === scopedThreadKey(thread);
153
+}
154
+
155
+/**
156
+ * The find a message search result opens, at the matched message: the whole
157
+ * query when the snippet holds it as typed ("vp run dev"), else its longest
158
+ * word, as the most telling ("sidebar" in "fix sidebar"), written as the
159
+ * snippet writes it ("Café" for "cafe", since find matches accents).
160
+ */
161
+export function findForMessageMatch(
162
+ match: Pick<OrchestrationThreadSearchMatch, "snippet" | "messageId">,
163
+ query: string,
164
+): PendingThreadFind {
165
+ const start = match.messageId ? { start: { entryId: match.messageId, occurrence: 0 } } : {};
166
+ // Apostrophes are straight in the query; straightening keeps offsets.
167
+ const together = messagePhrase(query)?.exec(match.snippet.replace(/[\u2018\u2019]/g, "'"));
168
+ if (together) {
169
+ return {
170
+ query: match.snippet.slice(together.index, together.index + together[0].length),
171
+ ...start,
172
+ };
173
+ }
174
+ const word =
175
+ messageSearchTokens(query).long.reduce(
176
+ (longest, token) => (token.length > longest.length ? token : longest),
177
+ "",
178
+ ) || query;
179
+ const ranges = findSearchTokenRanges(match.snippet, word);
180
+ // A whole word first, as search ranked it: "Café", not "Cafe" in "Cafeteria".
181
+ const shown =
182
+ ranges.find((range) => !/[\p{L}\p{N}]/u.test(match.snippet[range.end] ?? "")) ?? ranges[0];
183
+ return { query: shown ? match.snippet.slice(shown.start, shown.end) : word, ...start };
184
+}
apps/web/src/components/chat/useThreadFind.ts
+64
-159
@@ -1,43 +1,24 @@
1
import type { InlineSkill } from "@t3tools/shared/inlineSkills";
2
import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tools/contracts";
3
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4
-import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
5
-import { useStableCallback } from "~/hooks/useStableCallback";
4
+import { useEffect, useEffectEvent, useRef, useState } from "react";
5
import { orchestrationEnvironment } from "~/state/orchestration";
6
import { useThreadProjection } from "~/state/entities";
7
import { useEnvironmentQuery } from "~/state/query";
8
import { useDebouncedValue } from "~/state/queries";
9
+import { type ThreadFindMatch, type ThreadFindStart, stepThreadFindIndex } from "./threadFind";
10
import {
11
- type ThreadFindPositionReader,
12
- type ThreadFindStart,
13
- stepThreadFindIndex,
14
-} from "./threadFind";
15
-import {
16
- subscribeThreadFindOpen,
17
- subscribeThreadFindQuery,
18
- takeThreadFindQuery,
19
-} from "./threadFindActionBus";
20
-import { toastManager } from "../ui/toast";
11
+ CLOSED_THREAD_FIND,
12
+ closeThreadFind,
13
+ setThreadFindQuery,
14
+ useThreadFindOpen,
15
+ useThreadFindStore,
16
+ type ThreadFindLocalSelection,
17
+ type ThreadFindState,
18
+} from "./threadFindStore";
19
20
const EMPTY_SKILLS: readonly InlineSkill[] = [];
21
24
-const CLOSED_FIND = {
25
- threadKey: null as string | null,
26
- query: "",
27
- offset: 0,
28
- start: undefined as ThreadFindStart | undefined,
29
- focusRequestId: 0,
30
- navigationId: 0,
31
- requestId: 0,
32
- localSelection: null as {
33
- base: OrchestrationV2SearchThreadResult;
34
- baseNavigationId: number;
35
- activeIndex: number;
36
- match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;
37
- navigationId: number;
38
- } | null,
39
-};
40
-
22
export function useThreadFind({
23
thread,
24
enabled,
@@ -52,77 +33,17 @@ export function useThreadFind({
33
// Read here rather than passed in: a streamed delta re-renders only the find
34
// provider, which refreshes open results from it.
35
const content = useThreadProjection(enabled ? thread : null)?.projection;
55
- // Held in state so the timeline props that carry it can be stored in state too.
56
- const [positionReader] = useState<RefObject<ThreadFindPositionReader | null>>(() => ({
57
- current: null,
58
- }));
36
const lastContentRef = useRef(content);
37
const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
38
const refreshAfterSearchRef = useRef(false);
39
const threadKey = thread ? scopedThreadKey(thread) : null;
63
- const [state, setState] = useState(CLOSED_FIND);
64
- if (state.threadKey !== null && (!enabled || state.threadKey !== threadKey))
65
- setState(CLOSED_FIND);
66
- const isOpen = enabled && threadKey !== null && state.threadKey === threadKey;
67
- const open = useStableCallback(() => {
68
- if (threadKey === null) return;
69
- if (!enabled) {
70
- toastManager.add({
71
- id: "thread-find-unavailable",
72
- title: "Thread search is unavailable on this server.",
73
- description: "Update the server to enable it.",
74
- });
75
- return;
76
- }
77
- const start =
78
- state.threadKey === threadKey && state.query.trim()
79
- ? positionReader.current?.(state.query.trim())
80
- : undefined;
81
- setState((previous) => {
82
- const current = previous.threadKey === threadKey ? previous : CLOSED_FIND;
83
- return {
84
- ...current,
85
- threadKey,
86
- focusRequestId: previous.focusRequestId + 1,
87
- ...(current.query.trim()
88
- ? {
89
- start,
90
- offset: 0,
91
- localSelection: null,
92
- navigationId: current.navigationId + 1,
93
- requestId: current.navigationId + 1,
94
- }
95
- : {}),
96
- };
97
- });
98
- });
99
- const close = useStableCallback(() => setState(CLOSED_FIND));
100
- useEffect(() => subscribeThreadFindOpen(open), [open]);
101
- const openOnQuery = useStableCallback((query: string, start?: ThreadFindStart) => {
102
- if (threadKey === null) return;
103
- setState((previous) => ({
104
- ...(previous.threadKey === threadKey ? previous : CLOSED_FIND),
105
- threadKey,
106
- query,
107
- offset: 0,
108
- start,
109
- localSelection: null,
110
- focusRequestId: previous.focusRequestId + 1,
111
- navigationId: previous.navigationId + 1,
112
- requestId: previous.navigationId + 1,
113
- }));
114
- });
115
- // A palette message result opens find on its query, at its message, once
116
- // this thread shows.
117
- useEffect(() => {
118
- if (threadKey === null || !enabled) return;
119
- const take = () => {
120
- const find = takeThreadFindQuery(threadKey);
121
- if (find !== null) openOnQuery(find.query, find.start);
122
- };
123
- take();
124
- return subscribeThreadFindQuery(take);
125
- }, [enabled, openOnQuery, threadKey]);
40
+ const isOpen = useThreadFindOpen(thread, enabled);
41
+ const stored = useThreadFindStore();
42
+ const state = isOpen ? stored : CLOSED_THREAD_FIND;
43
+ const setState = (update: (previous: ThreadFindState) => Partial<ThreadFindState>) =>
44
+ useThreadFindStore.setState((previous) =>
45
+ previous.threadKey === threadKey ? update(previous) : previous,
46
+ );
47
48
const remote = useServerResults(
49
isOpen ? thread : null,
@@ -153,7 +74,7 @@ export function useThreadFind({
74
const navigationId = localSelection?.navigationId ?? remote.navigationId;
75
const findExpanded = isOpen && state.query.trim().length > 0;
76
const findQuery = isOpen && remote.data?.match ? state.query : "";
156
- const nextTimeline = {
77
+ const nextTimeline: TimelineFields = {
78
findOpen: isOpen,
79
findExpanded,
80
findQuery,
@@ -164,19 +85,13 @@ export function useThreadFind({
85
findNavigationId: navigationId,
86
};
87
// Keep timeline identity stable during count and response updates to avoid extra jumps.
167
- const [storedTimeline, setTimeline] = useState(() => ({
168
- fields: nextTimeline,
169
- props: { ...nextTimeline, findPositionReaderRef: positionReader },
170
- }));
88
+ const [storedTimeline, setTimeline] = useState(nextTimeline);
89
let timeline = storedTimeline;
172
- if (!sameTimeline(timeline.fields, nextTimeline)) {
173
- timeline = {
174
- fields: nextTimeline,
175
- props: { ...nextTimeline, findPositionReaderRef: positionReader },
176
- };
90
+ if (!sameTimeline(timeline, nextTimeline)) {
91
+ timeline = nextTimeline;
92
setTimeline(timeline);
93
}
179
- const match = timeline.fields.activeFindMatch;
94
+ const match = timeline.activeFindMatch;
95
const step = (delta: number) => {
96
if (count === 0 || counting) return;
97
setState((previous) => {
@@ -235,41 +150,40 @@ export function useThreadFind({
150
});
151
};
152
238
- const refreshLiveResultsRef = useRef(() => {});
239
- useLayoutEffect(() => {
240
- refreshLiveResultsRef.current = () => {
241
- if (!isOpen || !state.query.trim()) return;
242
- // Coalesce paging updates while the server counts to avoid restarting scans.
243
- if (progressive && remote.isPending) {
244
- refreshAfterSearchRef.current = true;
245
- return;
246
- }
247
- if (!match || state.navigationId !== navigationId) {
248
- remote.refresh();
249
- return;
250
- }
251
- const start = { entryId: match.entryId, occurrence: match.occurrence };
252
- if (
253
- state.offset === 0 &&
254
- state.start?.entryId === start.entryId &&
255
- state.start.occurrence === start.occurrence &&
256
- state.requestId === state.navigationId
257
- ) {
258
- remote.refresh();
259
- } else {
260
- setState((previous) => ({
261
- ...previous,
262
- start,
263
- offset: 0,
264
- requestId: previous.navigationId,
265
- }));
266
- }
267
- };
153
+ // Runs from the refresh timer and after a coalesced search settles, against
154
+ // the results and selection showing by then.
155
+ const refreshLiveResults = useEffectEvent(() => {
156
+ if (!isOpen || !state.query.trim()) return;
157
+ // Coalesce paging updates while the server counts to avoid restarting scans.
158
+ if (progressive && remote.isPending) {
159
+ refreshAfterSearchRef.current = true;
160
+ return;
161
+ }
162
+ if (!match || state.navigationId !== navigationId) {
163
+ remote.refresh();
164
+ return;
165
+ }
166
+ const start = { entryId: match.entryId, occurrence: match.occurrence };
167
+ if (
168
+ state.offset === 0 &&
169
+ state.start?.entryId === start.entryId &&
170
+ state.start.occurrence === start.occurrence &&
171
+ state.requestId === state.navigationId
172
+ ) {
173
+ remote.refresh();
174
+ } else {
175
+ setState((previous) => ({
176
+ ...previous,
177
+ start,
178
+ offset: 0,
179
+ requestId: previous.navigationId,
180
+ }));
181
+ }
182
});
183
useEffect(() => {
184
if (!refreshAfterSearchRef.current || remote.isPending) return;
185
refreshAfterSearchRef.current = false;
272
- if (!remote.error) refreshLiveResultsRef.current();
186
+ if (!remote.error) refreshLiveResults();
187
}, [remote.isPending, remote.error]);
188
useEffect(() => {
189
if (lastContentRef.current === content) return;
@@ -277,7 +191,7 @@ export function useThreadFind({
191
if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;
192
refreshTimerRef.current = setTimeout(() => {
193
refreshTimerRef.current = null;
280
- refreshLiveResultsRef.current();
194
+ refreshLiveResults();
195
}, 300);
196
}, [content, isOpen, state.query]);
197
useEffect(() => {
@@ -290,9 +204,6 @@ export function useThreadFind({
204
}, [threadKey, isOpen, state.query]);
205
206
return {
293
- isOpen,
294
- open,
295
- close,
207
barProps: {
208
open: isOpen,
209
query: state.query,
@@ -303,29 +214,23 @@ export function useThreadFind({
214
focusRequestId: state.focusRequestId,
215
onRetry: remote.refresh,
216
onQueryChange: (query: string) => {
306
- const start = positionReader.current?.(query.trim());
307
- setState((previous) => ({
308
- ...previous,
309
- query,
310
- offset: 0,
311
- start,
312
- localSelection: null,
313
- navigationId: previous.navigationId + 1,
314
- requestId: previous.navigationId + 1,
315
- }));
217
+ if (threadKey !== null) setThreadFindQuery(threadKey, query);
218
},
219
onNext: () => step(1),
220
onPrevious: () => step(-1),
319
- onClose: close,
221
+ onClose: closeThreadFind,
222
},
321
- timelineProps: timeline.props,
223
+ timelineProps: timeline,
224
};
225
}
226
325
-type TimelineFields = Omit<
326
- ReturnType<typeof useThreadFind>["timelineProps"],
327
- "findPositionReaderRef"
328
->;
227
+interface TimelineFields {
228
+ readonly findOpen: boolean;
229
+ readonly findExpanded: boolean;
230
+ readonly findQuery: string;
231
+ readonly activeFindMatch: ThreadFindMatch | null;
232
+ readonly findNavigationId: number;
233
+}
234
235
function sameTimeline(a: TimelineFields, b: TimelineFields) {
236
const aMatch = a.activeFindMatch;
@@ -344,7 +249,7 @@ function sameTimeline(a: TimelineFields, b: TimelineFields) {
249
}
250
251
function rebaseLocalSelection(
347
- selection: typeof CLOSED_FIND.localSelection,
252
+ selection: ThreadFindLocalSelection | null,
253
data: OrchestrationV2SearchThreadResult | null,
254
navigationId: number,
255
) {
apps/web/src/components/chat/useThreadFindNavigation.ts
+225
-160
@@ -1,10 +1,176 @@
1
import type { LegendListRef } from "@legendapp/list/react";
2
-import { useEffect, useLayoutEffect, useRef, type RefObject } from "react";
2
+import { useEffect, useEffectEvent, useRef, type RefObject } from "react";
3
import type { ThreadFindMatch } from "./threadFind";
4
import { useThreadFindHighlights } from "./threadFindHighlights";
5
6
const FIND_MATCH_VIEW_MARGIN = 96;
7
8
+type FindEntries = readonly { readonly id: string }[];
9
+
10
+interface RevealInputs {
11
+ readonly matchKey: string | null;
12
+ readonly rowIndex: number;
13
+ readonly entries: FindEntries;
14
+ readonly listReady: boolean;
15
+ readonly historyLoading: boolean;
16
+ readonly historyError: string | null;
17
+ readonly contentInsetEndAdjustment: number;
18
+ readonly container: HTMLElement | null;
19
+}
20
+
21
+/** Positioning bookkeeping that outlives a render: pending jumps and the pinned match during paging. */
22
+interface RevealState {
23
+ positioning: { key: string; rowIndex: number; entries: FindEntries } | null;
24
+ settledMatch: string | null;
25
+ activeRange: Range | null;
26
+ pagingPosition: { key: string; entries: FindEntries; top: number } | null;
27
+ revealedMatch: string | null;
28
+ positionedEntries: FindEntries | null;
29
+}
30
+
31
+/**
32
+ * Brings the active match into view. Async continuations re-enter with the
33
+ * inputs current by then, and stop once the match changes or the list unmounts.
34
+ */
35
+function revealThreadFindMatch(
36
+ range: Range | null,
37
+ inputs: RevealInputs,
38
+ context: {
39
+ readonly state: RevealState;
40
+ readonly listRef: RefObject<LegendListRef | null>;
41
+ readonly readInputs: () => RevealInputs;
42
+ },
43
+): void {
44
+ const { state, listRef, readInputs } = context;
45
+ const {
46
+ matchKey,
47
+ rowIndex,
48
+ entries,
49
+ listReady,
50
+ historyLoading,
51
+ historyError,
52
+ contentInsetEndAdjustment,
53
+ container,
54
+ } = inputs;
55
+ state.activeRange = range;
56
+ if (!matchKey) {
57
+ state.positioning = null;
58
+ state.settledMatch = null;
59
+ state.revealedMatch = null;
60
+ state.pagingPosition = null;
61
+ return;
62
+ }
63
+ const list = listRef.current;
64
+ const stillCurrent = () =>
65
+ list !== null && listRef.current === list && readInputs().matchKey === matchKey;
66
+ const revealAgain = () => revealThreadFindMatch(state.activeRange, readInputs(), context);
67
+ const pagingPosition = state.pagingPosition;
68
+ if (pagingPosition && pagingPosition.key !== matchKey) state.pagingPosition = null;
69
+ if (
70
+ range?.startContainer.isConnected &&
71
+ pagingPosition?.key === matchKey &&
72
+ pagingPosition.entries !== entries
73
+ ) {
74
+ const restore = () => {
75
+ const pinned = state.pagingPosition;
76
+ const currentRange = state.activeRange;
77
+ if (!stillCurrent() || !pinned || !currentRange?.startContainer.isConnected) return;
78
+ const delta = currentRange.getBoundingClientRect().top - pinned.top;
79
+ const scroll = listRef.current?.getState?.().scroll;
80
+ if (Math.abs(delta) >= 1 && typeof scroll === "number")
81
+ listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
82
+ };
83
+ pagingPosition.entries = entries;
84
+ restore();
85
+ // The list measures newly inserted activity after the first layout pass.
86
+ requestAnimationFrame(() =>
87
+ requestAnimationFrame(() => {
88
+ restore();
89
+ if (!readInputs().historyLoading && state.pagingPosition === pagingPosition)
90
+ state.pagingPosition = null;
91
+ }),
92
+ );
93
+ }
94
+ if (historyError) state.pagingPosition = null;
95
+ if (state.revealedMatch === matchKey) return;
96
+ if (!listReady || rowIndex < 0) return;
97
+ const materialize = () => {
98
+ const previous = state.positioning;
99
+ if (
100
+ !list ||
101
+ (previous?.key === matchKey && previous.rowIndex === rowIndex && previous.entries === entries)
102
+ )
103
+ return;
104
+ // Activity can insert rows during LegendList layout; retarget pending jumps.
105
+ const request = { key: matchKey, rowIndex, entries };
106
+ state.positioning = request;
107
+
108
+ void list
109
+ .scrollToIndex({
110
+ index: rowIndex,
111
+ animated: false,
112
+ viewOffset: FIND_MATCH_VIEW_MARGIN,
113
+ })
114
+ .then(() => {
115
+ if (state.positioning !== request || !stillCurrent()) return;
116
+
117
+ state.positionedEntries = entries;
118
+ state.settledMatch = matchKey;
119
+ revealAgain();
120
+ });
121
+ };
122
+ if (!range) {
123
+ if (container) materialize();
124
+ return;
125
+ }
126
+
127
+ const codeScroller = range.startContainer.parentElement?.closest("pre");
128
+ if (codeScroller) {
129
+ const rect = range.getBoundingClientRect();
130
+ const viewport = codeScroller.getBoundingClientRect();
131
+ if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;
132
+ else if (rect.right > viewport.right)
133
+ codeScroller.scrollLeft += rect.right - viewport.right + 16;
134
+ }
135
+ const rect = range.getBoundingClientRect();
136
+ const viewport = container?.getBoundingClientRect();
137
+ if (!viewport || rect.height === 0) return;
138
+ const margin = Math.min(
139
+ FIND_MATCH_VIEW_MARGIN,
140
+ Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),
141
+ );
142
+ const top = viewport.top + margin;
143
+ const bottom = viewport.bottom - margin - contentInsetEndAdjustment;
144
+ const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;
145
+ // DOM text can precede settled row sizes; wait before measuring offscreen matches.
146
+ if (
147
+ Math.abs(delta) >= 1 &&
148
+ state.positionedEntries !== entries &&
149
+ state.settledMatch !== matchKey
150
+ ) {
151
+ materialize();
152
+ return;
153
+ }
154
+ const scroll = list?.getState?.().scroll;
155
+ state.positionedEntries = entries;
156
+
157
+ state.revealedMatch = matchKey;
158
+ if (historyLoading) state.pagingPosition = { key: matchKey, entries, top: rect.top - delta };
159
+ if (Math.abs(delta) >= 1 && typeof scroll === "number") {
160
+ list?.scrollToOffset({ offset: scroll + delta, animated: false });
161
+ requestAnimationFrame(() => {
162
+ if (!stillCurrent()) return;
163
+ if (
164
+ listRef.current?.getState?.().scroll === scroll &&
165
+ range.getBoundingClientRect().top === rect.top
166
+ )
167
+ return;
168
+ state.revealedMatch = null;
169
+ revealAgain();
170
+ });
171
+ }
172
+}
173
+
174
export function useThreadFindNavigation({
175
container,
176
query,
@@ -22,7 +188,7 @@ export function useThreadFindNavigation({
188
match: ThreadFindMatch | null;
189
navigationId: number;
190
rowIndex: number;
25
- entries: readonly { readonly id: string }[];
191
+ entries: FindEntries;
192
listRef: RefObject<LegendListRef | null>;
193
contentInsetEndAdjustment: number;
194
listReady: boolean;
@@ -36,50 +202,50 @@ export function useThreadFindNavigation({
202
| undefined;
203
}) {
204
const matchKey = match ? `${navigationId}:${query}:${match.entryId}:${match.occurrence}` : null;
39
- const positioningRef = useRef<{
40
- key: string;
41
- rowIndex: number;
42
- entries: typeof entries;
43
- } | null>(null);
44
- const settledMatchRef = useRef<string | null>(null);
45
- const currentMatchKeyRef = useRef(matchKey);
46
- const activeRangeRef = useRef<Range | null>(null);
47
- const pagingPositionRef = useRef<{ key: string; entries: typeof entries; top: number } | null>(
48
- null,
49
- );
50
- const currentEntriesRef = useRef(entries);
51
- useLayoutEffect(() => {
52
- currentEntriesRef.current = entries;
53
- }, [entries]);
205
+ const historyLoading = historyControls?.loading ?? false;
206
+ const historyError = historyControls?.error ?? null;
207
+ const stateRef = useRef<RevealState>({
208
+ positioning: null,
209
+ settledMatch: null,
210
+ activeRange: null,
211
+ pagingPosition: null,
212
+ revealedMatch: null,
213
+ positionedEntries: null,
214
+ });
215
+ const readInputs = useEffectEvent((): RevealInputs => ({
216
+ matchKey,
217
+ rowIndex,
218
+ entries,
219
+ listReady,
220
+ historyLoading,
221
+ historyError,
222
+ contentInsetEndAdjustment,
223
+ container,
224
+ }));
225
+ // H/Z: stays an effect. The listener compares against the entries rendered at
226
+ // scroll time; the viewport ref callback in MessagesTimeline cannot read
227
+ // them without a latest-ref mirror, and capturing them would re-attach the
228
+ // viewport (observers, citation dismissal) on every streamed entry.
229
useEffect(() => {
230
if (!container) return;
231
const onScroll = () => {
57
- const position = pagingPositionRef.current;
58
- const range = activeRangeRef.current;
232
+ const state = stateRef.current;
233
+ const position = state.pagingPosition;
234
+ const range = state.activeRange;
235
if (
236
!position ||
61
- position.entries !== currentEntriesRef.current ||
237
+ position.entries !== readInputs().entries ||
238
!range?.startContainer.isConnected
239
)
240
return;
241
const rect = range.getBoundingClientRect();
242
const viewport = container.getBoundingClientRect();
67
- if (rect.bottom < viewport.top || rect.top > viewport.bottom)
68
- pagingPositionRef.current = null;
243
+ if (rect.bottom < viewport.top || rect.top > viewport.bottom) state.pagingPosition = null;
244
else position.top = rect.top;
245
};
246
container.addEventListener("scroll", onScroll, { passive: true });
247
return () => container.removeEventListener("scroll", onScroll);
248
}, [container]);
74
- const revealRef = useRef<(range: Range | null) => void>(() => {});
75
- useLayoutEffect(() => {
76
- currentMatchKeyRef.current = matchKey;
77
- return () => {
78
- currentMatchKeyRef.current = null;
79
- };
80
- }, [matchKey]);
81
- const revealedMatchRef = useRef<string | null>(null);
82
- const positionedEntriesRef = useRef<typeof entries | null>(null);
249
const requestedPagesRef = useRef<{ key: string | null; pages: Set<string> }>({
250
key: null,
251
pages: new Set(),
@@ -102,140 +268,39 @@ export function useThreadFindNavigation({
268
269
historyControls.onLoadEarlier(match.entryId);
270
}, [entries, historyControls, listReady, match, matchKey, rowIndex]);
105
- const reveal = (range: Range | null) => {
106
- activeRangeRef.current = range;
107
- if (!matchKey) {
108
- positioningRef.current = null;
109
- settledMatchRef.current = null;
110
- revealedMatchRef.current = null;
111
- pagingPositionRef.current = null;
112
- return;
113
- }
114
- const pagingPosition = pagingPositionRef.current;
115
- if (pagingPosition && pagingPosition.key !== matchKey) pagingPositionRef.current = null;
116
- if (
117
- range?.startContainer.isConnected &&
118
- pagingPosition?.key === matchKey &&
119
- pagingPosition.entries !== entries
120
- ) {
121
- const restore = () => {
122
- const pinned = pagingPositionRef.current;
123
- const currentRange = activeRangeRef.current;
124
- if (
125
- currentMatchKeyRef.current !== matchKey ||
126
- !pinned ||
127
- !currentRange?.startContainer.isConnected
128
- )
129
- return;
130
- const delta = currentRange.getBoundingClientRect().top - pinned.top;
131
- const scroll = listRef.current?.getState?.().scroll;
132
- if (Math.abs(delta) >= 1 && typeof scroll === "number")
133
- listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
134
- };
135
- pagingPosition.entries = entries;
136
- restore();
137
- // The list measures newly inserted activity after the first layout pass.
138
- requestAnimationFrame(() =>
139
- requestAnimationFrame(() => {
140
- restore();
141
- if (!historyControls?.loading && pagingPositionRef.current === pagingPosition)
142
- pagingPositionRef.current = null;
143
- }),
144
- );
145
- }
146
- if (historyControls?.error) pagingPositionRef.current = null;
147
- if (revealedMatchRef.current === matchKey) return;
148
- if (!listReady || rowIndex < 0) return;
149
- const materialize = () => {
150
- const list = listRef.current;
151
- const previous = positioningRef.current;
152
- if (
153
- !list ||
154
- (previous?.key === matchKey &&
155
- previous.rowIndex === rowIndex &&
156
- previous.entries === entries)
157
- )
158
- return;
159
- // Activity can insert rows during LegendList layout; retarget pending jumps.
160
- const request = { key: matchKey, rowIndex, entries };
161
- positioningRef.current = request;
162
-
163
- void list
164
- .scrollToIndex({
165
- index: rowIndex,
166
- animated: false,
167
- viewOffset: FIND_MATCH_VIEW_MARGIN,
168
- })
169
- .then(() => {
170
- if (positioningRef.current !== request || currentMatchKeyRef.current !== matchKey) return;
171
-
172
- positionedEntriesRef.current = entries;
173
- settledMatchRef.current = matchKey;
174
- revealRef.current(activeRangeRef.current);
175
- });
176
- };
177
- if (!range) {
178
- if (container) materialize();
179
- return;
180
- }
181
-
182
- const codeScroller = range.startContainer.parentElement?.closest("pre");
183
- if (codeScroller) {
184
- const rect = range.getBoundingClientRect();
185
- const viewport = codeScroller.getBoundingClientRect();
186
- if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;
187
- else if (rect.right > viewport.right)
188
- codeScroller.scrollLeft += rect.right - viewport.right + 16;
189
- }
190
- const rect = range.getBoundingClientRect();
191
- const viewport = container?.getBoundingClientRect();
192
- if (!viewport || rect.height === 0) return;
193
- const margin = Math.min(
194
- FIND_MATCH_VIEW_MARGIN,
195
- Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),
196
- );
197
- const top = viewport.top + margin;
198
- const bottom = viewport.bottom - margin - contentInsetEndAdjustment;
199
- const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;
200
- // DOM text can precede settled row sizes; wait before measuring offscreen matches.
201
- if (
202
- Math.abs(delta) >= 1 &&
203
- positionedEntriesRef.current !== entries &&
204
- settledMatchRef.current !== matchKey
205
- ) {
206
- materialize();
207
- return;
208
- }
209
- const scroll = listRef.current?.getState?.().scroll;
210
- positionedEntriesRef.current = entries;
211
-
212
- revealedMatchRef.current = matchKey;
213
- if (historyControls?.loading)
214
- pagingPositionRef.current = { key: matchKey, entries, top: rect.top - delta };
215
- if (Math.abs(delta) >= 1 && typeof scroll === "number") {
216
- listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
217
- requestAnimationFrame(() => {
218
- if (currentMatchKeyRef.current !== matchKey) return;
219
- if (
220
- listRef.current?.getState?.().scroll === scroll &&
221
- range.getBoundingClientRect().top === rect.top
222
- )
223
- return;
224
- revealedMatchRef.current = null;
225
- revealRef.current(activeRangeRef.current);
226
- });
227
- }
228
- };
229
-
230
- useLayoutEffect(() => {
231
- revealRef.current = reveal;
232
- }, [reveal]);
271
+ const reveal = useEffectEvent((range: Range | null, inputs: RevealInputs) =>
272
+ revealThreadFindMatch(range, inputs, { state: stateRef.current, listRef, readInputs }),
273
+ );
274
275
useThreadFindHighlights({
276
container,
277
query,
278
activeRowId: match?.entryId ?? null,
279
activeOccurrence: match?.occurrence ?? 0,
239
- onActiveRange: reveal,
280
+ onActiveRange: (range) => reveal(range, readInputs()),
281
});
282
+ // Positioning also depends on the list: a loaded page or a shifted row must
283
+ // retry the jump for the same selection. Declared after the highlight
284
+ // effects so it reuses the range they just resolved.
285
+ useEffect(() => {
286
+ reveal(stateRef.current.activeRange, {
287
+ matchKey,
288
+ rowIndex,
289
+ entries,
290
+ listReady,
291
+ historyLoading,
292
+ historyError,
293
+ contentInsetEndAdjustment,
294
+ container,
295
+ });
296
+ }, [
297
+ container,
298
+ matchKey,
299
+ rowIndex,
300
+ entries,
301
+ listReady,
302
+ historyLoading,
303
+ historyError,
304
+ contentInsetEndAdjustment,
305
+ ]);
306
}
apps/web/src/components/chat/useThreadFindPositionReader.ts
+8
-9
@@ -7,11 +7,12 @@ import {
7
type TimelineLatestRun,
8
} from "./MessagesTimeline.logic";
9
import type { ThreadFindPositionReader } from "./threadFind";
10
+import { attachThreadFindTimeline } from "./threadFindStore";
11
import { readThreadFindPosition } from "./threadFindPosition";
12
12
-/** Publishes how to read the find position of the timeline's current viewport. */
13
+/** Hands thread find how to read the find position of this timeline's viewport. */
14
export function useThreadFindPositionReader({
14
- findPositionReaderRef,
15
+ threadKey,
16
timelineViewportElement,
17
findFoldRunIds,
18
timelineEntries,
@@ -22,7 +23,7 @@ export function useThreadFindPositionReader({
23
rows,
24
contentInsetEndAdjustment,
25
}: {
25
- readonly findPositionReaderRef: React.RefObject<ThreadFindPositionReader | null> | undefined;
26
+ readonly threadKey: string;
27
readonly timelineViewportElement: HTMLDivElement | null;
28
readonly findFoldRunIds: ReadonlyMap<string, RunId> | null;
29
readonly timelineEntries: ReadonlyArray<TimelineEntry>;
@@ -33,8 +34,9 @@ export function useThreadFindPositionReader({
34
readonly rows: MessagesTimelineRow[];
35
readonly contentInsetEndAdjustment: number;
36
}) {
37
+ // Layout effect so a find opened right after a thread switch reads this viewport.
38
useLayoutEffect(() => {
37
- if (!findPositionReaderRef || !timelineViewportElement) return;
39
+ if (!timelineViewportElement) return;
40
const read: ThreadFindPositionReader = (query) => {
41
const foldRunIds =
42
findFoldRunIds ??
@@ -81,15 +83,12 @@ export function useThreadFindPositionReader({
83
contentInsetEndAdjustment,
84
);
85
};
84
- findPositionReaderRef.current = read;
85
- return () => {
86
- if (findPositionReaderRef.current === read) findPositionReaderRef.current = null;
87
- };
86
+ return attachThreadFindTimeline({ threadKey, readPosition: read });
87
}, [
88
contentInsetEndAdjustment,
89
findFoldRunIds,
91
- findPositionReaderRef,
90
isWorking,
91
+ threadKey,
92
latestRun,
93
rows,
94
runlessWorkActive,
apps/web/src/routes/_chat.tsx
+19
-2
@@ -8,7 +8,8 @@ import { isCommandPaletteOpen } from "../commandPaletteBus";
8
import { ThreadRouteView } from "../components/ThreadRouteView";
9
import { isAppModalPage } from "../components/sidebar/mainAppLocation";
10
import { SidebarInset } from "../components/ui/sidebar";
11
-import type { ThreadRouteTarget } from "../threadRoutes";
11
+import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../threadRoutes";
12
+import { retainThreadFindForRoute } from "../components/chat/threadFindStore";
13
import { ThreadLinkPrompt } from "../components/promptLinks/ThreadLinkPrompt";
14
import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";
15
import { openCommandPalette } from "../commandPaletteBus";
@@ -234,13 +235,29 @@ function ChatRouteLayout() {
235
}
236
237
export const Route = createFileRoute("/_chat")({
237
- beforeLoad: async ({ context }) => {
238
+ beforeLoad: async ({ context, location }) => {
239
if (
240
context.authGateState.status !== "authenticated" &&
241
context.authGateState.status !== "hosted-static"
242
) {
243
throw redirect({ to: "/pair", replace: true });
244
}
245
+ return { appModalPage: isAppModalPage(location.pathname) };
246
},
247
component: ChatRouteLayout,
248
+ // Every match carries the whole location's params, so this layout sees the thread route's too.
249
+ onEnter: ({ context, params }) => retainThreadFindForRouteMatch(context.appModalPage, params),
250
+ onStay: ({ context, params }) => retainThreadFindForRouteMatch(context.appModalPage, params),
251
+ onLeave: () => retainThreadFindForRoute({ modalPage: false, threadRef: null }),
252
});
253
+
254
+function retainThreadFindForRouteMatch(
255
+ modalPage: boolean,
256
+ params: Partial<Record<"environmentId" | "threadId", string>>,
257
+) {
258
+ const target = resolveThreadRouteTarget(params);
259
+ retainThreadFindForRoute({
260
+ modalPage,
261
+ threadRef: target?.kind === "server" ? target.threadRef : null,
262
+ });
263
+}