πͺ’ 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): stop IME composition from duplicating tracing search text (#17706)
Nikita Kabardinef335af35186
diff --git a/web/src/features/search-bar/components/ComposerTokens.clienttest.tsx b/web/src/features/search-bar/components/ComposerTokens.clienttest.tsxindex 919951e696..f1b4e18223 100644--- a/web/src/features/search-bar/components/ComposerTokens.clienttest.tsx+++ b/web/src/features/search-bar/components/ComposerTokens.clienttest.tsx@@ -26,4 +26,16 @@ describe("ComposerTokens", () => {'scores."Rouge Score":>=1',);});++ it("renders whitespace and trailing plain text as elements, not raw text nodes", () => {+ // IME composition writes into whatever text node the caret sits in. A+ // fragment-emitted " " between pills is a node React will not rewrite, so+ // the composed run stays in the DOM next to the token projection.+ const { container } = render(+ <ComposerTokens draft="level:ERROR hello" showDiagnostics={false} />,+ );+ for (const child of Array.from(container.childNodes)) {+ expect(child.nodeType).toBe(Node.ELEMENT_NODE);+ }+ });});diff --git a/web/src/features/search-bar/components/ComposerTokens.tsx b/web/src/features/search-bar/components/ComposerTokens.tsxindex b8a1b044fb..120f3e1242 100644--- a/web/src/features/search-bar/components/ComposerTokens.tsx+++ b/web/src/features/search-bar/components/ComposerTokens.tsx@@ -63,11 +63,14 @@ const composerTokenVariants = cva("max-w-full", {type TokenKind = "filter" | "freeText" | "operator" | "paren" | "invalid";function renderPlainText(text: string, keyPrefix: string): React.ReactNode[] {+ // Element wrappers, not fragments: an IME writes into whatever text node+ // the caret sits in, and React will not rewrite a fragment-emitted node+ // whose last rendered value is still `" "`. A span is a node React owns,+ // so compositionend can remount it instead of leaving a stuck sibling.return text.split(/(\s+)/)- .map((part, index) => (- <React.Fragment key={`${keyPrefix}:${index}`}>{part}</React.Fragment>- ));+ .filter((part) => part.length > 0)+ .map((part, index) => <span key={`${keyPrefix}:${index}`}>{part}</span>);}function FilterTokenBody({ segment }: { segment: FilterSegment }) {diff --git a/web/src/features/search-bar/components/SearchComposer.clienttest.tsx b/web/src/features/search-bar/components/SearchComposer.clienttest.tsxnew file mode 100644index 0000000000..671f82d227--- /dev/null+++ b/web/src/features/search-bar/components/SearchComposer.clienttest.tsx@@ -0,0 +1,116 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";+import { WORD_JOINER } from "@/src/features/search-bar/components/ComposerTokens";+import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";+import { createSearchBarStore } from "@/src/features/search-bar/store/searchBarStore";++const WORD_JOINER_RE = new RegExp(WORD_JOINER, "g");++function renderComposer(draft = "") {+ const store = createSearchBarStore();+ if (draft.length > 0) store.getState().actions.setDraft(draft);+ const view = render(+ <SearchBarStoreProvider store={store} commit={vi.fn()}>+ <SearchComposer observed={undefined} />+ </SearchBarStoreProvider>,+ );+ return { store, ...view };+}++function composerRoot(): HTMLElement {+ return screen.getByTestId("search-bar-input");+}++function visibleComposerText(root: HTMLElement = composerRoot()): string {+ return (root.textContent ?? "").replace(WORD_JOINER_RE, "");+}++function hasDirectTextNode(root: HTMLElement): boolean {+ return Array.from(root.childNodes).some(+ (node) =>+ node.nodeType === Node.TEXT_NODE && (node.textContent ?? "") !== "",+ );+}++function lastSpaceTextNode(root: HTMLElement): Text | null {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let spaceNode: Text | null = null;+ let node = walker.nextNode();+ while (node !== null) {+ if ((node.textContent ?? "").includes(" ")) {+ spaceNode = node as Text;+ }+ node = walker.nextNode();+ }+ return spaceNode;+}++/**+ * Simulate an IME commit without a real IME: the browser writes a text node+ * React does not own, then fires compositionend. Korean/Chinese IMEs do this+ * in an empty contenteditable (and into whitespace text nodes between pills).+ */+function commitImeText(root: HTMLElement, text: string, target?: Text) {+ if (target !== undefined) {+ target.textContent = `${target.textContent ?? ""}${text}`;+ } else {+ root.appendChild(document.createTextNode(text));+ }+ fireEvent.compositionEnd(root);+}++describe("SearchComposer IME composition", () => {+ it("does not duplicate Korean text committed into an empty bar", () => {+ const { store } = renderComposer();+ const root = composerRoot();++ act(() => {+ commitImeText(root, "μλ ");+ });++ expect(store.getState().draft).toBe("μλ ");+ expect(visibleComposerText(root)).toBe("μλ ");+ expect(hasDirectTextNode(root)).toBe(false);+ });++ it("lets Backspace delete the composed syllable after an IME commit", () => {+ const { store } = renderComposer();+ const root = composerRoot();++ act(() => {+ commitImeText(root, "μλ ");+ });+ expect(store.getState().draft).toBe("μλ ");++ act(() => {+ root.dispatchEvent(+ new InputEvent("beforeinput", {+ bubbles: true,+ cancelable: true,+ inputType: "deleteContentBackward",+ }),+ );+ });++ expect(store.getState().draft).toBe("μ");+ expect(visibleComposerText(root)).toBe("μ");+ expect(hasDirectTextNode(root)).toBe(false);+ });++ it("does not duplicate IME text written into the space between pills", () => {+ const { store } = renderComposer("level:ERROR ");+ const root = composerRoot();+ const spaceNode = lastSpaceTextNode(root);+ expect(spaceNode).not.toBeNull();++ act(() => {+ commitImeText(root, "μλ ", spaceNode!);+ });++ expect(store.getState().draft).toBe("level:ERROR μλ ");+ expect(visibleComposerText(root)).toBe("level:ERROR μλ ");+ expect(hasDirectTextNode(root)).toBe(false);+ });+});diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsxindex 6ebd562e95..5d2c65aeb3 100644--- a/web/src/features/search-bar/components/SearchComposer.tsx+++ b/web/src/features/search-bar/components/SearchComposer.tsx@@ -93,6 +93,22 @@ function textFromRoot(root: HTMLElement): string {return (root.textContent ?? "").replace(WORD_JOINER_RE, "");}+// IME composition (Korean, Chinese, Japanese) inserts a text node the+// contenteditable root does not already own. React will not remove that+// sibling when it later projects a token, so the composed run doubles and+// state-based delete cannot reach it. Strip those unmanaged nodes after+// reading textContent β token spans are all ELEMENT_NODE.+function stripUnmanagedRootChildren(root: HTMLElement): boolean {+ let removed = false;+ for (const child of Array.from(root.childNodes)) {+ if (child.nodeType !== Node.ELEMENT_NODE) {+ child.remove();+ removed = true;+ }+ }+ return removed;+}+function rawOffsetForLogicalOffset(text: string,logicalOffset: number,@@ -364,6 +380,10 @@ export function SearchComposer({const containerRef = React.useRef<HTMLDivElement>(null);// Selection to restore after the next reprojection of a controlled edit.const pendingSelectionRef = React.useRef<LogicalRange | null>(null);+ // Bumped after IME composition so token spans remount instead of keeping+ // text nodes the IME mutated in place (React skips an update when the+ // last rendered string is unchanged).+ const [tokensGeneration, setTokensGeneration] = React.useState(0);const selectionCollapsed = selectionSnapshot.start === selectionSnapshot.end;const caret = selectionSnapshot.end;@@ -560,10 +580,10 @@ export function SearchComposer({setHighlightedOptionId(null);}, []);- // Restore selection after a controlled mutation reprojected the DOM. Runs- // before paint so the caret never visibly jumps. External draft changes- // (URL nav) leave pendingSelectionRef null and the browser keeps whatever- // selection state it had.+ // Restore selection after a controlled mutation reprojected the DOM, and+ // after an IME remount of the token spans. Runs before paint so the caret+ // never visibly jumps. External draft changes (URL nav) leave+ // pendingSelectionRef null and the browser keeps whatever selection it had.React.useLayoutEffect(() => {const root = rootRef.current;const pending = pendingSelectionRef.current;@@ -572,7 +592,7 @@ export function SearchComposer({pendingSelectionRef.current = null;setSelectionRange(root, pending.start, pending.end);setSelectionSnapshot(pending);- }, [draft]);+ }, [draft, tokensGeneration]);// Mirror the native selection. Read-only: this effect never moves the// selection, it only snapshots it for completion planning and hover/focus@@ -598,8 +618,14 @@ export function SearchComposer({const root = rootRef.current;if (root === null) return;const next = textFromRoot(root);- if (next === draftRef.current) return;const caretNow = selectionOffsets(root).end;+ const stripped = stripUnmanagedRootChildren(root);+ if (next === draftRef.current && !stripped) return;+ setTokensGeneration((generation) => generation + 1);+ if (next === draftRef.current) {+ pendingSelectionRef.current = { start: caretNow, end: caretNow };+ return;+ }setDraftWithSelection(next, caretNow);openAutocompleteAfterEdit();}, [draftRef, openAutocompleteAfterEdit, setDraftWithSelection]);@@ -734,6 +760,9 @@ export function SearchComposer({const sel = selectionOffsets(root);caretAtEnd =sel.start === sel.end && sel.end === text.length && text.length > 0;+ if (stripUnmanagedRootChildren(root)) {+ setTokensGeneration((generation) => generation + 1);+ }if (text !== storeApi.getState().draft) actions.setDraft(text);}// The container validates, lowers, and writes the filter state; on failure@@ -1460,6 +1489,7 @@ export function SearchComposer({onMouseOver={onRootMouseOver}><ComposerTokens+ key={tokensGeneration}draft={draft}showDiagnostics={showTokenDiagnostics}scoreTypes={scoreTypes}