🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): Stale search highlights (#13237)
Ben Bachemc3438490e717
diff --git a/web/src/components/ChatMessages/messageSearch/context.tsx b/web/src/components/ChatMessages/messageSearch/context.tsxindex cb5deefdfc..0312554f6a 100644--- a/web/src/components/ChatMessages/messageSearch/context.tsx+++ b/web/src/components/ChatMessages/messageSearch/context.tsx@@ -160,9 +160,15 @@ export function useSyncMessageSearchMessages(}actions.registerPageMessages(pageId, messages);+ }, [actions, messages, pageId]);++ useEffect(() => {+ if (!actions) {+ return;+ }return () => {actions.unregisterPageMessages(pageId);};- }, [actions, messages, pageId]);+ }, [actions, pageId]);}diff --git a/web/src/components/ChatMessages/messageSearch/controller.clienttest.ts b/web/src/components/ChatMessages/messageSearch/controller.clienttest.tsindex fe044b4eb2..6b812eb979 100644--- a/web/src/components/ChatMessages/messageSearch/controller.clienttest.ts+++ b/web/src/components/ChatMessages/messageSearch/controller.clienttest.ts@@ -1,7 +1,17 @@import { ChatMessageRole, ChatMessageType } from "@langfuse/shared";+import {+ applyCodeMirrorSearchQuery,+ setActiveSearchMarkCodeMirrorRange,+} from "../../editor";import { createMessageSearchController } from "./controller";+jest.mock("../../editor", () => ({+ applyCodeMirrorSearchQuery: jest.fn(),+ setActiveSearchMarkCodeMirrorRange: jest.fn(),+ unsetActiveSearchMarkCodeMirrorRange: jest.fn(),+}));+describe("message search controller", () => {beforeEach(() => {jest.useFakeTimers();@@ -179,4 +189,138 @@ describe("message search controller", () => {expect(controller.getSnapshot().query).toBe("");expect(controller.getSnapshot().matches).toEqual([]);});++ it("reapplies editor search decorations when message content changes during an active search", () => {+ const controller = createMessageSearchController(["page-1"]);+ const editorRef = { current: null };+ const initialMessages = [+ {+ id: "message-1",+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "foo bar",+ },+ ] as const;++ controller.registerPageMessages("page-1", [...initialMessages]);+ controller.registerMessageTarget("page-1", "message-1", {+ rowRef: { current: null },+ editorRef,+ });++ expect(commitQuery(controller, "foo")).toHaveLength(1);+ const activeMatchBefore = controller.getSnapshot().activeMatch;++ jest.mocked(applyCodeMirrorSearchQuery).mockClear();+ jest.mocked(setActiveSearchMarkCodeMirrorRange).mockClear();++ controller.registerPageMessages("page-1", [+ {+ ...initialMessages[0],+ content: "foo foo bar",+ },+ ]);++ expect(controller.getSnapshot().matches).toHaveLength(2);+ expect(controller.getSnapshot().activeMatch?.key).toBe(+ activeMatchBefore?.key,+ );+ expect(applyCodeMirrorSearchQuery).toHaveBeenCalledTimes(1);+ expect(applyCodeMirrorSearchQuery).toHaveBeenCalledWith(editorRef, "foo", [+ { from: 0, to: 3 },+ { from: 4, to: 7 },+ ]);+ expect(setActiveSearchMarkCodeMirrorRange).toHaveBeenCalledTimes(1);+ expect(setActiveSearchMarkCodeMirrorRange).toHaveBeenCalledWith(+ editorRef,+ {+ from: 0,+ to: 3,+ },+ { scrollIntoView: false },+ );+ });++ it("does not scroll the active match during streaming updates", () => {+ const controller = createMessageSearchController(["page-1"]);+ const editorRef = { current: null };+ const pageScrollIntoView = jest.fn();+ const rowScrollIntoView = jest.fn();++ controller.registerPageTarget("page-1", {+ pageRef: {+ current: {+ scrollIntoView: pageScrollIntoView,+ } as unknown as HTMLDivElement,+ },+ });+ controller.registerPageMessages("page-1", [+ {+ id: "message-1",+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "foo",+ },+ ]);+ controller.registerMessageTarget("page-1", "message-1", {+ rowRef: {+ current: {+ scrollIntoView: rowScrollIntoView,+ } as unknown as HTMLDivElement,+ },+ editorRef,+ });++ commitQuery(controller, "foo");++ expect(pageScrollIntoView).toHaveBeenCalledTimes(1);+ expect(rowScrollIntoView).toHaveBeenCalledTimes(1);+ expect(setActiveSearchMarkCodeMirrorRange).toHaveBeenLastCalledWith(+ editorRef,+ { from: 0, to: 3 },+ { scrollIntoView: true },+ );++ pageScrollIntoView.mockClear();+ rowScrollIntoView.mockClear();+ jest.mocked(applyCodeMirrorSearchQuery).mockClear();+ jest.mocked(setActiveSearchMarkCodeMirrorRange).mockClear();++ controller.registerPageMessages("page-1", [+ {+ id: "message-1",+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "foo bar",+ },+ ]);+ controller.registerPageMessages("page-1", [+ {+ id: "message-1",+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "foo bar baz",+ },+ ]);++ expect(controller.getSnapshot().activeMatch?.key).toBe(+ "page-1:message-1:0:3",+ );+ expect(pageScrollIntoView).not.toHaveBeenCalled();+ expect(rowScrollIntoView).not.toHaveBeenCalled();+ expect(applyCodeMirrorSearchQuery).toHaveBeenCalledTimes(2);+ expect(setActiveSearchMarkCodeMirrorRange).toHaveBeenCalledTimes(2);+ expect(setActiveSearchMarkCodeMirrorRange).toHaveBeenNthCalledWith(+ 1,+ editorRef,+ { from: 0, to: 3 },+ { scrollIntoView: false },+ );+ expect(setActiveSearchMarkCodeMirrorRange).toHaveBeenNthCalledWith(+ 2,+ editorRef,+ { from: 0, to: 3 },+ { scrollIntoView: false },+ );+ });});diff --git a/web/src/components/ChatMessages/messageSearch/controller.ts b/web/src/components/ChatMessages/messageSearch/controller.tsindex 8608f8dc85..b30f8c6fff 100644--- a/web/src/components/ChatMessages/messageSearch/controller.ts+++ b/web/src/components/ChatMessages/messageSearch/controller.ts@@ -60,6 +60,20 @@ type MessageSearchMessageTarget = {editorRef: RefObject<ReactCodeMirrorRef | null>;};+type RefreshSearchOptions = {+ syncEditors?: boolean;+ scrollToActiveMatch?: boolean;+};++type SearchMatchRange = {+ from: number;+ to: number;+};++type SyncActiveMatchTargetOptions = {+ scrollIntoView?: boolean;+};+export type MessageSearchController = {subscribe: (listener: () => void) => () => void;getSnapshot: () => MessageSearchSnapshot;@@ -257,25 +271,54 @@ export function createMessageSearchController(pendingQueryTimeout = null;};+ const getMatchRangesForMessageTarget = (pageId: string, messageId: string) =>+ state.matches+ .filter(+ (match) => match.pageId === pageId && match.messageId === messageId,+ )+ .map((match) => ({ from: match.from, to: match.to }));+const syncEditorsToQuery = () => {const query = getCommittedQuery(state);+ const matchRangesByTargetKey = new Map<string, SearchMatchRange[]>();++ for (const match of state.matches) {+ const targetKey = getMessageTargetKey(match.pageId, match.messageId);+ const ranges = matchRangesByTargetKey.get(targetKey);- for (const target of messageTargets.values()) {- applyCodeMirrorSearchQuery(target.editorRef, query);+ if (ranges) {+ ranges.push({ from: match.from, to: match.to });+ } else {+ matchRangesByTargetKey.set(targetKey, [+ { from: match.from, to: match.to },+ ]);+ }+ }++ for (const [targetKey, target] of messageTargets.entries()) {+ applyCodeMirrorSearchQuery(+ target.editorRef,+ query,+ matchRangesByTargetKey.get(targetKey) ?? [],+ );}};- const syncActiveMatchTarget = () => {+ const syncActiveMatchTarget = ({+ scrollIntoView = true,+ }: SyncActiveMatchTargetOptions = {}) => {const activeMatch = getActiveMatch(state);if (!activeMatch) {return;}- pageTargets.get(activeMatch.pageId)?.pageRef.current?.scrollIntoView({- behavior: "smooth",- block: "nearest",- inline: "center",- });+ if (scrollIntoView) {+ pageTargets.get(activeMatch.pageId)?.pageRef.current?.scrollIntoView({+ behavior: "smooth",+ block: "nearest",+ inline: "center",+ });+ }let activeMessageTarget: MessageSearchMessageTarget | null = null;const inactiveMessageTargets: MessageSearchMessageTarget[] = [];@@ -297,16 +340,22 @@ export function createMessageSearchController(unsetActiveSearchMarkCodeMirrorRange(target?.editorRef);}- activeMessageTarget?.rowRef.current?.scrollIntoView({- behavior: "smooth",- block: "center",- inline: "nearest",- });+ if (scrollIntoView) {+ activeMessageTarget?.rowRef.current?.scrollIntoView({+ behavior: "smooth",+ block: "center",+ inline: "nearest",+ });+ }- setActiveSearchMarkCodeMirrorRange(activeMessageTarget?.editorRef, {- from: activeMatch.from,- to: activeMatch.to,- });+ setActiveSearchMarkCodeMirrorRange(+ activeMessageTarget?.editorRef,+ {+ from: activeMatch.from,+ to: activeMatch.to,+ },+ { scrollIntoView },+ );};const recomputeMatches = () => {@@ -339,24 +388,31 @@ export function createMessageSearchController(return previousActiveMatchKey !== state.activeMatchKey;};- const refreshSearchResults = (shouldSyncEditors: boolean) => {+ const refreshSearchResults = ({+ syncEditors = false,+ scrollToActiveMatch = false,+ }: RefreshSearchOptions) => {const activeMatchChanged = recomputeMatches();+ const shouldSyncEditors = syncEditors || activeMatchChanged;+ const shouldScrollToActiveMatch = scrollToActiveMatch || activeMatchChanged;- if (shouldSyncEditors || activeMatchChanged) {+ if (shouldSyncEditors) {syncEditorsToQuery();}- if (shouldSyncEditors || activeMatchChanged) {- syncActiveMatchTarget();+ // Redrawing the editor search marks clears the selected active-match mark,+ // so the active match must always be re-applied after syncing editors.+ if (shouldSyncEditors || shouldScrollToActiveMatch) {+ syncActiveMatchTarget({ scrollIntoView: shouldScrollToActiveMatch });}};- const refreshSearchResultsIfSearching = (shouldSyncEditors: boolean) => {+ const refreshSearchResultsIfSearching = (options: RefreshSearchOptions) => {if (!getCommittedQuery(state)) {return;}- refreshSearchResults(shouldSyncEditors);+ refreshSearchResults(options);emit();};@@ -366,7 +422,7 @@ export function createMessageSearchController(}state.searchQuery = nextSearchQuery;- refreshSearchResults(true);+ refreshSearchResults({ syncEditors: true, scrollToActiveMatch: true });return true;};@@ -520,7 +576,9 @@ export function createMessageSearchController(}state.pageIds = pageIds;- refreshSearchResultsIfSearching(false);+ refreshSearchResultsIfSearching({+ syncEditors: true,+ });},setPageLabelResolver(getPageLabel) {@@ -529,12 +587,14 @@ export function createMessageSearchController(}state.getPageLabel = getPageLabel;- refreshSearchResultsIfSearching(false);+ refreshSearchResultsIfSearching({});},registerPageMessages(pageId, messages) {state.pageMessagesById[pageId] = messages;- refreshSearchResultsIfSearching(false);+ refreshSearchResultsIfSearching({+ syncEditors: true,+ });},unregisterPageMessages(pageId) {@@ -543,7 +603,9 @@ export function createMessageSearchController(}delete state.pageMessagesById[pageId];- refreshSearchResultsIfSearching(false);+ refreshSearchResultsIfSearching({+ syncEditors: true,+ });},registerPageTarget(pageId, target) {@@ -559,9 +621,14 @@ export function createMessageSearchController(},registerMessageTarget(pageId, messageId, target) {- messageTargets.set(getMessageTargetKey(pageId, messageId), target);+ const targetKey = getMessageTargetKey(pageId, messageId);+ messageTargets.set(targetKey, target);- applyCodeMirrorSearchQuery(target.editorRef, getCommittedQuery(state));+ applyCodeMirrorSearchQuery(+ target.editorRef,+ getCommittedQuery(state),+ getMatchRangesForMessageTarget(pageId, messageId),+ );const activeMatch = getActiveMatch(state);if (diff --git a/web/src/components/editor/CodeMirrorEditor.tsx b/web/src/components/editor/CodeMirrorEditor.tsxindex 44b11e6479..43137c42f7 100644--- a/web/src/components/editor/CodeMirrorEditor.tsx+++ b/web/src/components/editor/CodeMirrorEditor.tsx@@ -309,6 +309,7 @@ const searchHighlightingSupport = StateField.define<DecorationSet>({export function applyCodeMirrorSearchQuery(editorRef: RefObject<ReactCodeMirrorRef | null> | undefined,searchValue: string,+ matchRanges: { from: number; to: number }[],) {const view = editorRef?.current?.view;if (!view) {@@ -325,14 +326,6 @@ export function applyCodeMirrorSearchQuery(effects: setSearchQuery.of(searchQuery),});- const cursor = searchQuery.getCursor(view.state);- const matchRanges: { from: number; to: number }[] = [];- let current = cursor.next();- while (!current.done) {- matchRanges.push(current.value);- current = cursor.next();- }-view.dispatch({effects: setSearchHighlightMarks.of(matchRanges),});@@ -341,17 +334,23 @@ export function applyCodeMirrorSearchQuery(export function setActiveSearchMarkCodeMirrorRange(editorRef: RefObject<ReactCodeMirrorRef | null> | undefined,range: { from: number; to: number } | null,+ { scrollIntoView = true }: { scrollIntoView?: boolean } = {},) {const view = editorRef?.current?.view;if (!view || !range) {return;}+ const effects: StateEffect<unknown>[] = [+ setSelectedSearchHighlightMark.of(range),+ ];++ if (scrollIntoView) {+ effects.push(EditorView.scrollIntoView(range.from));+ }+view.dispatch({- effects: [- setSelectedSearchHighlightMark.of(range),- EditorView.scrollIntoView(range.from),- ],+ effects,});}