Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(table): refresh tables in place instead of reloading them (#15984)

Nikita Kabardin31e709ddbdbf
diff --git a/web/src/components/table/data-table-refresh-button.tsx b/web/src/components/table/data-table-refresh-button.tsx
index 8c50c422b2..0ebe399adf 100644
--- a/web/src/components/table/data-table-refresh-button.tsx
+++ b/web/src/components/table/data-table-refresh-button.tsx
@@ -8,16 +8,11 @@ import {
DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu";
import { cn } from "@/src/utils/tailwind";
-
-export const REFRESH_INTERVALS = [
- { label: "Off", value: null },
- { label: "30s", value: 30_000 },
- { label: "1m", value: 60_000 },
- { label: "5m", value: 300_000 },
- { label: "15m", value: 900_000 },
-] as const;
-
-export type RefreshInterval = (typeof REFRESH_INTERVALS)[number]["value"];
+import { useAnimatedBusy } from "@/src/hooks/useAnimatedBusy";
+import {
+ REFRESH_INTERVALS,
+ type RefreshInterval,
+} from "@/src/components/table/utils/refresh-intervals";
interface DataTableRefreshButtonProps {
onRefresh: () => void;
@@ -43,6 +38,10 @@ export function DataTableRefreshButton({
const activeInterval = REFRESH_INTERVALS.find((i) => i.value === interval);
// Only a real interval counts as active; null ("Off") is the resting state.
const isActive = interval != null;
+ // A fast refresh would otherwise show a single frame of spinner. Not disabled
+ // while it spins either: the flash of the disabled state read as a glitch, and
+ // refreshing again mid-flight is harmless.
+ const { active: isSpinning } = useAnimatedBusy(isRefreshing);
return (
<div className="flex items-center">
@@ -50,14 +49,14 @@ export function DataTableRefreshButton({
variant="outline"
size="icon"
onClick={onRefresh}
- disabled={isRefreshing}
+ aria-busy={isSpinning}
className={cn(
"rounded-r-none border-r-0",
compact && isActive && "border-primary",
)}
title="Refresh"
>
- <RefreshCw className={cn("h-4 w-4", isRefreshing && "animate-spin")} />
+ <RefreshCw className={cn("h-4 w-4", isSpinning && "animate-spin")} />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsx
index a8942915e1..94ef6fdb91 100644
--- a/web/src/components/table/data-table-toolbar.tsx
+++ b/web/src/components/table/data-table-toolbar.tsx
@@ -48,10 +48,8 @@ import {
DropdownMenuSubContent,
} from "@/src/components/ui/dropdown-menu";
import { MultiSelect as MultiSelectFilter } from "@/src/features/filters/components/multi-select";
-import {
- DataTableRefreshButton,
- type RefreshInterval,
-} from "@/src/components/table/data-table-refresh-button";
+import { DataTableRefreshButton } from "@/src/components/table/data-table-refresh-button";
+import { type RefreshInterval } from "@/src/components/table/utils/refresh-intervals";
import {
getSearchButtonLabel,
getSearchMode,
diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsx
index 29e7b7a859..8518092a7b 100644
--- a/web/src/components/table/data-table.tsx
+++ b/web/src/components/table/data-table.tsx
@@ -52,6 +52,7 @@ import { type DataTablePeekViewProps } from "@/src/components/table/peek";
import isEqual from "lodash/isEqual";
import { useRouter } from "next/router";
import { useColumnSizing } from "@/src/components/table/hooks/useColumnSizing";
+import { useAnimatedBusy } from "@/src/hooks/useAnimatedBusy";
import {
type TableSelectionStoreLike,
useTableRowIsSelected,
@@ -61,8 +62,20 @@ import {
interface DataTableProps<TData, TValue> {
columns: LangfuseColumnDef<TData, TValue>[];
data: AsyncTableData<TData[]>;
+ /**
+ * A fetch is in flight while rows are already on screen (refresh, filter,
+ * page, sort). Renders a thin bar above the header instead of blanking the
+ * table: `data.isLoading` stays reserved for a genuine cold load.
+ */
+ isFetching?: boolean;
pagination?: {
totalCount: number | null; // null if loading or intentionally unknown
+ /**
+ * The exact count is still in flight while rows are already on screen (its
+ * query re-keys on a filter change one step behind the rows). Renders the
+ * page count as loading rather than as a result.
+ */
+ isTotalCountLoading?: boolean;
hasNextPage?: boolean;
onChange: OnChangeFn<PaginationState>;
state: PaginationState;
@@ -148,7 +161,7 @@ function isValidCssVariableName({
const INTERACTIVE_ROW_CLICK_SELECTOR =
"a, button, input, select, textarea, summary, [role='button'], [role='link']";
-export const shouldIgnoreRowClickTarget = (target: EventTarget | null) => {
+const shouldIgnoreRowClickTarget = (target: EventTarget | null) => {
if (!(target instanceof Element)) return false;
return Boolean(target.closest(INTERACTIVE_ROW_CLICK_SELECTOR));
@@ -198,6 +211,7 @@ const getCellPaddingClassName = (padding: DataTableCellPadding) => {
export function DataTable<TData extends object, TValue>({
columns,
data,
+ isFetching = false,
pagination,
rowSelection,
setRowSelection,
@@ -397,6 +411,11 @@ export function DataTable<TData extends object, TValue>({
columnVisibility,
]);
+ // Held for whole sweeps of the bar's animation: a 200ms refetch would
+ // otherwise flash a single frame.
+ // Cycle length matches the sweep, so a held refresh ends on a whole sweep.
+ const refetchBar = useAnimatedBusy(isFetching, REFETCH_SWEEP_MS);
+
const tableHeaders = shouldRenderGroupHeaders
? table.getHeaderGroups()
: [table.getHeaderGroups().slice(-1)[0]];
@@ -418,6 +437,17 @@ export function DataTable<TData extends object, TValue>({
className="relative min-h-full w-full overflow-auto border-t pr-2 [scrollbar-gutter:stable]"
style={{ ...columnSizeVars }}
>
+ {/* Zero-height so an arriving refetch never shifts the table. Sticky on
+ BOTH axes: this box is only as wide as the visible area, so without
+ `left-0` it scrolls out of view on a table wider than the viewport.
+ Keyed per busy period, not per fetch: one sweep from the left per
+ refresh, and no restart between a refresh's stages. */}
+ <div className="sticky top-0 left-0 z-30 h-0">
+ <TableRefetchBar
+ key={refetchBar.epoch}
+ active={refetchBar.active && !data.isLoading}
+ />
+ </div>
<Table>
<TableHeader className="sticky top-0 z-20">
{tableHeaders.map((headerGroup) => (
@@ -598,7 +628,9 @@ export function DataTable<TData extends object, TValue>({
<div className="bg-background sticky bottom-0 z-10 flex w-full justify-end border-t py-2 pr-2 font-bold">
<DataTablePagination
table={table}
- isLoading={data.isLoading}
+ isLoading={
+ data.isLoading || (pagination.isTotalCountLoading ?? false)
+ }
paginationOptions={pagination.options}
hideTotalCount={pagination.hideTotalCount}
canJumpPages={pagination.canJumpPages}
@@ -615,6 +647,69 @@ export function DataTable<TData extends object, TValue>({
);
}
+/**
+ * One sweep of the refetch bar. The single source of truth for the cycle: it is
+ * handed to the CSS animation as `--table-refetch-cycle` (see
+ * `--animate-table-refetch` in globals.css, which reads it with a fallback), and
+ * to `useAnimatedBusy` so the busy flag is only released on a whole sweep.
+ */
+const REFETCH_SWEEP_MS = 1400;
+
+/**
+ * The thin bar shown while a fetch runs over rows that are already on screen.
+ * Both edges are soft: the sweep is already running when the bar fades in (a
+ * one-shot fade rides on the sweep animation), and on the way out it fades
+ * first and only stops animating once that fade has finished. Mounted once per
+ * busy period β€” the caller keys it β€” so the sweep always starts from the left,
+ * and it never leaves an animation running behind an invisible bar.
+ */
+function TableRefetchBar({ active }: { active: boolean }) {
+ // The sweep runs only while the bar is on screen, plus the fade-out it has to
+ // survive. A bar that mounts idle β€” every table that passes no `isFetching`,
+ // and any table whose first render has nothing in flight β€” must never start it,
+ // and one that has faded out must stop. But `active` can also turn on within a
+ // single mount (a cold load holds it off until the skeletons go), so this
+ // cannot simply latch on the first render.
+ const [everActive, setEverActive] = useState(active);
+ const [fadedOut, setFadedOut] = useState(false);
+
+ if (active && !everActive) setEverActive(true);
+
+ const paused = !active && (!everActive || fadedOut);
+
+ return (
+ // Clipped track: the highlight sweeps out of view at both ends, and
+ // overflow-hidden keeps that from growing the table's scroll width. The fade
+ // uses an arbitrary transition, not `duration-*` β€” that utility sets
+ // --tw-duration, which `animate-*` reads as its animation-duration too, and
+ // turned the sweep into a strobe.
+ <div
+ aria-hidden="true"
+ onTransitionEnd={(event) => {
+ if (event.propertyName === "opacity" && !active) setFadedOut(true);
+ }}
+ className={cn(
+ "animate-table-refetch-in absolute inset-x-0 top-0 h-0.5 overflow-hidden [transition:opacity_200ms_ease-out]",
+ active ? "opacity-100" : "opacity-0",
+ )}
+ >
+ {/* Faint track, so the bar reads as one continuous element rather than a
+ highlight flashing in and out of nothing. Its own element: `cn` folds
+ two `bg-*` utilities into one and would drop it. */}
+ <div className="bg-primary-accent/20 absolute inset-0" />
+ <div
+ style={
+ { "--table-refetch-cycle": `${REFETCH_SWEEP_MS}ms` } as CSSProperties
+ }
+ className={cn(
+ "animate-table-refetch from-primary-accent/0 via-primary-accent to-primary-accent/0 absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r",
+ paused && "[animation-play-state:paused]",
+ )}
+ />
+ </div>
+ );
+}
+
function renderOrderingIndicator(orderBy?: OrderByState) {
if (!orderBy) return null;
if (orderBy.order === "ASC") return <span className="ml-1">β–²</span>;
diff --git a/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts b/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts
new file mode 100644
index 0000000000..eb259a1ba2
--- /dev/null
+++ b/web/src/components/table/hooks/usePaginationWindowPin.clienttest.ts
@@ -0,0 +1,63 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, vi } from "vitest";
+
+import { usePaginationWindowPin } from "./usePaginationWindowPin";
+
+const START = new Date("2026-08-12T12:00:00.000Z");
+const LIVE = { from: new Date("2026-08-11T12:00:00.000Z"), to: undefined };
+const NEWEST_ON_PAGE_1 = new Date("2026-08-12T11:59:58.000Z");
+
+describe("usePaginationWindowPin", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(START);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("pins to the row page 1 ended on, holds it while paging, and goes live on return", () => {
+ const { result, rerender } = renderHook(
+ ({ pageIndex }: { pageIndex: number }) =>
+ usePaginationWindowPin(LIVE, pageIndex),
+ { initialProps: { pageIndex: 0 } },
+ );
+
+ // Page 1 is the live tail: no upper bound, so new rows keep arriving.
+ expect(result.current.range?.to).toBeUndefined();
+
+ // Rows keep arriving while the reader sits on page 1; leaving it must pin to
+ // what was on screen, NOT to now, or page 2 re-includes the new arrivals.
+ vi.setSystemTime(new Date(START.getTime() + 40_000));
+ act(() => result.current.pinOnLeavingFirstPage(1, NEWEST_ON_PAGE_1));
+ rerender({ pageIndex: 1 });
+ expect(result.current.range?.to).toEqual(NEWEST_ON_PAGE_1);
+
+ // Paging further keeps that same set: offsets stay meaningful.
+ const pinned = result.current.range;
+ rerender({ pageIndex: 2 });
+ expect(result.current.range).toBe(pinned);
+
+ rerender({ pageIndex: 0 });
+ expect(result.current.range?.to).toBeUndefined();
+
+ // Going back out again re-pins to that page's newest row, not the stale one.
+ const newerTop = new Date(START.getTime() + 60_000);
+ act(() => result.current.pinOnLeavingFirstPage(1, newerTop));
+ rerender({ pageIndex: 1 });
+ expect(result.current.range?.to).toEqual(newerTop);
+ });
+
+ it("pins to now when a later page is opened directly, and leaves closed ranges alone", () => {
+ const { result } = renderHook(() => usePaginationWindowPin(LIVE, 2));
+ expect(result.current.range?.to).toEqual(START);
+
+ const absolute = {
+ from: new Date("2026-01-01T00:00:00.000Z"),
+ to: new Date("2026-01-02T00:00:00.000Z"),
+ };
+ const closed = renderHook(() => usePaginationWindowPin(absolute, 2));
+ expect(closed.result.current.range).toBe(absolute);
+ });
+});
diff --git a/web/src/components/table/hooks/usePaginationWindowPin.ts b/web/src/components/table/hooks/usePaginationWindowPin.ts
new file mode 100644
index 0000000000..ecf2755b47
--- /dev/null
+++ b/web/src/components/table/hooks/usePaginationWindowPin.ts
@@ -0,0 +1,48 @@
+import { useCallback, useMemo, useState } from "react";
+import { type TableDateRange } from "@/src/utils/date-range-utils";
+
+/**
+ * Holds the paged result set still while the reader is past the first page.
+ *
+ * Rows are paged by offset over a timestamp-DESC set, so a window left open at
+ * the top grows underneath someone on page 2: every row ingested since page 1
+ * was fetched shifts the offsets, repeating rows the reader already saw and
+ * pushing others past the last page, while the count query drifts with it.
+ *
+ * Page 1 is the live tail and stays open-ended. Leaving it pins the upper bound
+ * to the newest row that was on screen β€” the top of exactly the set page 1 was
+ * computed over, so page 2 continues where page 1 ended. Pinning to "now"
+ * instead would re-include everything ingested while the reader sat on page 1,
+ * which is the same off-by-N it is meant to prevent.
+ *
+ * The pin is only *applied* past page 1, so the page state (which lives in the
+ * URL and lands a render later than the handler) can never strand it, and
+ * returning to page 1 goes live again. Opening a later page directly has no page
+ * 1 to align with, so it pins to that first render instead. An already-closed
+ * window (an absolute range) is left alone.
+ */
+export function usePaginationWindowPin(
+ range: TableDateRange | undefined,
+ pageIndex: number,
+) {
+ const [pinnedAt, setPinnedAt] = useState<Date | null>(() =>
+ pageIndex > 0 ? new Date() : null,
+ );
+
+ const pin = pageIndex > 0 ? pinnedAt : null;
+
+ const pinnedRange = useMemo(
+ () => (range && !range.to && pin ? { from: range.from, to: pin } : range),
+ [range, pin],
+ );
+
+ /** Call from the pagination handler, where the leaving page's rows are known. */
+ const pinOnLeavingFirstPage = useCallback(
+ (nextPageIndex: number, newestVisible: Date | undefined) => {
+ if (nextPageIndex > 0) setPinnedAt(newestVisible ?? new Date());
+ },
+ [],
+ );
+
+ return { range: pinnedRange, pinOnLeavingFirstPage };
+}
diff --git a/web/src/components/table/hooks/usePendingRowIds.ts b/web/src/components/table/hooks/usePendingRowIds.ts
new file mode 100644
index 0000000000..d3b2dc2c3d
--- /dev/null
+++ b/web/src/components/table/hooks/usePendingRowIds.ts
@@ -0,0 +1,25 @@
+import { useMemo } from "react";
+
+type BatchQueryLike<TItem> = {
+ data?: TItem[];
+ isPending: boolean;
+ isFetching: boolean;
+};
+
+/**
+ * Per-row loading state for a batch query that lands one step behind the rows
+ * (trace metrics, batched I/O). A row keeps whatever it already has while the
+ * next batch is in flight; only a row whose id has not arrived yet reads as
+ * pending β€” so a refresh does not blink every cell back to a skeleton.
+ */
+export function usePendingRowIds<TItem extends { id: string }>(
+ query: BatchQueryLike<TItem>,
+): (rowId: string) => boolean {
+ const loadedIds = useMemo(
+ () => new Set((query.data ?? []).map((item) => item.id)),
+ [query.data],
+ );
+
+ return (rowId: string) =>
+ (query.isPending || query.isFetching) && !loadedIds.has(rowId);
+}
diff --git a/web/src/components/table/table-header-controls.tsx b/web/src/components/table/table-header-controls.tsx
index 2fcf318e2a..c1919e1f71 100644
--- a/web/src/components/table/table-header-controls.tsx
+++ b/web/src/components/table/table-header-controls.tsx
@@ -1,8 +1,6 @@
import { TimeRangePicker } from "@/src/components/date-picker";
-import {
- DataTableRefreshButton,
- type RefreshInterval,
-} from "@/src/components/table/data-table-refresh-button";
+import { DataTableRefreshButton } from "@/src/components/table/data-table-refresh-button";
+import { type RefreshInterval } from "@/src/components/table/utils/refresh-intervals";
import { PageHeaderControlsPortal } from "@/src/components/layouts/page-header-controls-slot";
import {
TABLE_AGGREGATION_OPTIONS,
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index de1b613f6e..52cebcf18e 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -100,9 +100,9 @@ import useSessionStorage from "@/src/components/useSessionStorage";
import { buildTraceDetailPath } from "@/src/utils/navigation";
import { getSafeRedirectPath } from "@/src/utils/redirect";
import {
- type RefreshInterval,
REFRESH_INTERVALS,
-} from "@/src/components/table/data-table-refresh-button";
+ type RefreshInterval,
+} from "@/src/components/table/utils/refresh-intervals";
import {
ObservationsTableStoreProvider,
useObservationsTableStore,
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 60bb777050..646fd38f81 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -54,7 +54,9 @@ import {
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
-import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
+import { useLiveTableDateRange } from "@/src/hooks/useLiveTableDateRange";
+import { usePendingRowIds } from "@/src/components/table/hooks/usePendingRowIds";
+import { usePaginationWindowPin } from "@/src/components/table/hooks/usePaginationWindowPin";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
@@ -97,9 +99,9 @@ import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextS
import { type TableDateRange } from "@/src/utils/date-range-utils";
import useSessionStorage from "@/src/components/useSessionStorage";
import {
- type RefreshInterval,
REFRESH_INTERVALS,
-} from "@/src/components/table/data-table-refresh-button";
+ type RefreshInterval,
+} from "@/src/components/table/utils/refresh-intervals";
import { TableHeaderControls } from "@/src/components/table/table-header-controls";
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
@@ -202,22 +204,13 @@ export default function TracesTable({
[allowedValues, setRawRefreshInterval],
);
- const [refreshTick, setRefreshTick] = useState(0);
const [manualRefreshTrigger, setManualRefreshTrigger] = useState(0); // resets the interval when manual refresh is called
const { setDetailPageList } = useDetailPageLists();
- // Auto-increment refresh tick to force date range recalculation
- useEffect(() => {
- if (!refreshInterval) return;
- const id = setInterval(() => {
- setRefreshTick((t) => t + 1);
- }, refreshInterval);
- return () => clearInterval(id);
- }, [refreshInterval, manualRefreshTrigger]);
-
- const handleRefresh = useCallback(() => {
- setRefreshTick((t) => t + 1);
- setManualRefreshTrigger((t) => t + 1);
+ // A refresh is invalidation only: the queried window is anchored (see
+ // useLiveTableDateRange), so a refetch reuses the same query keys and updates
+ // the rows on screen in place instead of blanking them.
+ const invalidateTableQueries = useCallback(() => {
Promise.all([
utils.traces.all.invalidate(),
utils.traces.metrics.invalidate(),
@@ -227,14 +220,20 @@ export default function TracesTable({
]);
}, [utils]);
+ const handleRefresh = useCallback(() => {
+ setManualRefreshTrigger((t) => t + 1);
+ invalidateTableQueries();
+ }, [invalidateTableQueries]);
+
+ useEffect(() => {
+ if (!refreshInterval) return;
+ const id = setInterval(invalidateTableQueries, refreshInterval);
+ return () => clearInterval(id);
+ }, [refreshInterval, manualRefreshTrigger, invalidateTableQueries]);
+
const { timeRange, setTimeRange } = useTableDateRange(projectId);
- // Convert timeRange to absolute date range for compatibility
- // refreshTick forces recalculation on each refresh cycle
- const tableDateRange = useMemo(() => {
- return toAbsoluteTimeRange(timeRange) ?? undefined;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [timeRange, refreshTick]);
+ const { range: tableDateRange } = useLiveTableDateRange(timeRange);
const dateRange = externalDateRange ?? tableDateRange;
@@ -243,26 +242,44 @@ export default function TracesTable({
order: "DESC",
});
- const dateRangeFilter: FilterState = dateRange
- ? [
- {
- column: "timestamp",
- type: "datetime",
- operator: ">=",
- value: dateRange.from,
- },
- ...(dateRange.to
- ? [
- {
- column: "timestamp",
- type: "datetime",
- operator: "<=",
- value: dateRange.to,
- } as const,
- ]
- : []),
- ]
- : [];
+ const toTimestampFilter = (range: TableDateRange | undefined): FilterState =>
+ range
+ ? [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: range.from,
+ },
+ ...(range.to
+ ? [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: "<=",
+ value: range.to,
+ } as const,
+ ]
+ : []),
+ ]
+ : [];
+
+ const [paginationState, setPaginationState] = usePaginationState(0, 50, {
+ page: "pageIndex",
+ limit: "pageSize",
+ });
+ const { selectAll, setSelectAll } = useSelectAll(projectId, "traces");
+
+ // Facets describe the whole window; only the paged row/count queries need the
+ // upper bound pinned, so that offset paging does not repeat or skip rows while
+ // the window keeps taking in newly ingested ones.
+ const dateRangeFilter: FilterState = toTimestampFilter(dateRange);
+ const { range: rowsDateRange, pinOnLeavingFirstPage } =
+ usePaginationWindowPin(
+ dateRange,
+ limitRows ? 0 : paginationState.pageIndex,
+ );
+ const rowsDateRangeFilter: FilterState = toTimestampFilter(rowsDateRange);
const userIdFilter: FilterState = userId
? [
{
@@ -401,7 +418,7 @@ export default function TracesTable({
const combinedFilterState = queryFilter.effectiveFilterState.concat(
userIdFilter,
- dateRangeFilter,
+ rowsDateRangeFilter,
);
// Use external filter state if provided, otherwise use combined filter
@@ -409,15 +426,9 @@ export default function TracesTable({
// callers that pass an externalDateRange (e.g. the eval preview's "last 24
// hours" window) have it honored for the row query, not just score columns.
const filterState = externalFilterState
- ? externalFilterState.concat(dateRangeFilter)
+ ? externalFilterState.concat(rowsDateRangeFilter)
: combinedFilterState;
- const [paginationState, setPaginationState] = usePaginationState(0, 50, {
- page: "pageIndex",
- limit: "pageSize",
- });
- const { selectAll, setSelectAll } = useSelectAll(projectId, "traces");
-
const { searchQuery, searchType, setSearchQuery, setSearchType } =
useFullTextSearch();
const legacyTracingSearchConfig = api.public.tracingSearchConfig.useQuery(
@@ -440,6 +451,10 @@ export default function TracesTable({
orderBy: null,
};
+ // Deliberately NOT placeholder-backed, unlike the row query: its key only
+ // changes when the filter does, and keeping the previous value would pair rows
+ // for the new filter with a count for the old one. It reports as loading
+ // instead until it catches up.
const totalCountQuery = api.traces.countAll.useQuery(tracesAllCountFilter, {
enabled: environmentFilterOptions.data !== undefined,
});
@@ -453,10 +468,14 @@ export default function TracesTable({
orderBy: orderByState,
};
+ // A filter/page/sort change (or a re-anchored window) is a new query key:
+ // keep the rows that are on screen until the new ones land, so only a genuine
+ // cold load renders skeletons.
const traces = api.traces.all.useQuery(tracesAllQueryFilter, {
enabled: environmentFilterOptions.data !== undefined,
refetchOnMount: false,
refetchOnWindowFocus: true,
+ placeholderData: (prev) => prev,
});
const traceMetrics = api.traces.metrics.useQuery(
{
@@ -468,9 +487,13 @@ export default function TracesTable({
enabled: traces.data !== undefined,
refetchOnMount: false,
refetchOnWindowFocus: true,
+ placeholderData: (prev) => prev,
},
);
+ // Metrics arrive per trace id, one query behind the rows.
+ const isMetricPending = usePendingRowIds(traceMetrics);
+
type TracesCoreOutput = RouterOutput["traces"]["all"]["traces"][number];
type TraceMetricOutput = RouterOutput["traces"]["metrics"][number];
@@ -769,7 +792,7 @@ export default function TracesTable({
cell: ({ row }) => {
const value: TracesTableRow["levelCounts"] =
row.getValue("levelCounts");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id)) return <TableTextLoadingCell />;
const counts: LevelCount[] = Object.entries(value).map(
([level, count]) => ({
@@ -792,7 +815,7 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const value: TracesTableRow["latency"] = row.getValue("latency");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id)) return <TableTextLoadingCell />;
return value !== undefined ? (
<span className="text-nowrap">{formatIntervalSeconds(value)}</span>
) : undefined;
@@ -809,7 +832,7 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id)) return <TableTextLoadingCell />;
if (!value.inputUsage && !value.outputUsage && !value.totalUsage) {
return null;
}
@@ -839,7 +862,7 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const cost: TracesTableRow["totalCost"] = row.getValue("totalCost");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id)) return <TableTextLoadingCell />;
return cost != null ? (
<BreakdownTooltip details={row.original.costDetails ?? []} isCost>
<div className="flex items-center gap-1">
@@ -1063,7 +1086,7 @@ export default function TracesTable({
cell: ({ row }) => {
const value: TracesTableRow["observationCount"] =
row.getValue("observationCount");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id)) return <TableTextLoadingCell />;
return <span>{numberFormatter(value, 0)}</span>;
},
},
@@ -1075,7 +1098,7 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const value: TracesTableRow["level"] = row.getValue("level");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id)) return <TableTextLoadingCell />;
return value ? (
<span
className={cn(
@@ -1183,7 +1206,8 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const cost: TracesTableRow["cost"] = row.getValue("cost");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id))
+ return <TableTextLoadingCell />;
return (
<div>
{cost?.inputCost ? (
@@ -1206,7 +1230,8 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const cost: TracesTableRow["cost"] = row.getValue("cost");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id))
+ return <TableTextLoadingCell />;
return (
<div>
{cost?.outputCost ? (
@@ -1241,7 +1266,8 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id))
+ return <TableTextLoadingCell />;
return <span>{numberFormatter(value.inputUsage, 0)}</span>;
},
enableHiding: true,
@@ -1256,7 +1282,8 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id))
+ return <TableTextLoadingCell />;
return <span>{numberFormatter(value.outputUsage, 0)}</span>;
},
enableHiding: true,
@@ -1271,7 +1298,8 @@ export default function TracesTable({
loadingCell: <TableTextLoadingCell />,
cell: ({ row }) => {
const value: TracesTableRow["usage"] = row.getValue("usage");
- if (!traceMetrics.data) return <TableTextLoadingCell />;
+ if (isMetricPending(row.original.id))
+ return <TableTextLoadingCell />;
return <span>{numberFormatter(value.totalUsage, 0)}</span>;
},
enableHiding: true,
@@ -1546,6 +1574,7 @@ export default function TracesTable({
<DataTable
columns={columns}
hidePagination={hideControls}
+ isFetching={refreshConfig.isRefreshing}
data={
traces.isPending || isViewLoading
? { isLoading: true, isError: false }
@@ -1566,7 +1595,21 @@ export default function TracesTable({
? undefined
: {
totalCount,
- onChange: setPaginationState,
+ isTotalCountLoading: totalCountQuery.isPending,
+ onChange: (updater) => {
+ const next =
+ typeof updater === "function"
+ ? updater(paginationState)
+ : updater;
+ // Leaving page 1 freezes the paged set at the newest row
+ // still on screen, so page 2 continues where this page
+ // ends even if rows keep arriving.
+ pinOnLeavingFirstPage(
+ next.pageIndex,
+ rows[0]?.timestamp,
+ );
+ setPaginationState(next);
+ },
state: paginationState,
}
}
diff --git a/web/src/components/table/utils/refresh-intervals.ts b/web/src/components/table/utils/refresh-intervals.ts
new file mode 100644
index 0000000000..f2c557a269
--- /dev/null
+++ b/web/src/components/table/utils/refresh-intervals.ts
@@ -0,0 +1,10 @@
+/** Auto-refresh choices offered by the table refresh control. */
+export const REFRESH_INTERVALS = [
+ { label: "Off", value: null },
+ { label: "30s", value: 30_000 },
+ { label: "1m", value: 60_000 },
+ { label: "5m", value: 300_000 },
+ { label: "15m", value: 900_000 },
+] as const;
+
+export type RefreshInterval = (typeof REFRESH_INTERVALS)[number]["value"];
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index a04c4ce334..3b1e27db39 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -6,6 +6,7 @@ import {
} from "@/src/components/table/data-table-controls";
import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";
import { useEffect, useMemo, useState, useRef, useCallback } from "react";
+import { startOfMinute } from "date-fns";
import { usePaginationState } from "@/src/hooks/usePaginationState";
import {
type UseSidebarFilterStateOptions,
@@ -54,8 +55,9 @@ import {
useRowHeightLocalStorage,
} from "@/src/components/table/data-table-row-height-switch";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
+import { useLiveTableDateRange } from "@/src/hooks/useLiveTableDateRange";
+import { usePaginationWindowPin } from "@/src/components/table/hooks/usePaginationWindowPin";
import {
- toAbsoluteTimeRange,
type TableDateRange,
TABLE_AGGREGATION_OPTIONS,
} from "@/src/utils/date-range-utils";
@@ -116,9 +118,9 @@ import { getSafeRedirectPath } from "@/src/utils/redirect";
// import { useObservationCountCheck } from "@/src/features/events/hooks/useObservationCountCheck";
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
import {
- type RefreshInterval,
REFRESH_INTERVALS,
-} from "@/src/components/table/data-table-refresh-button";
+ type RefreshInterval,
+} from "@/src/components/table/utils/refresh-intervals";
import useSessionStorage from "@/src/components/useSessionStorage";
import { api } from "@/src/utils/api";
import { RunEvaluationDialog } from "@/src/features/batch-actions/components/RunEvaluationDialog/index";
@@ -405,70 +407,38 @@ export default function ObservationsEventsTable({
[allowedValues, setRawRefreshInterval],
);
- const [refreshTick, setRefreshTick] = useState(0);
- // Facet options are not "live": the auto-refresh tick must keep updating the
- // table rows without re-fetching facets (their values don't change tick to
- // tick). They re-anchor only on a real scope change β€” a new time range or an
- // explicit refresh β€” tracked by this separate tick, which the auto interval
- // never bumps.
- const [filterOptionsRefreshTick, setFilterOptionsRefreshTick] = useState(0);
-
- // Tick-safe refresh: table rows + counts + the chart query, WITHOUT
- // re-anchoring facet options (their values don't change tick-to-tick, so
- // re-fetching open high-cardinality facets every tick is wasteful). The auto
- // interval uses this. The chart runs dashboard.executeQuery; for absolute
- // time ranges its query key is stable across refreshes, so invalidate it too.
- const handleAutoRefresh = useCallback(() => {
- setRefreshTick((t) => t + 1);
- Promise.all([
- utils.events.all.invalidate(),
- utils.events.countAll.invalidate(),
- // Invalidate filterOptions too so the "Total β‰ˆ X" count refreshes on the auto tick (re-anchors facets as a side effect).
- utils.events.filterOptions.invalidate(),
- utils.dashboard.executeQuery.invalidate(),
- ]);
- }, [utils]);
+ // When the chart/outlier-strip window (below) last advanced. Truncated to the
+ // minute: a to-the-millisecond bound re-keyed the chart query on every tick,
+ // and that cold load is what faded the strip out mid-refresh.
+ const [chartRefreshedAtMs, setChartRefreshedAt] = useState(() =>
+ startOfMinute(new Date()).getTime(),
+ );
- // Explicit refresh (manual button): everything the auto tick does, PLUS
- // re-anchoring the facet options β€” the one place their values are re-read.
+ // A refresh is invalidation only: rows, counts and facet options share one
+ // anchored window (see useLiveTableDateRange), so every refetch reuses its
+ // query key and updates in place instead of re-keying into a cold load. The
+ // chart runs dashboard.executeQuery, which is invalidated alongside.
const handleRefresh = useCallback(() => {
- setRefreshTick((t) => t + 1);
- setFilterOptionsRefreshTick((t) => t + 1);
+ setChartRefreshedAt(startOfMinute(new Date()).getTime());
Promise.all([
utils.events.all.invalidate(),
utils.events.countAll.invalidate(),
+ // Invalidate filterOptions too so the "Total β‰ˆ X" count refreshes.
utils.events.filterOptions.invalidate(),
utils.dashboard.executeQuery.invalidate(),
]);
}, [utils]);
- // Auto-refresh runs handleAutoRefresh (rows + chart + the "Total β‰ˆ X" filter-options scan).
useEffect(() => {
if (!refreshInterval) return;
- const id = setInterval(() => {
- handleAutoRefresh();
- }, refreshInterval);
+ const id = setInterval(handleRefresh, refreshInterval);
return () => clearInterval(id);
- }, [refreshInterval, handleAutoRefresh]);
-
- // Convert timeRange to absolute date range for compatibility
- // Include refreshTick to force recalculation on refresh
- const tableDateRange = useMemo(() => {
- // refreshTick forces recalculation but isn't used in computation
- refreshTick;
- return toAbsoluteTimeRange(timeRange) ?? undefined;
- }, [timeRange, refreshTick]);
-
- // Same absolute range, but anchored to scope changes only (NOT the auto tick),
- // so opening/keeping a facet open never re-fetches on a refresh interval.
- const filterOptionsTableDateRange = useMemo(() => {
- filterOptionsRefreshTick;
- return toAbsoluteTimeRange(timeRange) ?? undefined;
- }, [timeRange, filterOptionsRefreshTick]);
+ }, [refreshInterval, handleRefresh]);
+
+ const { range: tableDateRange, anchoredTo } =
+ useLiveTableDateRange(timeRange);
const dateRange = externalDateRange ?? tableDateRange;
- const filterOptionsDateRange =
- externalDateRange ?? filterOptionsTableDateRange;
// Chart view ("any view is a chart"): URL-driven table↔chart toggle + config.
// Only offered on the full (non-embedded) events surface, which is already
@@ -484,13 +454,25 @@ export default function ObservationsEventsTable({
config: chartConfig,
setConfig: setChartConfig,
} = useChartViewState();
- const chartTimeWindow = useMemo(
- () => ({
- from: dateRange?.from ?? new Date(Date.now() - 24 * 60 * 60 * 1000),
- to: dateRange?.to ?? new Date(),
- }),
- [dateRange],
- );
+ // Unlike the table, the chart and the outlier strip need a CLOSED window. Both
+ // ends are derived from the same length: the end is the later of the window's
+ // anchor and the last refresh, and the start is measured back from that end β€”
+ // never taken from the table's anchored `from`, which would let the window grow
+ // between anchors, or invert once the user picks a range shorter than the time
+ // since the last refresh.
+ const chartTimeWindow = useMemo(() => {
+ const anchorMs = anchoredTo?.getTime();
+ const fromMs = dateRange?.from.getTime();
+ const lengthMs =
+ anchorMs !== undefined && fromMs !== undefined
+ ? anchorMs - fromMs
+ : 24 * 60 * 60 * 1000;
+ const endMs = dateRange?.to
+ ? dateRange.to.getTime()
+ : Math.max(anchorMs ?? 0, chartRefreshedAtMs);
+
+ return { from: new Date(endMs - lengthMs), to: new Date(endMs) };
+ }, [dateRange, anchoredTo, chartRefreshedAtMs]);
// Drill-in writes the clicked bucket as an absolute range. URL-only
// (pushIn β†’ browser Back restores the outer window) and deliberately NOT
@@ -500,7 +482,12 @@ export default function ObservationsEventsTable({
persistAsDefault: false,
});
- const dateRangeFilter: FilterState = toStartTimeFilterState(dateRange);
+ // Facets describe the whole window (see facetStartTimeFilter below); the paged
+ // row/count queries take the pinned upper bound instead, so offset paging does
+ // not repeat or skip rows while the window keeps taking in newly ingested ones.
+ const { range: rowsDateRange, pinOnLeavingFirstPage } =
+ usePaginationWindowPin(dateRange, limitRows ? 0 : paginationState.page - 1);
+ const dateRangeFilter: FilterState = toStartTimeFilterState(rowsDateRange);
const appRootDefault = useAppRootDefault({
enabled: enableAppRootDefault,
@@ -621,17 +608,18 @@ export default function ObservationsEventsTable({
[userId, sessionId, promptName, promptVersion],
);
- // The time window travels separately, on the tick-decoupled range so the
- // auto refresh leaves the facets alone.
const facetRefiningFilter = useMemo(
() =>
externalFilterState ??
filterCore.filterState.concat(embedScopeFilterState),
[externalFilterState, filterCore.filterState, embedScopeFilterState],
);
+ // Same anchored window as the rows: the facets no longer need a tick-decoupled
+ // range to survive an auto refresh, because the window itself no longer moves
+ // tick to tick.
const facetStartTimeFilter = useMemo(
- () => toStartTimeFilterState(filterOptionsDateRange),
- [filterOptionsDateRange],
+ () => toStartTimeFilterState(dateRange),
+ [dateRange],
);
// Fetch filter options. Lazy: start with the eagerly-visible facets and load
@@ -835,8 +823,8 @@ export default function ObservationsEventsTable({
isTotalCountError,
hasMore,
handleAddToAnnotationQueue,
- dataUpdatedAt,
- ioLoading,
+ isFetching,
+ isIoPending,
isSilencedError,
usedAppRootFallback,
} = useEventsTableData({
@@ -1198,7 +1186,7 @@ export default function ObservationsEventsTable({
),
cell: ({ row }) => {
const value: string | undefined = row.getValue("input");
- if (ioLoading) {
+ if (isIoPending(row.original.id)) {
return (
<JsonSkeleton
numRows={rowHeight === "s" ? 1 : undefined}
@@ -1231,7 +1219,7 @@ export default function ObservationsEventsTable({
),
cell: ({ row }) => {
const value: string | undefined = row.getValue("output");
- if (ioLoading) {
+ if (isIoPending(row.original.id)) {
return (
<JsonSkeleton
numRows={rowHeight === "s" ? 1 : undefined}
@@ -1268,7 +1256,7 @@ export default function ObservationsEventsTable({
},
cell: ({ row }) => {
const value: string | undefined = row.getValue("metadata");
- if (ioLoading) {
+ if (isIoPending(row.original.id)) {
return (
<JsonSkeleton
numRows={rowHeight === "s" ? 1 : undefined}
@@ -1899,7 +1887,7 @@ export default function ObservationsEventsTable({
const refreshConfig = {
onRefresh: handleRefresh,
- isRefreshing: observations.status === "loading",
+ isRefreshing: isFetching,
interval: refreshInterval,
setInterval: setRefreshInterval,
};
@@ -2283,11 +2271,14 @@ export default function ObservationsEventsTable({
onConfigChange={setChartConfig}
/>
) : (
+ // No remount key: keying this on the fetch timestamp threw the
+ // table (and its scroll position) away on every refresh. The body
+ // re-renders on the new row array by itself.
<DataTable
- key={`observations-table-${dataUpdatedAt}-${rows.length > 0 && rows[0]?.input ? "with-io" : "without-io"}`}
tableName="observations"
columns={columns}
peekView={peekConfig}
+ isFetching={isFetching}
data={
observations.status === "loading" || isViewLoading
? { isLoading: true, isError: false }
@@ -2337,6 +2328,13 @@ export default function ObservationsEventsTable({
pageSize: paginationState.limit,
})
: updater;
+ // Leaving page 1 freezes the paged set at the newest
+ // row still on screen, so page 2 continues where this
+ // page ends even if rows keep arriving.
+ pinOnLeavingFirstPage(
+ newState.pageIndex,
+ rows[0]?.startTime ?? undefined,
+ );
setPaginationState({
page: newState.pageIndex + 1,
limit: newState.pageSize,
diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.ts
index b727124f9e..41e25b7072 100644
--- a/web/src/features/events/hooks/useEventsTableData.ts
+++ b/web/src/features/events/hooks/useEventsTableData.ts
@@ -9,6 +9,7 @@ import {
import { type FullEventsObservations } from "@langfuse/shared/src/server";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
+import { usePendingRowIds } from "@/src/components/table/hooks/usePendingRowIds";
import { type EventBatchIOOutput } from "@/src/features/events/server/eventsRouter";
import {
removeAppRootDefaultFilter,
@@ -135,11 +136,10 @@ export function useEventsTableData({
appRootFallbackQuery.isSuccess &&
appRootFallbackQuery.data.observations.length > 0;
+ // Built from the rows on screen, placeholder or not: while the row query is
+ // showing the previous page the payload β€” and therefore the I/O query key β€”
+ // is the previous one too, so the cells keep the I/O they already have.
const batchIOPayload = useMemo(() => {
- if (activeObservations.isPlaceholderData) {
- return null;
- }
-
const validObservations =
activeObservations.data?.observations?.filter(
(o) => o.id && o.traceId && o.startTime,
@@ -170,12 +170,7 @@ export function useEventsTableData({
? { truncated: false as const, ioCharLimit }
: {}),
};
- }, [
- activeObservations.data?.observations,
- activeObservations.isPlaceholderData,
- projectId,
- ioCharLimit,
- ]);
+ }, [activeObservations.data?.observations, projectId, ioCharLimit]);
// Fetch I/O data
const ioDataQuery = api.events.batchIO.useQuery(batchIOPayload!, {
@@ -184,8 +179,12 @@ export function useEventsTableData({
rowsEnabled && activeObservations.isSuccess && batchIOPayload !== null,
refetchOnWindowFocus: false,
staleTime: 0,
+ placeholderData: (prev) => prev,
});
+ // I/O lands one query behind the rows.
+ const isIoPending = usePendingRowIds(ioDataQuery);
+
// Extract error information for display (only from observations.all, not batchIO)
const error = activeObservations.error;
@@ -199,7 +198,10 @@ export function useEventsTableData({
// Memoize joined data to prevent infinite re-renders
// Handle loading, error, and success states
const joinedData = useMemo(() => {
- if (activeObservations.isLoading || activeObservations.isPlaceholderData) {
+ // Placeholder data is the previous key's rows: report them as loaded so a
+ // filter/page/sort change keeps them on screen. "loading" now means the
+ // table has nothing to show at all.
+ if (activeObservations.isPending) {
return { status: "loading" as const, rows: undefined };
}
@@ -217,8 +219,7 @@ export function useEventsTableData({
ioDataQuery.data,
);
}, [
- activeObservations.isLoading,
- activeObservations.isPlaceholderData,
+ activeObservations.isPending,
activeObservations.isError,
activeObservations.data?.observations,
ioDataQuery.data,
@@ -229,6 +230,7 @@ export function useEventsTableData({
const totalCountQuery = api.events.countAll.useQuery(getCountPayload, {
enabled: selectAll,
refetchOnWindowFocus: true,
+ placeholderData: (prev) => prev,
});
const totalCount = selectAll
@@ -296,7 +298,12 @@ export function useEventsTableData({
return {
observations: joinedData,
- dataUpdatedAt: activeObservations.dataUpdatedAt,
+ /**
+ * A fetch over the visible rows β€” drives the progress bar, not a skeleton.
+ * Deliberately excludes the select-all count query: it touches no row on
+ * screen, and `isTotalCountLoading` already covers its own UI.
+ */
+ isFetching: activeObservations.isFetching || ioDataQuery.isFetching,
totalCount,
uniqueTraceCount,
isTotalCountLoading,
@@ -304,7 +311,7 @@ export function useEventsTableData({
hasMore,
addToQueueMutation,
handleAddToAnnotationQueue,
- ioLoading: ioDataQuery.isLoading,
+ isIoPending,
error,
errorHttpStatus,
isSilencedError,
diff --git a/web/src/hooks/useAnimatedBusy.clienttest.ts b/web/src/hooks/useAnimatedBusy.clienttest.ts
new file mode 100644
index 0000000000..5972b15def
--- /dev/null
+++ b/web/src/hooks/useAnimatedBusy.clienttest.ts
@@ -0,0 +1,115 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, vi } from "vitest";
+
+import { useAnimatedBusy } from "./useAnimatedBusy";
+
+describe("useAnimatedBusy", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-11T12:00:00.000Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("holds a fast finish for a whole cycle, and a slow one to its next cycle", () => {
+ const { result, rerender } = renderHook(
+ ({ busy }: { busy: boolean }) => useAnimatedBusy(busy, 1000).active,
+ { initialProps: { busy: false } },
+ );
+
+ // 200ms of work still spins for the full 1000ms turn.
+ rerender({ busy: true });
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ rerender({ busy: false });
+ expect(result.current).toBe(true);
+
+ act(() => {
+ vi.advanceTimersByTime(799);
+ });
+ expect(result.current).toBe(true);
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(result.current).toBe(false);
+
+ // 1200ms of work rounds up to two turns rather than stopping mid-rotation.
+ rerender({ busy: true });
+ act(() => {
+ vi.advanceTimersByTime(1200);
+ });
+ rerender({ busy: false });
+ expect(result.current).toBe(true);
+
+ act(() => {
+ vi.advanceTimersByTime(800);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("stays on across the gap between a refresh's stages", () => {
+ const { result, rerender } = renderHook(
+ ({ busy }: { busy: boolean }) => useAnimatedBusy(busy, 1000, 400).active,
+ { initialProps: { busy: false } },
+ );
+
+ // Rows land, then their batched I/O starts a moment later: one refresh, so
+ // the flag must not drop in between (it would restart the animation).
+ rerender({ busy: true });
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ rerender({ busy: false });
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(result.current).toBe(true);
+
+ rerender({ busy: true });
+ act(() => {
+ vi.advanceTimersByTime(400);
+ });
+ rerender({ busy: false });
+ expect(result.current).toBe(true);
+
+ // Released a settle window later, rounded up to a whole cycle (900 + 400
+ // settle -> two cycles from the original start).
+ act(() => {
+ vi.advanceTimersByTime(1100);
+ });
+ expect(result.current).toBe(false);
+ });
+
+ it("counts one epoch per busy period, so the animation restarts only between refreshes", () => {
+ const { result, rerender } = renderHook(
+ ({ busy }: { busy: boolean }) => useAnimatedBusy(busy, 1000, 400),
+ { initialProps: { busy: false } },
+ );
+ expect(result.current.epoch).toBe(0);
+
+ // One refresh, two stages: same epoch throughout.
+ rerender({ busy: true });
+ const first = result.current.epoch;
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ rerender({ busy: false });
+ rerender({ busy: true });
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(result.current.epoch).toBe(first);
+
+ rerender({ busy: false });
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ expect(result.current.active).toBe(false);
+
+ rerender({ busy: true });
+ expect(result.current.epoch).toBe(first + 1);
+ });
+});
diff --git a/web/src/hooks/useAnimatedBusy.ts b/web/src/hooks/useAnimatedBusy.ts
new file mode 100644
index 0000000000..9844250e5e
--- /dev/null
+++ b/web/src/hooks/useAnimatedBusy.ts
@@ -0,0 +1,67 @@
+import { useEffect, useRef, useState } from "react";
+
+export type AnimatedBusy = {
+ active: boolean;
+ /**
+ * Increments once per busy period. Key an animated element on it so each
+ * period plays the animation from its start, without remounting (and
+ * restarting) it while the period is still running.
+ */
+ epoch: number;
+};
+
+/**
+ * Holds a short-lived busy flag on for whole animation cycles.
+ *
+ * Two problems it solves. A local refresh often resolves in ~200ms, which shows
+ * as a single frame of animation. And one refresh is usually several sequential
+ * queries β€” rows, then the batched I/O for those rows, then counts β€” so the raw
+ * flag drops between stages and the animation would restart mid-refresh. The
+ * flag is therefore released only after everything has been quiet for
+ * `settleMs`, rounded up to a whole cycle so it never stops mid-rotation.
+ */
+export function useAnimatedBusy(
+ busy: boolean,
+ cycleMs = 1000,
+ settleMs = 400,
+): AnimatedBusy {
+ const [state, setState] = useState<AnimatedBusy>({
+ active: busy,
+ epoch: 0,
+ });
+ const startedAt = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (busy) {
+ startedAt.current ??= Date.now();
+ setState((prev) =>
+ prev.active ? prev : { active: true, epoch: prev.epoch + 1 },
+ );
+ return;
+ }
+
+ if (startedAt.current === null) return;
+
+ const stop = () => {
+ startedAt.current = null;
+ setState((prev) => (prev.active ? { ...prev, active: false } : prev));
+ };
+
+ const settledAt = Date.now() + settleMs;
+ const cycles = Math.max(
+ 1,
+ Math.ceil((settledAt - startedAt.current) / cycleMs),
+ );
+ const remaining = startedAt.current + cycles * cycleMs - Date.now();
+
+ if (remaining <= 0) {
+ stop();
+ return;
+ }
+
+ const id = setTimeout(stop, remaining);
+ return () => clearTimeout(id);
+ }, [busy, cycleMs, settleMs]);
+
+ return state;
+}
diff --git a/web/src/hooks/useLiveTableDateRange.clienttest.ts b/web/src/hooks/useLiveTableDateRange.clienttest.ts
new file mode 100644
index 0000000000..ef6f999853
--- /dev/null
+++ b/web/src/hooks/useLiveTableDateRange.clienttest.ts
@@ -0,0 +1,108 @@
+import { renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, vi } from "vitest";
+
+import { useLiveTableDateRange } from "./useLiveTableDateRange";
+
+const START = new Date("2026-08-11T12:00:00.000Z");
+
+describe("useLiveTableDateRange", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(START);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("keeps one window (and therefore one query key) across refreshes of a relative range", () => {
+ const { result, rerender } = renderHook(
+ () => useLiveTableDateRange({ range: "last1Day" }).range,
+ );
+
+ const initial = result.current;
+ expect(initial?.from).toEqual(new Date("2026-08-10T12:00:00.000Z"));
+ // Open-ended at the top: rows arriving after the anchor still match, so the
+ // window never has to be re-resolved to pick them up.
+ expect(initial?.to).toBeUndefined();
+
+ // Two auto-refresh ticks later the window is byte-identical.
+ vi.setSystemTime(new Date(START.getTime() + 30_000));
+ rerender();
+ vi.setSystemTime(new Date(START.getTime() + 60_000));
+ rerender();
+
+ expect(result.current).toBe(initial);
+ });
+
+ it("re-anchors once the window has drifted past its budget", () => {
+ const { result, rerender } = renderHook(
+ () => useLiveTableDateRange({ range: "last1Day" }).range,
+ );
+ const initial = result.current;
+
+ // 10% of 24h = 2.4h budget: still the same window just before it.
+ vi.setSystemTime(new Date(START.getTime() + 2 * 60 * 60 * 1000));
+ rerender();
+ expect(result.current).toBe(initial);
+
+ vi.setSystemTime(new Date(START.getTime() + 3 * 60 * 60 * 1000));
+ rerender();
+ expect(result.current?.from).toEqual(new Date("2026-08-10T15:00:00.000Z"));
+ });
+
+ it("exposes the anchor as a closed upper bound for consumers that need one", () => {
+ const { result, rerender } = renderHook(
+ ({ range }: { range: string }) => useLiveTableDateRange({ range }),
+ { initialProps: { range: "last1Day" } },
+ );
+
+ // Charts pair `anchoredTo` with `range.from`, so the pair is always exactly
+ // the selected length β€” it can neither grow nor invert.
+ expect(result.current.anchoredTo).toEqual(START);
+ expect(
+ result.current.anchoredTo!.getTime() -
+ result.current.range!.from.getTime(),
+ ).toBe(24 * 60 * 60 * 1000);
+
+ vi.setSystemTime(new Date(START.getTime() + 10 * 60 * 1000));
+ rerender({ range: "last1Hour" });
+ expect(
+ result.current.anchoredTo!.getTime() -
+ result.current.range!.from.getTime(),
+ ).toBe(60 * 60 * 1000);
+ });
+
+ it("passes an absolute range through unchanged and never drifts it", () => {
+ const absolute = {
+ from: new Date("2026-01-01T00:00:00.000Z"),
+ to: new Date("2026-01-02T00:00:00.000Z"),
+ };
+ const { result, rerender } = renderHook(
+ () => useLiveTableDateRange(absolute).range,
+ );
+
+ expect(result.current).toEqual(absolute);
+ const initial = result.current;
+
+ vi.setSystemTime(new Date(START.getTime() + 30 * 24 * 60 * 60 * 1000));
+ rerender();
+ expect(result.current).toBe(initial);
+ });
+
+ it("re-anchors when the user picks another range, including an equal-by-value one", () => {
+ const { result, rerender } = renderHook(
+ ({ range }: { range: string }) => useLiveTableDateRange({ range }).range,
+ { initialProps: { range: "last1Day" } },
+ );
+ const initial = result.current;
+
+ // A fresh object for the same preset must not re-anchor (it would churn the
+ // query key on every parent render).
+ rerender({ range: "last1Day" });
+ expect(result.current).toBe(initial);
+
+ rerender({ range: "last1Hour" });
+ expect(result.current?.from).toEqual(new Date("2026-08-11T11:00:00.000Z"));
+ });
+});
diff --git a/web/src/hooks/useLiveTableDateRange.ts b/web/src/hooks/useLiveTableDateRange.ts
new file mode 100644
index 0000000000..279aec277b
--- /dev/null
+++ b/web/src/hooks/useLiveTableDateRange.ts
@@ -0,0 +1,107 @@
+import { useState } from "react";
+import {
+ type TableDateRange,
+ type TimeRange,
+ toAbsoluteTimeRange,
+} from "@/src/utils/date-range-utils";
+
+/**
+ * A relative window ("past 24h") re-resolved on every refresh tick minted a
+ * fresh absolute `from`/`to`, i.e. a new tRPC query key per tick β€” so every
+ * refresh was a cold load with no cached rows. This anchors the window instead:
+ *
+ * - relative ranges stay open-ended at the top (`to: undefined`), so rows that
+ * arrive after the anchor still match without re-resolving the window,
+ * - the anchor is only replaced when the user picks another range or when it has
+ * drifted past its budget, which keeps the query key β€” and therefore the rows
+ * on screen β€” stable across refreshes.
+ */
+const DRIFT_BUDGET_FRACTION = 0.1;
+const MIN_DRIFT_BUDGET_MS = 60_000;
+
+export type LiveTableDateRange = {
+ /** What the table queries: open-ended at the top for a relative range. */
+ range: TableDateRange | undefined;
+ /**
+ * The instant the window was anchored β€” its closed upper bound. Consumers that
+ * need a closed window (charts) pair this with `range.from`; the table's own
+ * filter deliberately leaves the top open so late-arriving rows still match.
+ */
+ anchoredTo: Date | undefined;
+};
+
+type Anchor = {
+ timeRange: TimeRange;
+ anchoredAt: number;
+ /** Only relative windows drift with wall-clock time. */
+ isRelative: boolean;
+ value: LiveTableDateRange;
+};
+
+const isSameTimeRange = (a: TimeRange, b: TimeRange): boolean => {
+ if ("range" in a || "range" in b) {
+ return "range" in a && "range" in b && a.range === b.range;
+ }
+ return (
+ a.from.getTime() === b.from.getTime() && a.to.getTime() === b.to.getTime()
+ );
+};
+
+const anchorTimeRange = (timeRange: TimeRange, now: number): Anchor => {
+ const isRelative = "range" in timeRange;
+ const absolute = toAbsoluteTimeRange(timeRange);
+
+ return {
+ timeRange,
+ anchoredAt: now,
+ isRelative,
+ value: {
+ range: absolute
+ ? { from: absolute.from, to: isRelative ? undefined : absolute.to }
+ : undefined,
+ anchoredTo: absolute
+ ? isRelative
+ ? new Date(now)
+ : absolute.to
+ : undefined,
+ },
+ };
+};
+
+/** How far the anchor may fall behind wall-clock time before it is replaced. */
+const driftBudgetMs = (anchor: Anchor): number => {
+ const windowMs = anchor.value.range
+ ? anchor.anchoredAt - anchor.value.range.from.getTime()
+ : 0;
+ return Math.max(windowMs * DRIFT_BUDGET_FRACTION, MIN_DRIFT_BUDGET_MS);
+};
+
+const isAnchorStale = (anchor: Anchor, now: number): boolean =>
+ anchor.isRelative &&
+ anchor.value.range !== undefined &&
+ now - anchor.anchoredAt > driftBudgetMs(anchor);
+
+/**
+ * Resolves a table's (possibly relative) time range into an absolute window
+ * whose identity is stable across refreshes, so refetching keeps the rows that
+ * are already on screen instead of cold-loading a new query key.
+ */
+export function useLiveTableDateRange(
+ timeRange: TimeRange,
+): LiveTableDateRange {
+ const [anchor, setAnchor] = useState<Anchor>(() =>
+ anchorTimeRange(timeRange, Date.now()),
+ );
+
+ const now = Date.now();
+ if (
+ !isSameTimeRange(anchor.timeRange, timeRange) ||
+ isAnchorStale(anchor, now)
+ ) {
+ const next = anchorTimeRange(timeRange, now);
+ setAnchor(next);
+ return next.value;
+ }
+
+ return anchor.value;
+}
diff --git a/web/src/styles/globals.css b/web/src/styles/globals.css
index 9d3bfd9b9d..59e8167477 100644
--- a/web/src/styles/globals.css
+++ b/web/src/styles/globals.css
@@ -173,6 +173,33 @@
--animate-accordion-down: accordion-down 0.2s ease-out;
--animate-accordion-up: accordion-up 0.2s ease-out;
--animate-appear: appear 0.2s ease-out forwards;
+ /* Cycle length comes from REFETCH_SWEEP_MS in components/table/data-table.tsx,
+ which sets --table-refetch-cycle on the element: the same number also
+ releases the busy flag on a whole sweep, so the two must not drift. */
+ --animate-table-refetch: table-refetch var(--table-refetch-cycle, 1.4s) linear
+ infinite;
+ --animate-table-refetch-in: table-refetch-fade-in 200ms ease-out;
+
+ /* Sweeps the highlight of the table's refetch bar across its track. It starts
+ and ends fully outside the (clipped) track, so the jump back to the start is
+ never visible β€” inside the track it reads as a blink every cycle. Linear,
+ because eased motion makes that wrap even more obvious. The highlight is a
+ third of the track wide, hence -100%/300% of its own width. */
+ @keyframes table-refetch {
+ from {
+ transform: translateX(-100%);
+ }
+
+ to {
+ transform: translateX(300%);
+ }
+ }
+
+ @keyframes table-refetch-fade-in {
+ from {
+ opacity: 0;
+ }
+ }
@keyframes rainbow {
0% {