Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(filters): stop the sidebar from reordering mid-interaction (LFE-14843) (#15884)

Nikita Kabardin6f89f6827450
diff --git a/web/src/components/table/data-table-controls.clienttest.tsx b/web/src/components/table/data-table-controls.clienttest.tsx
index 5da56c31d3..6a828602ee 100644
--- a/web/src/components/table/data-table-controls.clienttest.tsx
+++ b/web/src/components/table/data-table-controls.clienttest.tsx
@@ -419,7 +419,88 @@ describe("DataTableControls facet ordering", () => {
expect(labelOrder("Beta", "Alpha")).toBe(true);
});
- it("re-sorts immediately when a facet's activity changes", () => {
+ it("keeps the order while the user works the list, and re-settles on an external change (LFE-14843)", () => {
+ const { rerender } = render(
+ <TooltipProvider>
+ <DataTableControls
+ queryFilter={queryFilter([
+ categoricalFilter("alpha", "Alpha", false),
+ categoricalFilter("beta", "Beta", true),
+ ])}
+ />
+ </TooltipProvider>,
+ );
+ expect(labelOrder("Beta", "Alpha")).toBe(true);
+
+ // Clicking inside the facet list marks what follows as the user's own
+ // edit: Alpha activating must not teleport out from under the cursor.
+ fireEvent.pointerDown(screen.getByText("Alpha"));
+ rerender(
+ <TooltipProvider>
+ <DataTableControls
+ queryFilter={queryFilter([
+ categoricalFilter("alpha", "Alpha", true),
+ categoricalFilter("beta", "Beta", true),
+ ])}
+ />
+ </TooltipProvider>,
+ );
+ expect(labelOrder("Beta", "Alpha")).toBe(true);
+
+ // A change from outside the sidebar (search bar, saved view, Clear all,
+ // AI apply) carries no facet interaction, so the order settles.
+ rerender(
+ <TooltipProvider>
+ <DataTableControls
+ queryFilter={queryFilter([
+ categoricalFilter("alpha", "Alpha", true),
+ categoricalFilter("beta", "Beta", false),
+ ])}
+ />
+ </TooltipProvider>,
+ );
+ expect(labelOrder("Alpha", "Beta")).toBe(true);
+ });
+
+ it("restores catalog order on Clear all, even with an in-list interaction outstanding", () => {
+ const { rerender } = render(
+ <TooltipProvider>
+ <DataTableControls
+ queryFilter={queryFilter([
+ categoricalFilter("alpha", "Alpha", false),
+ categoricalFilter("beta", "Beta", true),
+ ])}
+ />
+ </TooltipProvider>,
+ );
+ expect(labelOrder("Beta", "Alpha")).toBe(true);
+
+ // An in-list interaction that changes no promotion leaves its attribution
+ // outstanding — Clear all must not inherit it and keep Beta pinned.
+ fireEvent.pointerDown(screen.getByText("Beta"));
+ // Radix opens the menu on pointer-down, which jsdom doesn't synthesize
+ // reliably; the keyboard path opens it without PointerEvent support.
+ fireEvent.keyDown(screen.getByRole("button", { name: "Filter options" }), {
+ key: "Enter",
+ });
+ fireEvent.click(
+ screen.getByRole("menuitem", { name: "Clear all filters" }),
+ );
+
+ rerender(
+ <TooltipProvider>
+ <DataTableControls
+ queryFilter={queryFilter([
+ categoricalFilter("alpha", "Alpha", false),
+ categoricalFilter("beta", "Beta", false),
+ ])}
+ />
+ </TooltipProvider>,
+ );
+ expect(labelOrder("Alpha", "Beta")).toBe(true);
+ });
+
+ it("re-sorts immediately when a facet's activity changes externally", () => {
const { rerender } = render(
<TooltipProvider>
<DataTableControls
diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsx
index e4c153bf2f..9eb845658c 100644
--- a/web/src/components/table/data-table-controls.tsx
+++ b/web/src/components/table/data-table-controls.tsx
@@ -22,6 +22,13 @@ import {
getFacetSummaryValue,
rankFacetOptions,
} from "@/src/features/filters/lib/facet-display";
+import {
+ advanceFacetOrder,
+ orderFacets,
+ promoteFacet,
+ settleOnNextChange,
+ EMPTY_FACET_ORDER,
+} from "@/src/features/filters/lib/facet-order";
import { useMediaQuery } from "react-responsive";
import useLocalStorage from "@/src/components/useLocalStorage";
import { cn } from "@/src/utils/tailwind";
@@ -216,19 +223,42 @@ export function DataTableControls({
const [revealedColumns, setRevealedColumns] = useState<string[]>([]);
// Selected filters on top: a facet is PROMOTED when it carries an active
- // filter OR the user explicitly added it via "Add filter" — the explicit
- // add is a promotion in itself, so typing a first value (facet becomes
- // active) or clearing it again (inactive) never moves the facet around
- // while someone is working in it. Config order is preserved within each
- // group, the sort updates immediately, and both display modes share the
- // exact same order. When an interaction does move a facet (activation by
- // direct click), the follow-scroll effect below keeps it in view.
+ // filter OR the user explicitly added it via "Add filter". The order is
+ // SETTLED, not live (LFE-14843): the promoted set that drives it is
+ // recomputed at deliberate boundaries — mount, permalink hydration, a saved
+ // view, Clear all, an AI or search-bar apply — and held still while someone
+ // works the sidebar, so a facet activated by direct click never teleports
+ // out from under the cursor. Membership stays live: `showOnlyActive` and the
+ // active counts read isPromoted, only the ORDER is frozen.
const revealedSet = new Set(revealedColumns);
const isPromoted = (filter: UIFilter) =>
filter.isActive || revealedSet.has(filter.column);
- const orderedFilters = [...queryFilter.filters].sort(
- (a, b) => Number(isPromoted(b)) - Number(isPromoted(a)),
+ const livePromotedColumns = queryFilter.filters
+ .filter(isPromoted)
+ .map((filter) => filter.column);
+ // Bumped by any interaction inside the facet list (below); the pure reducer
+ // attributes the next promotion change to it instead of re-settling.
+ const facetInteractionRef = useRef(0);
+ const facetOrderRef = useRef(EMPTY_FACET_ORDER);
+ const facetOrder = advanceFacetOrder(
+ facetOrderRef.current,
+ livePromotedColumns,
+ facetInteractionRef.current,
);
+ facetOrderRef.current = facetOrder;
+ const noteFacetInteraction = () => {
+ facetInteractionRef.current += 1;
+ };
+ // Boundaries the sidebar owns itself (Clear all, AI apply): the change they
+ // cause must settle, so drop any attribution still outstanding.
+ const noteSettleBoundary = useCallback(() => {
+ facetOrderRef.current = settleOnNextChange(
+ facetOrderRef.current,
+ facetInteractionRef.current,
+ );
+ }, []);
+
+ const orderedFilters = orderFacets(queryFilter.filters, facetOrder);
const displayedFilters = showOnlyActive
? orderedFilters.filter(isPromoted)
: orderedFilters;
@@ -251,12 +281,13 @@ export function DataTableControls({
: [];
// Follow-scroll + recency: DOM scrolling is the external system here, so an
- // effect is the right integration boundary. When exactly one facet changed
- // activity (the user's own interaction — bulk changes like Clear all, AI
- // apply, or a restored view skip the scroll), the re-sort has already moved
- // it by the time this runs; scroll the list to its new position.
+ // effect is the right integration boundary. A single facet's activity change
+ // that DID move it (a re-settle, e.g. one filter applied from the search bar
+ // — the user's own sidebar edits no longer reorder anything) has moved it by
+ // the time this runs; scroll the list to its new position. Bulk changes
+ // (Clear all, AI apply, a restored view) skip the scroll.
const scrollRootRef = useRef<HTMLDivElement>(null);
- // Last focused element inside the list: re-sorting moves DOM nodes, and a
+ // Last focused element inside the list: a re-settle moves DOM nodes, and a
// reinserted node loses focus even when React merely reorders it — typing
// the first character into a facet's input must not kick the caret out.
const lastFocusedRef = useRef<HTMLElement | null>(null);
@@ -309,6 +340,10 @@ export function DataTableControls({
if (!queryFilter.expanded.includes(column)) {
queryFilter.onExpandedChange([...queryFilter.expanded, column]);
}
+ // Deliberate promotion: the added facet joins the top block without
+ // re-settling the facets around it.
+ noteFacetInteraction();
+ facetOrderRef.current = promoteFacet(facetOrderRef.current, column);
// The added facet lands at its config-order slot within the promoted
// group — bring it into view once the re-render has painted.
requestAnimationFrame(() => {
@@ -337,6 +372,7 @@ export function DataTableControls({
const handleFiltersGenerated = useCallback(
(filters: FilterState) => {
// Apply filters
+ noteSettleBoundary();
queryFilter.setFilterState(filters);
// The v3 wand previously emitted nothing at its only intent seam
// (metadata only: count of generated conditions, never their values).
@@ -360,10 +396,19 @@ export function DataTableControls({
// Close popover
setAiPopoverOpen(false);
},
- [queryFilter, capture, tableName],
+ [queryFilter, capture, tableName, noteSettleBoundary],
);
- const promotedFacetCount = displayedFilters.filter(isPromoted).length;
+ // Separator position: the SETTLED promoted block, not the live one — a facet
+ // activated mid-session keeps its place below the line until the next settle.
+ // Active-only mode has no inactive catalog to divide from, so no separator:
+ // counting every displayed facet keeps the divider out of the render loop's
+ // range, as the live count did before.
+ const promotedFacetCount = showOnlyActive
+ ? displayedFilters.length
+ : displayedFilters.filter((filter) =>
+ facetOrder.promoted.has(filter.column),
+ ).length;
const renderFacet = (filter: UIFilter) => {
// A column the current surface can't honour blocks the facet whether or
@@ -570,6 +615,13 @@ export function DataTableControls({
layout === "inline" ? "w-full" : "w-0 min-w-full",
"pt-1 pb-10",
)}
+ // Any interaction in the list marks the filter change it causes as the
+ // user's own edit, so the order holds still (LFE-14843). Capture phase,
+ // and on this node rather than the scroll root: React events propagate
+ // through portals by the React tree, so a facet's portalled dropdown
+ // (metadata keys, score names) counts too.
+ onPointerDownCapture={noteFacetInteraction}
+ onKeyDownCapture={noteFacetInteraction}
>
<Accordion
type="multiple"
@@ -875,6 +927,7 @@ export function DataTableControls({
// this, a value-less added facet stays pinned after
// Clear all and the active-only empty state can never
// render again this mount.
+ noteSettleBoundary();
setRevealedColumns([]);
queryFilter.clearAll();
}}
diff --git a/web/src/features/filters/lib/facet-order.clienttest.ts b/web/src/features/filters/lib/facet-order.clienttest.ts
new file mode 100644
index 0000000000..4100628a60
--- /dev/null
+++ b/web/src/features/filters/lib/facet-order.clienttest.ts
@@ -0,0 +1,97 @@
+import {
+ advanceFacetOrder,
+ EMPTY_FACET_ORDER,
+ orderFacets,
+ promoteFacet,
+ settleFacetOrder,
+ settleOnNextChange,
+} from "./facet-order";
+import type { FacetOrder } from "./facet-order";
+
+const CATALOG = [{ column: "alpha" }, { column: "beta" }, { column: "gamma" }];
+const shown = (order: FacetOrder) =>
+ orderFacets(CATALOG, order).map((facet) => facet.column);
+
+describe("facet order", () => {
+ it("settles promoted-first, config order within each group", () => {
+ expect(shown(settleFacetOrder(["beta"]))).toEqual([
+ "beta",
+ "alpha",
+ "gamma",
+ ]);
+ expect(shown(settleFacetOrder(["gamma", "beta"]))).toEqual([
+ "beta",
+ "gamma",
+ "alpha",
+ ]);
+ // no promotion at all: the config order stands
+ expect(shown(EMPTY_FACET_ORDER)).toEqual(["alpha", "beta", "gamma"]);
+ });
+
+ it("holds the order through the user's own edits and re-settles on the next external change", () => {
+ // Boundary (mount / permalink hydration): beta arrives active and promoted.
+ let order = advanceFacetOrder(EMPTY_FACET_ORDER, ["beta"], 0);
+ expect(shown(order)).toEqual(["beta", "alpha", "gamma"]);
+
+ // The user clicks a value on gamma, low in the list: it activates in place.
+ order = advanceFacetOrder(order, ["beta", "gamma"], 1);
+ expect(shown(order)).toEqual(["beta", "alpha", "gamma"]);
+
+ // A StrictMode re-render with the same inputs must not move anything.
+ expect(advanceFacetOrder(order, ["beta", "gamma"], 1)).toBe(order);
+
+ // Clearing beta mid-session leaves the layout alone too.
+ order = advanceFacetOrder(order, ["gamma"], 2);
+ expect(shown(order)).toEqual(["beta", "alpha", "gamma"]);
+
+ // An apply from elsewhere (search bar, saved view, Clear all, AI) carries
+ // no new facet interaction, so the order settles to reality.
+ order = advanceFacetOrder(order, ["alpha", "gamma"], 2);
+ expect(shown(order)).toEqual(["alpha", "gamma", "beta"]);
+ });
+
+ it("never holds a stale block: an outstanding interaction cannot survive an empty set or a boundary", () => {
+ // beta settled on top, then three in-list edits that changed values but not
+ // promotion: none of them consumed its token, so one is still outstanding.
+ const order = settleFacetOrder(["beta"]);
+ const token = 3;
+
+ // Clearing everything settles regardless — no block to hold, no separator.
+ expect(shown(advanceFacetOrder(order, [], token))).toEqual([
+ "alpha",
+ "beta",
+ "gamma",
+ ]);
+
+ // Left outstanding, the attribution would hold the old block…
+ expect(shown(advanceFacetOrder(order, ["gamma"], token))).toEqual([
+ "beta",
+ "alpha",
+ "gamma",
+ ]);
+ // …so a boundary the sidebar owns (Clear all, AI apply) drops it first.
+ expect(
+ shown(
+ advanceFacetOrder(settleOnNextChange(order, token), ["gamma"], token),
+ ),
+ ).toEqual(["gamma", "alpha", "beta"]);
+ });
+
+ it("promotes an added facet into the top block without re-settling the rest", () => {
+ // alpha activated in place during the session, so it stays below the line.
+ let order = advanceFacetOrder(
+ settleFacetOrder(["beta"]),
+ ["alpha", "beta"],
+ 1,
+ );
+ expect(shown(order)).toEqual(["beta", "alpha", "gamma"]);
+
+ // "Add filter" → gamma: a deliberate promotion of gamma only.
+ order = advanceFacetOrder(
+ promoteFacet(order, "gamma"),
+ ["alpha", "beta", "gamma"],
+ 2,
+ );
+ expect(shown(order)).toEqual(["beta", "gamma", "alpha"]);
+ });
+});
diff --git a/web/src/features/filters/lib/facet-order.ts b/web/src/features/filters/lib/facet-order.ts
new file mode 100644
index 0000000000..e1128ee15e
--- /dev/null
+++ b/web/src/features/filters/lib/facet-order.ts
@@ -0,0 +1,104 @@
+// Pure facet-ordering helpers for the filter sidebar
+// (data-table-controls.tsx). No React, no state — unit-testable.
+
+/**
+ * The settled promotion order: which facet columns sit in the sidebar's top
+ * block. Held across renders so the list does not reorder under the hands of
+ * someone working it (LFE-14843).
+ */
+export type FacetOrder = {
+ /** Columns in the top block, as settled at the last boundary. */
+ promoted: ReadonlySet<string>;
+ /** The live promoted columns this order was last reconciled against. */
+ key: string;
+ /** The facet-list interaction this order last attributed a change to. */
+ interactionToken: number;
+};
+
+export const EMPTY_FACET_ORDER: FacetOrder = {
+ promoted: new Set(),
+ key: "",
+ interactionToken: 0,
+};
+
+const orderKey = (promotedColumns: readonly string[]) =>
+ promotedColumns.join(",");
+
+/** Settle the order to the live promotion state. */
+export function settleFacetOrder(
+ promotedColumns: readonly string[],
+ interactionToken = 0,
+): FacetOrder {
+ return {
+ promoted: new Set(promotedColumns),
+ key: orderKey(promotedColumns),
+ interactionToken,
+ };
+}
+
+/**
+ * The order for the current render, given the live promoted columns and the
+ * facet list's interaction counter.
+ *
+ * A promotion change that follows an interaction inside the facet list is the
+ * user's own edit: the order stays as settled, so the facet being worked in
+ * never moves under the cursor. Every other cause — permalink hydration, a
+ * saved view, Clear all, an AI or search-bar apply — re-settles.
+ *
+ * Attribution consumes the token only when the promoted set actually changes,
+ * so an unrelated re-render between the click and the filter landing cannot
+ * eat it. Idempotent: same inputs, same output (StrictMode re-renders).
+ */
+export function advanceFacetOrder(
+ order: FacetOrder,
+ promotedColumns: readonly string[],
+ interactionToken: number,
+): FacetOrder {
+ const key = orderKey(promotedColumns);
+ if (key === order.key) return order;
+ // Nothing promoted means there is no block to protect, so never hold a stale
+ // one: whatever emptied the filters (Clear all, a cleared search bar) must
+ // fall back to plain config order.
+ const holdOrder =
+ promotedColumns.length > 0 && interactionToken !== order.interactionToken;
+ return holdOrder
+ ? { promoted: order.promoted, key, interactionToken }
+ : settleFacetOrder(promotedColumns, interactionToken);
+}
+
+/**
+ * Cancel any pending in-list attribution, so the change a boundary action
+ * causes settles even if an earlier interaction left one outstanding (an
+ * in-list edit that changed values without changing promotion never consumed
+ * its token). Called by the boundaries the sidebar owns: Clear all, AI apply.
+ */
+export function settleOnNextChange(
+ order: FacetOrder,
+ interactionToken: number,
+): FacetOrder {
+ return order.interactionToken === interactionToken
+ ? order
+ : { ...order, interactionToken };
+}
+
+/**
+ * "Add filter" is a deliberate promotion: the picked facet joins the top block
+ * (in config order) without re-settling the facets around it.
+ */
+export function promoteFacet(order: FacetOrder, column: string): FacetOrder {
+ if (order.promoted.has(column)) return order;
+ return { ...order, promoted: new Set(order.promoted).add(column) };
+}
+
+/** Promoted facets first, config order preserved within each group. */
+export function orderFacets<T extends { column: string }>(
+ facets: readonly T[],
+ order: FacetOrder,
+): T[] {
+ const promoted: T[] = [];
+ const rest: T[] = [];
+ for (const facet of facets) {
+ (order.promoted.has(facet.column) ? promoted : rest).push(facet);
+ }
+ return [...promoted, ...rest];
+}