Skip to content

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

fix(dashboards): resolve the v4 read path before widgets query, make the toggle reliable (#16901)

Nikita Kabardin8ab4604700dd
diff --git a/web/src/__tests__/detail-page-route-params.clienttest.tsx b/web/src/__tests__/detail-page-route-params.clienttest.tsx
index 14fb3093d0..8255890652 100644
--- a/web/src/__tests__/detail-page-route-params.clienttest.tsx
+++ b/web/src/__tests__/detail-page-route-params.clienttest.tsx
@@ -21,8 +21,8 @@ vi.mock("@/src/components/session", () => ({
),
}));
-vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
- useV4Beta: () => ({ isBetaEnabled: false }),
+vi.mock("@/src/features/events/hooks/useReadPath", () => ({
+ useReadPath: () => ({ isV4: false }),
}));
vi.mock(
diff --git a/web/src/__tests__/server/dashboard-execute-query-version.servertest.ts b/web/src/__tests__/server/dashboard-execute-query-version.servertest.ts
new file mode 100644
index 0000000000..0c5b4848f0
--- /dev/null
+++ b/web/src/__tests__/server/dashboard-execute-query-version.servertest.ts
@@ -0,0 +1,110 @@
+/**
+ * Contract tests for dashboard.executeQuery's `version` input:
+ * - `version` is required — there is no implicit v1 default a client can
+ * fall into while its session is still resolving.
+ * - Both versions serve regardless of the USER's read path: saved v1 widgets
+ * render for v4 users, and monitors previews / shared v2 widgets query v2
+ * for users whose own read path is still v3. Only a legacy deployment
+ * (events tables not written) rejects v2 — not covered here because the
+ * test env boots in dual mode.
+ */
+import { type QueryType } from "@langfuse/shared/query";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import type { Session } from "next-auth";
+
+describe("dashboard.executeQuery version contract", () => {
+ let projectId: string;
+ let orgId: string;
+
+ beforeAll(async () => {
+ const org = await createOrgProjectAndApiKey();
+ projectId = org.projectId;
+ orgId = org.orgId;
+ });
+
+ function makeCaller(options: { v4BetaEnabled: boolean }) {
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: "user-1",
+ canCreateOrganizations: true,
+ name: "Test User",
+ v4BetaEnabled: options.v4BetaEnabled,
+ organizations: [
+ {
+ id: orgId,
+ name: "Test Organization",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: false,
+ aiTelemetryEnabled: true,
+ projects: [
+ {
+ id: projectId,
+ role: "ADMIN",
+ retentionDays: 30,
+ deletedAt: null,
+ name: "Test Project",
+ hasTraces: true,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ templateFlag: true,
+ v4BetaToggleVisible: false,
+ observationEvals: false,
+ experimentsV4Enabled: false,
+ searchBar: false,
+ },
+ admin: false,
+ },
+ environment: {} as any,
+ };
+ const ctx = createInnerTRPCContext({ session, headers: {} });
+ return appRouter.createCaller({ ...ctx, prisma });
+ }
+
+ const query: QueryType = {
+ view: "traces",
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ orderBy: null,
+ };
+
+ it("rejects a missing version instead of defaulting to v1", async () => {
+ const caller = makeCaller({ v4BetaEnabled: true });
+ await expect(
+ caller.dashboard.executeQuery({ projectId, query } as any),
+ ).rejects.toThrow();
+ });
+
+ it("serves v1 and v2 to a v4 session (saved v1 widgets still render)", async () => {
+ const caller = makeCaller({ v4BetaEnabled: true });
+ await expect(
+ caller.dashboard.executeQuery({ projectId, query, version: "v1" }),
+ ).resolves.toBeDefined();
+ await expect(
+ caller.dashboard.executeQuery({ projectId, query, version: "v2" }),
+ ).resolves.toBeDefined();
+ });
+
+ it("serves v2 to a v3-read-path session (monitors previews, shared v2 widgets)", async () => {
+ const caller = makeCaller({ v4BetaEnabled: false });
+ await expect(
+ caller.dashboard.executeQuery({ projectId, query, version: "v2" }),
+ ).resolves.toBeDefined();
+ });
+});
diff --git a/web/src/__tests__/server/execute-query-stream.servertest.ts b/web/src/__tests__/server/execute-query-stream.servertest.ts
index 3d06d297ea..945b1d4a92 100644
--- a/web/src/__tests__/server/execute-query-stream.servertest.ts
+++ b/web/src/__tests__/server/execute-query-stream.servertest.ts
@@ -114,6 +114,8 @@ describe("execute-query-stream handler", () => {
function makeBody(queryOverrides?: Record<string, unknown>) {
return {
projectId,
+ // The suite's fixture data lives in the v3 traces table.
+ version: "v1" as const,
query: {
view: "traces" as const,
dimensions: [],
@@ -128,6 +130,14 @@ describe("execute-query-stream handler", () => {
};
}
+ it("should return 400 when version is missing (no implicit default)", async () => {
+ mockGetServerAuthSession.mockResolvedValue(makeSession());
+ const { version: _version, ...bodyWithoutVersion } = makeBody();
+ const { req, res } = createPostMocks(bodyWithoutVersion);
+ await handler(req, res);
+ expect(res._getStatusCode()).toBe(400);
+ });
+
it("should return 400 when v4 beta is disabled", async () => {
mockGetServerAuthSession.mockResolvedValue(
makeSession({ v4BetaEnabled: false }),
diff --git a/web/src/components/publish-object-switch.tsx b/web/src/components/publish-object-switch.tsx
index bb2c3c35ea..cd866be945 100644
--- a/web/src/components/publish-object-switch.tsx
+++ b/web/src/components/publish-object-switch.tsx
@@ -10,7 +10,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/src/components/ui/tooltip";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { env } from "@/src/env.mjs";
@@ -34,7 +34,7 @@ export const PublishTraceSwitch = (props: {
/** Hover tooltip for the icon button (suppressed while the popover is open). */
tooltip?: string;
}) => {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const capture = usePostHogClientCapture();
const hasAccess = useHasProjectAccess({
projectId: props.projectId,
@@ -54,7 +54,7 @@ export const PublishTraceSwitch = (props: {
};
const mut = api.traces.publish.useMutation({
onMutate: async (input) => {
- if (isBetaEnabled) {
+ if (isV4) {
await utils.events.byTraceId.cancel(eventsTraceQueryInput);
const previousEvents = utils.events.byTraceId.getData(
@@ -90,7 +90,7 @@ export const PublishTraceSwitch = (props: {
return { previousTrace };
},
onError: (err, _input, context) => {
- if (isBetaEnabled) {
+ if (isV4) {
utils.events.byTraceId.setData(
eventsTraceQueryInput,
context?.previousEvents,
@@ -104,7 +104,7 @@ export const PublishTraceSwitch = (props: {
trpcErrorToast(err);
},
onSuccess: async () => {
- if (!isBetaEnabled) {
+ if (!isV4) {
await utils.traces.all.invalidate();
}
},
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 13fc6e1bdc..014a3e19bb 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -66,7 +66,7 @@ import { TableSelectionManager } from "@/src/features/table/components/TableSele
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import { createIdTableColumn } from "@/src/components/design-system/table/columns/createIdTableColumn";
import { usePaginationState } from "@/src/hooks/usePaginationState";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import {
ScoreTag,
scoreLevelFromScore,
@@ -171,14 +171,14 @@ export default function ScoresTable({
() => new Set<string>(hiddenColumns),
[hiddenColumns],
);
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// In v4beta, scores must exclusively use events-backed endpoints (no traces-table route).
- const useEventsBackedScores = isBetaEnabled;
+ const useEventsBackedScores = isV4;
// Same derivation `WidgetForm.tsx`/`ChartScores` use (`activeVersion`/
// `metricsVersion`) — the chart/outlier strip must read the same version
// as the table's own data, or a non-beta project's trace/observation
// breakdown would run against the events-backed view and come back empty.
- const chartViewVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";
+ const chartViewVersion: ViewVersion = isV4 ? "v2" : "v1";
const utils = api.useUtils();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const [paginationState, setPaginationState] = usePaginationState(0, 50, {
@@ -240,7 +240,7 @@ export default function ScoresTable({
// same guard `traces.tsx`/`EventsTable.tsx` already have.
queryParams: ["observation", "display", "timestamp", "traceId"],
tableName: scoresFilterConfig.tableName,
- isV4: isBetaEnabled,
+ isV4,
extractParamsValuesFromRow: (
row: ScoresTableRow,
): Record<string, string> =>
@@ -668,7 +668,7 @@ export default function ScoresTable({
defaultHidden: true,
loadingCell: <Skeleton className="h-4 w-1/2" />,
cell: ({ row }) => {
- if (isBetaEnabled && !scoreMetrics.data) {
+ if (isV4 && !scoreMetrics.data) {
return <Skeleton className="h-4 w-1/2" />;
}
const traceTags: string[] | undefined = row.getValue("traceTags");
@@ -721,7 +721,7 @@ export default function ScoresTable({
defaultHidden: true,
size: 150,
getCell: (value) => {
- if (isBetaEnabled && !scoreMetrics.data) return { type: "loading" };
+ if (isV4 && !scoreMetrics.data) return { type: "loading" };
if (!value) return undefined;
const filter = encodeURIComponent(
@@ -849,7 +849,7 @@ export default function ScoresTable({
defaultHidden: true,
size: 100,
getCell: (value) => {
- if (isBetaEnabled && !scoreMetrics.data) return { type: "loading" };
+ if (isV4 && !scoreMetrics.data) return { type: "loading" };
if (typeof value !== "string") return undefined;
return {
@@ -881,9 +881,9 @@ export default function ScoresTable({
}),
createLinkTableColumn<ScoresTableRow>({
accessorKey: "jobConfigurationId",
- header: isBetaEnabled ? "Evaluator" : "Eval Configuration ID",
+ header: isV4 ? "Evaluator" : "Eval Configuration ID",
headerTooltip: {
- description: isBetaEnabled
+ description: isV4
? "The evaluator associated with the score."
: "The Job Configuration ID associated with the score.",
href: "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge",
@@ -893,7 +893,7 @@ export default function ScoresTable({
defaultHidden: true,
size: 150,
getCell: (_, { row }) => {
- if (isBetaEnabled) {
+ if (isV4) {
const value = row.original.evaluatorId;
if (typeof value !== "string") return undefined;
@@ -992,7 +992,7 @@ export default function ScoresTable({
// Merge v4 metrics into table rows
const enrichedScores = useMemo(() => {
- if (!isBetaEnabled) {
+ if (!isV4) {
return scoresV3.data?.scores.map(convertToTableRow);
}
@@ -1038,7 +1038,7 @@ export default function ScoresTable({
} satisfies ScoresTableRow;
});
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [scores.data, scoreMetrics.data, isBetaEnabled]);
+ }, [scores.data, scoreMetrics.data, isV4]);
const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({
tableName: TableViewPresetTableName.Scores,
@@ -1236,7 +1236,7 @@ export default function ScoresTable({
expandPeek={expandScorePeek}
itemType="TRACE"
tableName={scoresFilterConfig.tableName}
- isV4={isBetaEnabled}
+ isV4={isV4}
projectId={projectId}
/>
)}
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index fcbb948273..6fb91c42fb 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -91,7 +91,7 @@ export type SessionTableProps = {
projectId: string;
userId?: string;
omittedFilter?: SessionOmittableFilterColumn[];
- isBetaEnabled?: boolean;
+ isV4?: boolean;
/**
* When true, render the time-range picker and auto-refresh button in the
* page header (next to the title) via the header controls slot, instead of
@@ -105,12 +105,12 @@ export default function SessionsTable({
projectId,
userId,
omittedFilter = [],
- isBetaEnabled = false,
+ isV4 = false,
showControlsInPageHeader = false,
}: SessionTableProps) {
const sessionsFilterConfig = useMemo(
- () => getSessionFilterConfig(omittedFilter, isBetaEnabled),
- [isBetaEnabled, omittedFilter],
+ () => getSessionFilterConfig(omittedFilter, isV4),
+ [isV4, omittedFilter],
);
const { setDetailPageList } = useDetailPageLists();
const { timeRange, setTimeRange } = useTableDateRange(projectId);
@@ -199,7 +199,7 @@ export default function SessionsTable({
: undefined,
},
{
- enabled: !isBetaEnabled,
+ enabled: !isV4,
trpc: {
context: {
skipBatch: true,
@@ -217,7 +217,7 @@ export default function SessionsTable({
: undefined,
},
{
- enabled: isBetaEnabled,
+ enabled: isV4,
trpc: {
context: {
skipBatch: true,
@@ -226,7 +226,7 @@ export default function SessionsTable({
},
);
- const filterOptions = isBetaEnabled ? filterOptionsV4 : filterOptionsV3;
+ const filterOptions = isV4 ? filterOptionsV4 : filterOptionsV3;
const newFilterOptions = useMemo(() => {
const scoreCategories =
@@ -277,9 +277,9 @@ export default function SessionsTable({
),
// Sidebar-only implicit environment defaults
implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
- isV4: isBetaEnabled,
+ isV4,
}),
- [isBetaEnabled, isSidebarFilterLoading, projectId, userId],
+ [isV4, isSidebarFilterLoading, projectId, userId],
);
const queryFilter = useSidebarFilterState(
@@ -305,7 +305,7 @@ export default function SessionsTable({
// Generally available on the v4 sessions table. Still off on the user-detail
// mount, which is page-scoped by a userId filter the bar must not fight (the
// same embedded opt-out EventsTable applies).
- const sessionsSearchBarEnabled = isBetaEnabled && !userId;
+ const sessionsSearchBarEnabled = isV4 && !userId;
const observedOptions = useMemo(
() => toObservedOptions(newFilterOptions, isSidebarFilterLoading),
[newFilterOptions, isSidebarFilterLoading],
@@ -356,29 +356,27 @@ export default function SessionsTable({
};
const sessionsV3 = api.sessions.all.useQuery(payloadGetAll, {
- enabled: !isBetaEnabled,
+ enabled: !isV4,
refetchOnWindowFocus: true,
});
const sessionsV4 = api.sessions.allFromEvents.useQuery(payloadGetAll, {
- enabled: isBetaEnabled,
+ enabled: isV4,
refetchOnWindowFocus: true,
});
- const sessions = isBetaEnabled ? sessionsV4 : sessionsV3;
+ const sessions = isV4 ? sessionsV4 : sessionsV3;
const sessionCountQueryV3 = api.sessions.countAll.useQuery(payloadCount, {
- enabled: !isBetaEnabled,
+ enabled: !isV4,
refetchOnWindowFocus: true,
});
const sessionCountQueryV4 = api.sessions.countAllFromEvents.useQuery(
payloadCount,
{
- enabled: isBetaEnabled,
+ enabled: isV4,
refetchOnWindowFocus: true,
},
);
- const sessionCountQuery = isBetaEnabled
- ? sessionCountQueryV4
- : sessionCountQueryV3;
+ const sessionCountQuery = isV4 ? sessionCountQueryV4 : sessionCountQueryV3;
const addToQueueMutation = api.annotationQueueItems.createMany.useMutation({
onSuccess: (data) => {
@@ -407,7 +405,7 @@ export default function SessionsTable({
sessionIds: sessionsV3.data?.sessions.map((s) => s.id) ?? [],
},
{
- enabled: sessionsV3.data !== undefined && !isBetaEnabled,
+ enabled: sessionsV3.data !== undefined && !isV4,
refetchOnWindowFocus: true,
},
);
@@ -419,12 +417,12 @@ export default function SessionsTable({
queryFromTimestamp: dateRange?.from ?? null,
},
{
- enabled: sessionsV4.data !== undefined && isBetaEnabled,
+ enabled: sessionsV4.data !== undefined && isV4,
refetchOnWindowFocus: true,
},
);
- const sessionMetrics = isBetaEnabled ? sessionMetricsV4 : sessionMetricsV3;
+ const sessionMetrics = isV4 ? sessionMetricsV4 : sessionMetricsV3;
type SessionCoreOutput = RouterOutput["sessions"]["all"]["sessions"][number];
type SessionMetricOutput = RouterOutput["sessions"]["metrics"][number];
diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
index 165f21c40a..91ae89eaa9 100644
--- a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
@@ -16,7 +16,7 @@ import { Badge } from "@/src/components/ui/badge";
import { Separator } from "@/src/components/ui/separator";
import Link from "next/link";
import { Card } from "@/src/components/ui/card";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { api } from "@/src/utils/api";
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
import { CommentDrawerController } from "@/src/features/comments/CommentDrawerController";
@@ -45,14 +45,14 @@ export const SessionAnnotationProcessor: React.FC<
SessionAnnotationProcessorProps
> = ({ item, data, configs, projectId }) => {
const [visibleTraces, setVisibleTraces] = useState(PAGE_SIZE);
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// Fetch traces separately when v4 beta is enabled (events table path)
// The byIdWithScoresFromEvents endpoint doesn't include traces array
const tracesFromEventsQuery = api.sessions.tracesFromEvents.useQuery(
{ projectId, sessionId: item.objectId },
{
- enabled: isBetaEnabled,
+ enabled: isV4,
retry(failureCount, error) {
if (
error.data?.code === "UNAUTHORIZED" ||
@@ -70,7 +70,7 @@ export const SessionAnnotationProcessor: React.FC<
projectId,
sessionId: item.objectId,
},
- { enabled: isBetaEnabled },
+ { enabled: isV4 },
);
const sessionCommentCounts = api.comments.getCountByObjectId.useQuery({
@@ -83,20 +83,20 @@ export const SessionAnnotationProcessor: React.FC<
// - v4 beta OFF: traces come from data.traces (byIdWithScores endpoint)
// - v4 beta ON: traces come from separate tracesFromEvents query
const traces = useMemo(() => {
- if (isBetaEnabled) {
+ if (isV4) {
return tracesFromEventsQuery.data ?? [];
}
return data?.traces ?? [];
- }, [isBetaEnabled, tracesFromEventsQuery.data, data?.traces]);
+ }, [isV4, tracesFromEventsQuery.data, data?.traces]);
// For the "Total traces" badge, show countTraces from session metadata when available (v4),
// or fall back to loaded traces length
const totalTracesForBadge = useMemo(() => {
- if (isBetaEnabled) {
+ if (isV4) {
return data?.countTraces ?? traces.length;
}
return traces.length;
- }, [isBetaEnabled, data?.countTraces, traces.length]);
+ }, [isV4, data?.countTraces, traces.length]);
// Stable callback to avoid creating new function reference on every render (defeats React.memo)
const openPeek = useCallback(
@@ -192,7 +192,7 @@ export const SessionAnnotationProcessor: React.FC<
<div className="flex-1 overflow-y-auto">
<div className="p-4">
{/* Loading state for v4 beta traces */}
- {isBetaEnabled && tracesFromEventsQuery.isLoading && (
+ {isV4 && tracesFromEventsQuery.isLoading && (
<div className="space-y-4">
{Array.from({ length: 3 }).map((_, i) => (
<Card
@@ -208,13 +208,13 @@ export const SessionAnnotationProcessor: React.FC<
</div>
)}
{/* Error state for v4 beta traces */}
- {isBetaEnabled && tracesFromEventsQuery.isError && (
+ {isV4 && tracesFromEventsQuery.isError && (
<div className="text-destructive p-2 text-sm">
Failed to load traces for this session.
</div>
)}
{/* Trace list - v4 path uses LazyTraceEventsRow for deferred loading */}
- {isBetaEnabled &&
+ {isV4 &&
tracesFromEventsQuery.isSuccess &&
traces
.slice(0, visibleTraces)
@@ -234,7 +234,7 @@ export const SessionAnnotationProcessor: React.FC<
/>
))}
{/* Trace list - v3 path uses SessionIO */}
- {!isBetaEnabled &&
+ {!isV4 &&
traces.slice(0, visibleTraces).map((trace: any) => (
<Card
className="border-border hover:border-ring group mb-2 grid gap-2 p-2 shadow-none"
@@ -260,7 +260,7 @@ export const SessionAnnotationProcessor: React.FC<
/>
</Card>
))}
- {(!isBetaEnabled || tracesFromEventsQuery.isSuccess) &&
+ {(!isV4 || tracesFromEventsQuery.isSuccess) &&
traces.length > visibleTraces && (
<div className="flex justify-center py-4">
<Button
diff --git a/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.ts b/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.ts
index a9b5e1e477..cc87f0a838 100644
--- a/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.ts
+++ b/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.ts
@@ -3,7 +3,7 @@ import {
type AnnotationQueueItem,
AnnotationQueueObjectType,
} from "@langfuse/shared";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";
export interface ObjectDataHook<TData> {
@@ -17,7 +17,7 @@ export const useAnnotationObjectData = (
item: (AnnotationQueueItem & { parentTraceId?: string | null }) | null,
projectId: string,
): ObjectDataHook<any> => {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const traceId = item?.parentTraceId ?? item?.objectId;
const isTraceOrObservation =
@@ -29,7 +29,7 @@ export const useAnnotationObjectData = (
const traceQuery = api.traces.byIdWithObservationsAndScores.useQuery(
{ traceId: traceId as string, projectId },
{
- enabled: isTraceOrObservation && !isBetaEnabled,
+ enabled: isTraceOrObservation && !isV4,
retry(failureCount, error) {
if (
error.data?.code === "UNAUTHORIZED" ||
@@ -44,7 +44,7 @@ export const useAnnotationObjectData = (
const eventsData = useEventsTraceData({
projectId,
traceId: traceId ?? "",
- enabled: isTraceOrObservation && isBetaEnabled,
+ enabled: isTraceOrObservation && isV4,
});
const isSession =
@@ -57,7 +57,7 @@ export const useAnnotationObjectData = (
projectId,
},
{
- enabled: isSession && !isBetaEnabled,
+ enabled: isSession && !isV4,
retry(failureCount, error) {
if (
error.data?.code === "UNAUTHORIZED" ||
@@ -76,7 +76,7 @@ export const useAnnotationObjectData = (
projectId,
},
{
- enabled: isSession && isBetaEnabled,
+ enabled: isSession && isV4,
retry(failureCount, error) {
if (
error.data?.code === "UNAUTHORIZED" ||
@@ -99,7 +99,7 @@ export const useAnnotationObjectData = (
switch (item.objectType) {
case AnnotationQueueObjectType.TRACE:
case AnnotationQueueObjectType.OBSERVATION:
- if (isBetaEnabled) {
+ if (isV4) {
return {
data: eventsData.data,
isLoading: eventsData.isLoading,
@@ -114,7 +114,7 @@ export const useAnnotationObjectData = (
errorCode: traceQuery.error?.data?.code,
};
case AnnotationQueueObjectType.SESSION:
- if (isBetaEnabled) {
+ if (isV4) {
return {
data: sessionEventsQuery.data,
isLoading: sessionEventsQuery.isLoading,
diff --git a/web/src/features/chart-view/EventsChartView.tsx b/web/src/features/chart-view/EventsChartView.tsx
index 5c6a1979a8..9f4fa43f7a 100644
--- a/web/src/features/chart-view/EventsChartView.tsx
+++ b/web/src/features/chart-view/EventsChartView.tsx
@@ -46,7 +46,7 @@ export function EventsChartView({
{ projectId, query, version: "v2" },
{
enabled: validRange,
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
trpc: { context: { skipBatch: true } },
},
);
diff --git a/web/src/features/command-k-menu/CommandMenu.tsx b/web/src/features/command-k-menu/CommandMenu.tsx
index 99456bd198..13018d5eb6 100644
--- a/web/src/features/command-k-menu/CommandMenu.tsx
+++ b/web/src/features/command-k-menu/CommandMenu.tsx
@@ -20,7 +20,7 @@ import { useAccountSettingsPages } from "@/src/pages/account/settings";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
import { api } from "@/src/utils/api";
import { type NavigationItem } from "@/src/components/layouts/utilities/routes";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
type IdNavigationItem = {
type: "trace_id" | "observation_id";
@@ -338,13 +338,9 @@ function CommandMenuComponent({
const capture = usePostHogClientCapture();
const router = useRouter();
const { project } = useQueryProjectOrOrganization();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const [search, setSearch] = useState("");
- const idNavigationItem = getIdNavigationItem(
- search,
- project?.id,
- isBetaEnabled,
- );
+ const idNavigationItem = getIdNavigationItem(search, project?.id, isV4);
const debouncedSearchChange = useDebounce(
(value: string) => {
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsx
index dbc69051ce..f3aae23aed 100644
--- a/web/src/features/dashboard/components/ChartScores.tsx
+++ b/web/src/features/dashboard/components/ChartScores.tsx
@@ -36,7 +36,7 @@ export function ChartScores(props: {
toTimestamp: Date;
projectId: string;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
}) {
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index 9dd59fb810..4dc2dd9d45 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -42,7 +42,7 @@ export const GenerationLatencyChart = ({
fromTimestamp: Date;
toTimestamp: Date;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
}) => {
diff --git a/web/src/features/dashboard/components/LatencyTables.tsx b/web/src/features/dashboard/components/LatencyTables.tsx
index e92f3ab6b8..bf0972968d 100644
--- a/web/src/features/dashboard/components/LatencyTables.tsx
+++ b/web/src/features/dashboard/components/LatencyTables.tsx
@@ -176,7 +176,7 @@ export const LatencyTable = ({
fromTimestamp: Date;
toTimestamp: Date;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
}) => {
const { title, nameHeader, buildQuery } = LATENCY_TABLE_KINDS[kind];
diff --git a/web/src/features/dashboard/components/ModelCostTable.tsx b/web/src/features/dashboard/components/ModelCostTable.tsx
index 0144cd72c3..e7a5b3ad0a 100644
--- a/web/src/features/dashboard/components/ModelCostTable.tsx
+++ b/web/src/features/dashboard/components/ModelCostTable.tsx
@@ -29,7 +29,7 @@ export const ModelCostTable = ({
fromTimestamp: Date;
toTimestamp: Date;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
}) => {
const modelCostQuery: QueryType = {
diff --git a/web/src/features/dashboard/components/ModelSelector.tsx b/web/src/features/dashboard/components/ModelSelector.tsx
index a5b3c2240f..4fb79eb9e1 100644
--- a/web/src/features/dashboard/components/ModelSelector.tsx
+++ b/web/src/features/dashboard/components/ModelSelector.tsx
@@ -108,7 +108,7 @@ export const useModelSelection = (
globalFilterState: FilterState,
fromTimestamp: Date,
toTimestamp: Date,
- metricsVersion?: ViewVersion,
+ metricsVersion: ViewVersion,
options?: {
enabled?: boolean;
queryId: string;
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 2817270999..4cfb400ecb 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -47,7 +47,7 @@ export const ModelUsageChart = ({
toTimestamp: Date;
userAndEnvFilterState: FilterState;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
}) => {
diff --git a/web/src/features/dashboard/components/ScoresTable.tsx b/web/src/features/dashboard/components/ScoresTable.tsx
index 3e2f7201ad..e85e573e7c 100644
--- a/web/src/features/dashboard/components/ScoresTable.tsx
+++ b/web/src/features/dashboard/components/ScoresTable.tsx
@@ -56,7 +56,7 @@ export const ScoresTable = ({
projectId: string;
globalFilterState: FilterState;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
}) => {
const localFilters = createTracesTimeFilter(
globalFilterState,
@@ -88,7 +88,7 @@ export const ScoresTable = ({
],
orderBy: [{ column: "scoreId", direction: "DESC", agg: "COUNT" }],
queryName: "score-aggregate",
- version: metricsVersion ?? "v1",
+ version: metricsVersion,
},
{
trpc: {
@@ -133,7 +133,7 @@ export const ScoresTable = ({
],
orderBy: [{ column: "scoreId", direction: "DESC", agg: "COUNT" }],
queryName: "score-aggregate",
- version: metricsVersion ?? "v1",
+ version: metricsVersion,
},
{
trpc: {
diff --git a/web/src/features/dashboard/components/TracesBarListChart.tsx b/web/src/features/dashboard/components/TracesBarListChart.tsx
index 4101925f1f..e64f01ca4a 100644
--- a/web/src/features/dashboard/components/TracesBarListChart.tsx
+++ b/web/src/features/dashboard/components/TracesBarListChart.tsx
@@ -31,7 +31,7 @@ export const TracesBarListChart = ({
fromTimestamp: Date;
toTimestamp: Date;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
}) => {
const isV2 = metricsVersion === "v2";
diff --git a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
index 3bfd1f4b1e..6b69feb4a5 100644
--- a/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/TracesTimeSeriesChart.tsx
@@ -35,7 +35,7 @@ export const TracesAndObservationsTimeSeriesChart = ({
toTimestamp: Date;
agg: DashboardDateRangeAggregationOption;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
syncId?: string;
}) => {
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index 4fa99685f8..caf9621873 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -37,7 +37,7 @@ export const UserChart = ({
fromTimestamp: Date;
toTimestamp: Date;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
}) => {
const userCostQuery: QueryType = {
diff --git a/web/src/features/dashboard/components/hooks.ts b/web/src/features/dashboard/components/hooks.ts
index c61fe47535..98a9ab9364 100644
--- a/web/src/features/dashboard/components/hooks.ts
+++ b/web/src/features/dashboard/components/hooks.ts
@@ -20,7 +20,7 @@ export const useAllModels = (
globalFilterState: FilterState,
fromTimestamp: Date,
toTimestamp: Date,
- metricsVersion?: ViewVersion,
+ metricsVersion: ViewVersion,
options?: UseAllModelsOptions,
) => {
const allModels = useScheduledDashboardExecuteQuery(
diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
index 12daf5c90f..44695e3245 100644
--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
@@ -23,7 +23,7 @@ export function CategoricalScoreChart(props: {
fromTimestamp: Date;
toTimestamp: Date;
agg?: DashboardDateRangeAggregationOption;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
}) {
const scoresQuery: QueryType = {
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
index bbb142b823..7b901ccaa8 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
@@ -17,9 +17,9 @@ export function NumericScoreHistogram(props: {
source: ScoreSourceType;
dataType: Extract<ScoreDataTypeType, "NUMERIC" | "BOOLEAN">;
globalFilterState: FilterState;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
}) {
- const version = props.metricsVersion ?? "v1";
+ const version = props.metricsVersion;
const histogram = api.dashboard.scoreHistogram.useQuery(
{
projectId: props.projectId,
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index 34f57f3064..cbc897a5d0 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -30,7 +30,7 @@ export function NumericScoreTimeSeriesChart(props: {
globalFilterState: FilterState;
fromTimestamp: Date;
toTimestamp: Date;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
/** Shared hover-sync group so this chart joins the dashboard crosshair. */
syncId?: string;
diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
index 48028693a1..c4823aabce 100644
--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
@@ -31,7 +31,7 @@ export function ScoreAnalytics(props: {
toTimestamp: Date;
projectId: string;
isLoading?: boolean;
- metricsVersion?: ViewVersion;
+ metricsVersion: ViewVersion;
schedulerId?: string;
/** Shared hover-sync group so the per-score line charts join the dashboard crosshair. */
syncId?: string;
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index b35f034a22..088543aeb1 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -10,6 +10,7 @@ import {
} from "@/src/server/api/services/sqlInterface";
import { createHistogramData } from "@/src/features/dashboard/lib/score-analytics-utils";
import { TRPCError } from "@trpc/server";
+import { env } from "@/src/env.mjs";
import {
getScoreAggregate,
getNumericScoreHistogram,
@@ -447,10 +448,27 @@ export const dashboardRouter = createTRPCRouter({
z.object({
projectId: z.string(),
query: customQuery,
- version: viewVersions.optional().default("v1"),
+ // Required on purpose: a client must decide the read path explicitly.
+ // An implicit v1 default let unresolved-session clients silently fire
+ // legacy-table queries for v4 users.
+ version: viewVersions,
}),
)
.query(async ({ input }) => {
+ // Deployment-level guard, not a per-user one: v2 reads the events
+ // views, which exist whenever the deployment writes them. Monitors
+ // previews and shared v2-widgets legitimately query v2 for users whose
+ // own read path is still v3; only a legacy deployment has nothing for
+ // v2 to read. v1 stays open (saved v1 widgets render for v4 users).
+ if (
+ input.version === "v2" &&
+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "legacy"
+ ) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "v2 queries are not available on this deployment",
+ });
+ }
try {
const validation = validateQuery(input.query, input.version);
if (!validation.valid) {
diff --git a/web/src/features/dashboard/utils/dashboard-import-export.clienttest.ts b/web/src/features/dashboard/utils/dashboard-import-export.clienttest.ts
index bc9b23fb1c..b71eec05db 100644
--- a/web/src/features/dashboard/utils/dashboard-import-export.clienttest.ts
+++ b/web/src/features/dashboard/utils/dashboard-import-export.clienttest.ts
@@ -95,17 +95,17 @@ describe("parseDashboardImport", () => {
it("ignores payloads without the dashboard envelope", () => {
expect(
parseDashboardImport(JSON.stringify({ widgets: [] }), {
- isBetaEnabled: false,
+ isV4: false,
}),
).toEqual({ status: "not-dashboard" });
- expect(
- parseDashboardImport("plain text", { isBetaEnabled: false }),
- ).toEqual({ status: "not-dashboard" });
+ expect(parseDashboardImport("plain text", { isV4: false })).toEqual({
+ status: "not-dashboard",
+ });
});
it("round-trips an exported dashboard", () => {
const result = parseDashboardImport(JSON.stringify(validExport()), {
- isBetaEnabled: false,
+ isV4: false,
});
expect(result.status).toBe("dashboard");
@@ -133,7 +133,7 @@ describe("parseDashboardImport", () => {
...validExport(),
version: DASHBOARD_FILE_FORMAT_VERSION + 1,
}),
- { isBetaEnabled: false },
+ { isV4: false },
);
expect(result.status).toBe("invalid");
@@ -152,7 +152,7 @@ describe("parseDashboardImport", () => {
});
const result = parseDashboardImport(JSON.stringify(payload), {
- isBetaEnabled: false,
+ isV4: false,
});
expect(result.status).toBe("dashboard");
@@ -168,7 +168,7 @@ describe("parseDashboardImport", () => {
widgets[0].widget = { ...widgets[0].widget, chartConfig: { type: "PIE" } };
const result = parseDashboardImport(JSON.stringify(payload), {
- isBetaEnabled: false,
+ isV4: false,
});
expect(result.status).toBe("invalid");
@@ -185,7 +185,7 @@ describe("parseDashboardImport", () => {
name: "Empty",
widgets: [],
}),
- { isBetaEnabled: false },
+ { isV4: false },
);
expect(result.status).toBe("invalid");
@@ -205,7 +205,7 @@ describe("parseDashboardImport", () => {
},
],
}),
- { isBetaEnabled: false },
+ { isV4: false },
);
expect(result.status).toBe("invalid");
@@ -255,19 +255,19 @@ describe("isPasteablePlacementPayload", () => {
isPasteablePlacementPayload(
JSON.stringify(buildWidgetExport(baseWidget)),
{
- isBetaEnabled: false,
+ isV4: false,
},
),
).toBe(true);
expect(
isPasteablePlacementPayload(
JSON.stringify(buildPresetExport(HOME_DASHBOARD_PRESET_IDS[0])),
- { isBetaEnabled: false },
+ { isV4: false },
),
).toBe(true);
expect(
isPasteablePlacementPayload('{"hello": "world"}', {
- isBetaEnabled: false,
+ isV4: false,
}),
).toBe(false);
});
diff --git a/web/src/features/dashboard/utils/dashboard-import-export.ts b/web/src/features/dashboard/utils/dashboard-import-export.ts
index a7ce0f90b6..d322120663 100644
--- a/web/src/features/dashboard/utils/dashboard-import-export.ts
+++ b/web/src/features/dashboard/utils/dashboard-import-export.ts
@@ -100,7 +100,7 @@ export function parsePastedPreset(text: string): PastedPresetParseResult {
*/
export function isPasteablePlacementPayload(
text: string,
- params: { isBetaEnabled: boolean },
+ params: { isV4: boolean },
): boolean {
if (parsePastedWidget(text, params).status === "widget") return true;
return parsePastedPreset(text).status === "preset";
@@ -237,7 +237,7 @@ export type DashboardImportParseResult =
*/
export function parseDashboardImport(
text: string,
- params: { isBetaEnabled: boolean },
+ params: { isV4: boolean },
): DashboardImportParseResult {
let parsedJson: unknown;
try {
@@ -301,7 +301,7 @@ export function parseDashboardImport(
try {
const result = parseImportedWidgetJson({
parsedJson: placement.widget,
- isBetaEnabled: params.isBetaEnabled,
+ isV4: params.isV4,
});
removedFilters = removedFilters || result.removedFilters;
placements.push({ type: "widget", widget: result.widget, ...position });
diff --git a/web/src/features/evals/components/code-eval-test-run-card.tsx b/web/src/features/evals/components/code-eval-test-run-card.tsx
index d20faecc76..6e9efae3ed 100644
--- a/web/src/features/evals/components/code-eval-test-run-card.tsx
+++ b/web/src/features/evals/components/code-eval-test-run-card.tsx
@@ -11,7 +11,7 @@ import {
usePreviewData,
} from "@/src/features/evals/hooks/usePreviewData";
import { useFirstEvalPreviewPointer } from "@/src/features/evals/hooks/useEvalPreviewNavigation";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { detailPageListKeys } from "@/src/features/navigate-detail-pages/context";
import { api, type RouterOutputs } from "@/src/utils/api";
import {
@@ -66,12 +66,12 @@ export function CodeEvalTestRunCard({
disabled?: boolean;
enableExecutionTracePeek?: boolean;
}) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const isSupportedTarget = isCodeEvalTestTarget(target);
const canPreview = isSupportedTarget && !disabled;
const previewPointer = useFirstEvalPreviewPointer({
target,
- useEventsTable: isBetaEnabled,
+ useEventsTable: isV4,
});
const peekNavigationProps = usePeekNavigation({
// traceId: not written here, but cleared (and preferred by the trace
@@ -79,7 +79,7 @@ export function CodeEvalTestRunCard({
// (LFE-11041).
queryParams: ["observation", "display", "timestamp", "traceId"],
tableName: "evalTemplates",
- isV4: isBetaEnabled,
+ isV4,
expandConfig: {
basePath: `/project/${projectId}/traces`,
},
@@ -164,7 +164,7 @@ export function CodeEvalTestRunCard({
observationId,
traceId,
startTime: timestamp,
- shouldReadFromObservationsTable: !isBetaEnabled,
+ shouldReadFromObservationsTable: !isV4,
});
}}
>
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index eafa1445d5..67a5450dbc 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -106,7 +106,7 @@ import {
} from "@/src/features/evals/utils/evaluator-constants";
import { useEvalConfigFilterOptions } from "@/src/features/evals/hooks/useEvalConfigFilterOptions";
import { VariableMappingCard } from "@/src/features/evals/components/variable-mapping-card";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";
import {
isCodeEvalTemplate,
@@ -189,7 +189,7 @@ const ObservationsPreview = memo(
isNewCompatible: boolean;
compatibilityCheckWasPerformed: boolean;
}) => {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const dateRange = useMemo(() => {
return {
@@ -241,7 +241,7 @@ const ObservationsPreview = memo(
) : (
// Keep the evaluator preview isolated from the parent route's table state.
<PeekTableStateProvider>
- {isBetaEnabled ? (
+ {isV4 ? (
<EventsTable
projectId={projectId}
hideControls
@@ -351,7 +351,7 @@ export const InnerEvaluatorForm = (props: {
const capture = usePostHogClientCapture();
const router = useRouter();
const [showTraceConfirmDialog, setShowTraceConfirmDialog] = useState(false);
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
const isCodeEvalConfig =
isCodeEvalEnabled && isCodeEvalTemplate(props.evalTemplate);
@@ -381,7 +381,7 @@ export const InnerEvaluatorForm = (props: {
datasetFilterOptions,
} = useEvalConfigFilterOptions({
projectId: props.projectId,
- useEventsTable: isBetaEnabled,
+ useEventsTable: isV4,
includeLegacyTraceOptions: showLegacyTargetOptions,
});
@@ -560,7 +560,7 @@ export const InnerEvaluatorForm = (props: {
const watchedScoreName = form.watch("scoreName");
const watchedFilter = form.watch("filter") ?? EMPTY_FILTER_STATE;
const shouldShowExperimentEventsPreview =
- isExperimentTarget(watchedTarget) && isBetaEnabled;
+ isExperimentTarget(watchedTarget) && isV4;
const shouldShowEventsPreview =
isEventTarget(watchedTarget) || shouldShowExperimentEventsPreview;
const previewTableVisible = !props.disabled && !props.hidePreviewTable;
@@ -810,12 +810,12 @@ export const InnerEvaluatorForm = (props: {
isCodeEvalConfig &&
!props.disabled &&
(isEventTarget(watchedTarget) ||
- (isExperimentTarget(watchedTarget) && isBetaEnabled));
+ (isExperimentTarget(watchedTarget) && isV4));
const shouldShowCodeEvalSourceLinkInSettingsCard =
isCodeEvalConfig &&
!props.disabled &&
isExperimentTarget(watchedTarget) &&
- !isBetaEnabled;
+ !isV4;
const formBody = (
<div
@@ -1269,7 +1269,7 @@ export const InnerEvaluatorForm = (props: {
is not the v4 user's experience — never show it there. */}
{shouldShowLegacyTracePreview(
form.watch("target"),
- isBetaEnabled,
+ isV4,
) && (
<TracesPreview
projectId={props.projectId}
diff --git a/web/src/features/evals/components/variable-mapping-card.tsx b/web/src/features/evals/components/variable-mapping-card.tsx
index 8efd417913..2ccd72faca 100644
--- a/web/src/features/evals/components/variable-mapping-card.tsx
+++ b/web/src/features/evals/components/variable-mapping-card.tsx
@@ -55,7 +55,7 @@ import { useVariableMappingSync } from "@/src/features/evals/hooks/useVariableMa
import { Button } from "@/src/components/ui/button";
import Link from "next/link";
import { useRouter } from "next/router";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import {
type EvalPreviewPointer,
buildEvalPreviewNavigationPath,
@@ -94,7 +94,7 @@ export const VariableMappingCard = ({
const [selectedPreviewPointer, setSelectedPreviewPointer] =
useState<EvalPreviewPointer>();
const router = useRouter();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const peekId =
typeof router.query.peek === "string" ? router.query.peek : undefined;
const isPeekView = Boolean(peekId);
@@ -102,9 +102,9 @@ export const VariableMappingCard = ({
// The trace preview reads the legacy traces table, which is not the v4
// user's experience — never offer it there.
const shouldShowPreviewForTarget =
- shouldShowLegacyTracePreview(target, isBetaEnabled) ||
+ shouldShowLegacyTracePreview(target, isV4) ||
isEventTarget(target) ||
- (isExperimentTarget(target) && isBetaEnabled);
+ (isExperimentTarget(target) && isV4);
const { fields } = useFieldArray({
control: form.control,
@@ -162,7 +162,7 @@ export const VariableMappingCard = ({
shouldShowPreviewForTarget && !disabled && !shouldDisablePreviewForNonOtel;
const previewNavigationListKey = getEvalPreviewDetailPageListKey(
target,
- isBetaEnabled,
+ isV4,
);
const evalPreviewBasePath = hideAdvancedSettings
? `/project/${projectId}/evals/remap?evaluator=${oldConfigId}`
@@ -247,7 +247,7 @@ export const VariableMappingCard = ({
)}
</div>
</div>
- {shouldShowLegacyTracePreview(form.watch("target"), isBetaEnabled) &&
+ {shouldShowLegacyTracePreview(form.watch("target"), isV4) &&
!disabled && (
<FormDescription>
Preview of the evaluation prompt with the variables replaced with
diff --git a/web/src/features/evals/hooks/useEvalCapabilities.ts b/web/src/features/evals/hooks/useEvalCapabilities.ts
index 8c1fb288e2..6ee00d1290 100644
--- a/web/src/features/evals/hooks/useEvalCapabilities.ts
+++ b/web/src/features/evals/hooks/useEvalCapabilities.ts
@@ -1,7 +1,7 @@
import { useSession } from "next-auth/react";
import { api } from "@/src/utils/api";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";
import { useForceV3Experience } from "@/src/features/v4-migration/useForceV3Experience";
import { isNewLegacyEvalAllowed } from "@/src/features/evals/utils/legacyEvalGate";
@@ -30,7 +30,7 @@ export function useEvalCapabilities(
): EvalCapabilities {
const { data: session, status: sessionStatus } = useSession();
const isSessionLoading = sessionStatus === "loading";
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
const isCodeEvalConfig =
isCodeEvalEnabled && (options?.isCodeEvalTemplate ?? false);
@@ -38,7 +38,7 @@ export function useEvalCapabilities(
// Query SDK version info from events table (only when v4 beta is enabled)
const sdkVersionInfo = api.events.getSdkVersionInfo.useQuery(
{ projectId },
- { enabled: isBetaEnabled && Boolean(projectId) },
+ { enabled: isV4 && Boolean(projectId) },
);
// Determine OTEL status from SDK version info
@@ -70,7 +70,7 @@ export function useEvalCapabilities(
return {
isNewCompatible: isOtel,
// True when v4 beta is enabled (SDK check query was run)
- compatibilityCheckWasPerformed: isBetaEnabled,
+ compatibilityCheckWasPerformed: isV4,
// Allow setting up new legacy evals only if: not a code eval AND the
// deployment mode offers the legacy experience. Having existing legacy
// evals no longer grants this; they remain editable via edit mode.
diff --git a/web/src/features/evals/hooks/useEvalConfigMappingData.ts b/web/src/features/evals/hooks/useEvalConfigMappingData.ts
index ecc76340cc..9dc5055e81 100644
--- a/web/src/features/evals/hooks/useEvalConfigMappingData.ts
+++ b/web/src/features/evals/hooks/useEvalConfigMappingData.ts
@@ -7,7 +7,7 @@ import {
usePreviewData,
} from "@/src/features/evals/hooks/usePreviewData";
import { useEffect, useRef } from "react";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { isTraceTargetOnV4 } from "@/src/features/evals/utils/typeHelpers";
import {
type EvalPreviewPointer,
@@ -28,12 +28,12 @@ export function useEvalConfigMappingData(
selectedPreviewPointer?: EvalPreviewPointer,
): EvalConfigMappingData {
const router = useRouter();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const targetValue = useWatch({ control: form.control, name: "target" });
const firstPreviewPointer = useFirstEvalPreviewPointer({
target: targetValue,
- useEventsTable: isBetaEnabled,
+ useEventsTable: isV4,
});
const urlPreviewPointer = getEvalPreviewPointerFromUrlQuery(
router.query,
@@ -45,7 +45,7 @@ export function useEvalConfigMappingData(
// The trace preview reads the legacy traces table, which is not the v4
// user's experience — never fetch or expect preview data there.
- const traceTargetOnV4 = isTraceTargetOnV4(targetValue, isBetaEnabled);
+ const traceTargetOnV4 = isTraceTargetOnV4(targetValue, isV4);
const { previewData, isLoading } = usePreviewData({
projectId,
diff --git a/web/src/features/evals/hooks/usePreviewData.ts b/web/src/features/evals/hooks/usePreviewData.ts
index fb5218c1f2..6c02aaf8a7 100644
--- a/web/src/features/evals/hooks/usePreviewData.ts
+++ b/web/src/features/evals/hooks/usePreviewData.ts
@@ -4,7 +4,7 @@ import {
isEventTarget,
isExperimentTarget,
} from "@/src/features/evals/utils/typeHelpers";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { api, sendAsPostOption, type RouterOutputs } from "@/src/utils/api";
import {
EvalTargetObject,
@@ -308,11 +308,11 @@ export function usePreviewData({
observationId,
timestamp,
}: UsePreviewDataParams): PreviewResult {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const mode = getPreviewMode({
enabled,
target,
- shouldUseEventsTable: isBetaEnabled,
+ shouldUseEventsTable: isV4,
});
const tracePreview = useTracePreview({
diff --git a/web/src/features/evals/pages/remap-evaluator.tsx b/web/src/features/evals/pages/remap-evaluator.tsx
index 54f6ae23d7..82c74b071b 100644
--- a/web/src/features/evals/pages/remap-evaluator.tsx
+++ b/web/src/features/evals/pages/remap-evaluator.tsx
@@ -35,7 +35,7 @@ import {
DEFAULT_OBSERVATION_FILTER_WHEN_REMAPPING,
} from "@/src/features/evals/utils/evaluator-constants";
import { buildModernEvaluatorsUrl } from "@/src/features/v4-migration/evaluatorMigrationUrls";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
const V4_DOCS_URL = "https://langfuse.com/docs/v4";
const EVAL_MIGRATION_DOCS_URL =
@@ -113,7 +113,7 @@ export default function RemapEvaluatorPage() {
await router.push(`/project/${projectId}/evals${filterQuery}`);
};
- const { isBetaEnabled: isV4BetaEnabled } = useV4Beta();
+ const { isV4: isV4BetaEnabled } = useReadPath();
// Map old config to new config with modern target
// Only copy scoreName - filters and variable mapping will be initialized fresh
diff --git a/web/src/features/evals/utils/typeHelpers.ts b/web/src/features/evals/utils/typeHelpers.ts
index 2111697262..b326a2b2d2 100644
--- a/web/src/features/evals/utils/typeHelpers.ts
+++ b/web/src/features/evals/utils/typeHelpers.ts
@@ -56,15 +56,14 @@ export const isTraceTarget = (targetObject: string): boolean => {
export const isTraceTargetOnV4 = (
targetObject: string,
- isBetaEnabled: boolean,
-): boolean => isTraceTarget(targetObject) && isBetaEnabled;
+ isV4: boolean,
+): boolean => isTraceTarget(targetObject) && isV4;
export const shouldShowLegacyTracePreview = (
targetObject: string,
- isBetaEnabled: boolean,
+ isV4: boolean,
): boolean =>
- isTraceTarget(targetObject) &&
- !isTraceTargetOnV4(targetObject, isBetaEnabled);
+ isTraceTarget(targetObject) && !isTraceTargetOnV4(targetObject, isV4);
export const isEventTarget = (targetObject: string): boolean => {
return targetObject === EvalTargetObject.EVENT;
diff --git a/web/src/features/events/actions/setReadPath.ts b/web/src/features/events/actions/setReadPath.ts
new file mode 100644
index 0000000000..bb572a596a
--- /dev/null
+++ b/web/src/features/events/actions/setReadPath.ts
@@ -0,0 +1,77 @@
+import posthog from "posthog-js";
+
+import { type ResolvedReadPath } from "@/src/features/events/hooks/useReadPath";
+import { readPathToggleStore } from "@/src/features/events/stores/readPathToggleStore";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { V4_BETA_ENABLED_POSTHOG_PROPERTY } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { setV4BetaEnabledSentryTag } from "@/src/utils/sentryV4BetaTag";
+
+type SetReadPathDeps = {
+ /** `api.userAccount.setV4BetaEnabled` mutateAsync, wired by the toggle surface. */
+ setV4BetaEnabled: (input: {
+ enabled: boolean;
+ }) => Promise<{ v4BetaEnabled: boolean }>;
+ /**
+ * next-auth session update. Returns null on failure (it never throws) —
+ * a failed refresh is a failed toggle.
+ */
+ updateSession: () => Promise<unknown>;
+ /** Runs only after the toggle fully committed (mutation + session update). */
+ onSuccess?: () => void | Promise<unknown>;
+};
+
+/**
+ * The one toggle workflow shared by every read-path toggle surface. The
+ * switch renders `pendingReadPath ?? session read path`, so on any failure —
+ * an unrefreshed session would leave the UI on the old read path while the
+ * server is on the new one, so a failed `updateSession` counts too — clearing
+ * the pending intent snaps the switch back to the session's value.
+ */
+export async function setReadPath(
+ target: ResolvedReadPath,
+ deps: SetReadPathDeps,
+): Promise<void> {
+ const { pendingReadPath, actions } = readPathToggleStore.getState();
+ if (pendingReadPath !== null) return;
+ actions.begin(target);
+
+ try {
+ // The server may override the requested value (e.g. events_only ignores
+ // an opt-out) — analytics and Sentry tag follow what it actually set.
+ const { v4BetaEnabled } = await deps.setV4BetaEnabled({
+ enabled: target === "v4",
+ });
+ posthog.setPersonProperties({
+ [V4_BETA_ENABLED_POSTHOG_PROPERTY]: v4BetaEnabled,
+ });
+ posthog.register({
+ [V4_BETA_ENABLED_POSTHOG_PROPERTY]: v4BetaEnabled,
+ });
+ setV4BetaEnabledSentryTag(v4BetaEnabled);
+ const updatedSession = await deps.updateSession();
+ if (!updatedSession) {
+ throw new Error(
+ "The setting was saved but the session could not be refreshed",
+ );
+ }
+ } catch (error) {
+ actions.settle();
+ showErrorToast(
+ target === "v4" ? "Could not switch to V4" : "Could not switch to V3",
+ error instanceof Error ? error.message : "Please try again.",
+ );
+ return;
+ }
+
+ // Pending intent is kept through onSuccess (the post-toggle redirect) so
+ // the switch stays disabled until navigation lands. The toggle itself has
+ // committed at this point — a failed redirect must not read as a failed
+ // toggle (and callers do not await this workflow).
+ try {
+ await deps.onSuccess?.();
+ } catch {
+ // best-effort post-toggle navigation
+ } finally {
+ actions.settle();
+ }
+}
diff --git a/web/src/features/events/components/V4SidebarToggle.tsx b/web/src/features/events/components/V4SidebarToggle.tsx
index d7f18cac0e..3930217c26 100644
--- a/web/src/features/events/components/V4SidebarToggle.tsx
+++ b/web/src/features/events/components/V4SidebarToggle.tsx
@@ -6,7 +6,9 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/src/components/ui/tooltip";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
+import { setReadPath } from "@/src/features/events/actions/setReadPath";
+import { usePendingReadPath } from "@/src/features/events/stores/readPathToggleStore";
import { V4IntroDialog } from "@/src/features/events/components/V4IntroDialog";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";
@@ -15,9 +17,11 @@ import {
getV4PreviewEnabledRedirect,
} from "@/src/features/events/lib/v4PreviewRedirect";
import { useQueryProject } from "@/src/features/projects/hooks";
+import { api } from "@/src/utils/api";
import { ZapIcon } from "lucide-react";
-import { useId } from "react";
+import { useId, useState } from "react";
import { useRouter } from "next/router";
+import { useSession } from "next-auth/react";
import {
singleRunToExperimentsUrl,
toExperimentsResultsUrl,
@@ -37,31 +41,40 @@ function asArrayValue(value: string | string[] | undefined) {
return Array.isArray(value) ? value : [value];
}
+const INTRO_DIALOG_SEEN_KEY = "v4-beta-intro-dialog-seen";
+
// Shared behavior for every V4 Preview toggle surface: session-backed state,
// intro dialog on first enable, and the datasets/experiments URL translation
// that keeps the current page valid after switching. `source` distinguishes
-// the surfaces in the shared v4_beta_toggled event.
+// the surfaces in the shared v4_beta_toggled event. The commit itself is the
+// shared `setReadPath` workflow; only the intro dialog lives here.
function useV4PreviewToggle(source: "sidebar" | "migration_panel") {
const router = useRouter();
- const {
- isBetaEnabled,
- canToggleV4,
- setBetaEnabled,
- enableWithIntro,
- showIntroDialog,
- confirmIntroDialog,
- dismissIntroDialog,
- isLoading,
- } = useV4Beta();
+ const { isV4, canToggleV4 } = useReadPath();
+ const pendingReadPath = usePendingReadPath();
+ const { update: updateSession } = useSession();
+ const mutation = api.userAccount.setV4BetaEnabled.useMutation();
const capture = usePostHogClientCapture();
- const redirectAfterToggle = (enabled: boolean) => {
+ const [showIntroDialog, setShowIntroDialog] = useState(false);
+ const [pendingAfterToggle, setPendingAfterToggle] = useState<
+ (() => Promise<unknown> | void) | undefined
+ >();
+
+ // The pending intent wins while a toggle is committing, so the switch shows
+ // the value the user just chose — and snaps back if the commit fails.
+ const isChecked = pendingReadPath ? pendingReadPath === "v4" : isV4;
+ const isLoading = pendingReadPath !== null;
+
+ // Returns the navigation promise so the pending intent (disabled switch)
+ // holds until the redirect lands.
+ const redirectAfterToggle = (enabled: boolean): Promise<unknown> | void => {
const projectId = asSingleValue(router.query.projectId);
if (!projectId) return;
if (!enabled) {
const redirect = getV4PreviewDisabledRedirect(router.pathname, projectId);
- if (redirect) router.push(redirect);
+ if (redirect) return router.push(redirect);
return;
}
@@ -70,8 +83,7 @@ function useV4PreviewToggle(source: "sidebar" | "migration_panel") {
projectId,
);
if (evaluatorRedirect) {
- router.push(evaluatorRedirect);
- return;
+ return router.push(evaluatorRedirect);
}
if (
@@ -80,7 +92,7 @@ function useV4PreviewToggle(source: "sidebar" | "migration_panel") {
) {
const runId = asSingleValue(router.query.runId);
if (runId) {
- router.push(singleRunToExperimentsUrl(projectId, runId));
+ return router.push(singleRunToExperimentsUrl(projectId, runId));
}
return;
}
@@ -92,32 +104,58 @@ function useV4PreviewToggle(source: "sidebar" | "migration_panel") {
) {
const runIds = asArrayValue(router.query.runs);
if (runIds.length > 0) {
- router.push(toExperimentsResultsUrl(projectId, runIds));
+ return router.push(toExperimentsResultsUrl(projectId, runIds));
}
}
};
+ const commitToggle = (
+ enabled: boolean,
+ afterToggle?: () => Promise<unknown> | void,
+ ) => {
+ setReadPath(enabled ? "v4" : "v3", {
+ setV4BetaEnabled: (input) => mutation.mutateAsync(input),
+ updateSession,
+ onSuccess: () => {
+ capture("sidebar:v4_beta_toggled", { enabled, source });
+ return afterToggle ? afterToggle() : redirectAfterToggle(enabled);
+ },
+ });
+ };
+
// afterToggle, when given, replaces the default same-page URL translation
// and runs only after the toggle actually committed (mutation + session
// update done, intro dialog confirmed rather than dismissed).
- const handleToggle = (enabled: boolean, afterToggle?: () => void) => {
- const onSuccess = () => {
- capture("sidebar:v4_beta_toggled", { enabled, source });
- if (afterToggle) {
- afterToggle();
- } else {
- redirectAfterToggle(enabled);
- }
- };
- if (enabled) {
- enableWithIntro({ onSuccess });
- } else {
- setBetaEnabled(false, { onSuccess });
+ const handleToggle = (
+ enabled: boolean,
+ afterToggle?: () => Promise<unknown> | void,
+ ) => {
+ if (
+ enabled &&
+ typeof window !== "undefined" &&
+ !localStorage.getItem(INTRO_DIALOG_SEEN_KEY)
+ ) {
+ setPendingAfterToggle(() => afterToggle);
+ setShowIntroDialog(true);
+ return;
}
+ commitToggle(enabled, afterToggle);
+ };
+
+ const confirmIntroDialog = () => {
+ localStorage.setItem(INTRO_DIALOG_SEEN_KEY, "true");
+ setShowIntroDialog(false);
+ commitToggle(true, pendingAfterToggle);
+ setPendingAfterToggle(undefined);
+ };
+
+ const dismissIntroDialog = () => {
+ setShowIntroDialog(false);
+ setPendingAfterToggle(undefined);
};
return {
- isBetaEnabled,
+ isChecked,
canToggleV4,
isLoading,
handleToggle,
@@ -129,7 +167,7 @@ function useV4PreviewToggle(source: "sidebar" | "migration_panel") {
export function V4SidebarToggle() {
const {
- isBetaEnabled,
+ isChecked,
canToggleV4,
isLoading,
handleToggle,
@@ -168,7 +206,7 @@ export function V4SidebarToggle() {
<Switch
id="v4-beta-toggle"
size="sm"
- checked={isBetaEnabled}
+ checked={isChecked}
onCheckedChange={handleToggle}
disabled={isLoading}
aria-label="Toggle V4 Preview"
@@ -205,7 +243,7 @@ export function V4PreviewToggleRow({ projectId }: { projectId?: string }) {
const toggleId = useId();
const descriptionId = useId();
const {
- isBetaEnabled,
+ isChecked,
canToggleV4,
isLoading,
handleToggle,
@@ -232,7 +270,7 @@ export function V4PreviewToggleRow({ projectId }: { projectId?: string }) {
<Switch
id={toggleId}
size="sm"
- checked={isBetaEnabled}
+ checked={isChecked}
onCheckedChange={handlePanelToggle}
disabled={isLoading}
aria-label="Toggle V4 Preview"
diff --git a/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsx b/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsx
index 98431809e3..c4a771dd99 100644
--- a/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsx
+++ b/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsx
@@ -281,7 +281,7 @@ export function EventsOutlierStrip({
? prev
: undefined;
},
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
trpc: { context: { skipBatch: true } },
},
);
diff --git a/web/src/features/events/hooks/useReadPath.ts b/web/src/features/events/hooks/useReadPath.ts
new file mode 100644
index 0000000000..413e35eec6
--- /dev/null
+++ b/web/src/features/events/hooks/useReadPath.ts
@@ -0,0 +1,42 @@
+import { useSession } from "next-auth/react";
+
+/** The events read path a data-fetching surface must use. */
+export type ResolvedReadPath = "v3" | "v4";
+/** "unknown" = the session has not resolved yet; no versioned fetch may fire. */
+export type ReadPath = ResolvedReadPath | "unknown";
+
+/**
+ * The user's v3/v4 read path, derived from the session. v4 is the default
+ * experience; v3 is the explicit legacy opt-out. While the session is still
+ * loading the read path is "unknown": UI chrome may use the `isV4` /
+ * `isV3Legacy` booleans (both false while unknown), but anything that fetches
+ * by version must consume a resolved `readPath` — gate rendering on
+ * `isResolved` and pass the narrowed value down as a prop.
+ */
+export function useReadPath(): {
+ readPath: ReadPath;
+ isV4: boolean;
+ isV3Legacy: boolean;
+ isResolved: boolean;
+ canToggleV4: boolean;
+} {
+ const { data: session, status } = useSession();
+
+ // A session re-check reports "loading" with the previous session still in
+ // hand — that keeps the resolved path. Only a cold load is unknown.
+ const readPath: ReadPath = session?.user
+ ? session.user.v4BetaEnabled === true
+ ? "v4"
+ : "v3"
+ : status === "loading"
+ ? "unknown"
+ : "v3";
+
+ return {
+ readPath,
+ isV4: readPath === "v4",
+ isV3Legacy: readPath === "v3",
+ isResolved: readPath !== "unknown",
+ canToggleV4: session?.user?.canToggleV4 === true,
+ };
+}
diff --git a/web/src/features/events/hooks/useV4Beta.ts b/web/src/features/events/hooks/useV4Beta.ts
deleted file mode 100644
index c4313c9b41..0000000000
--- a/web/src/features/events/hooks/useV4Beta.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { useSession } from "next-auth/react";
-import { api } from "@/src/utils/api";
-import { useCallback, useState } from "react";
-import posthog from "posthog-js";
-import { V4_BETA_ENABLED_POSTHOG_PROPERTY } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { setV4BetaEnabledSentryTag } from "@/src/utils/sentryV4BetaTag";
-
-type SetV4EnabledOptions = {
- onSuccess?: () => void | Promise<void>;
-};
-
-const INTRO_DIALOG_SEEN_KEY = "v4-beta-intro-dialog-seen";
-
-export function useV4Beta() {
- const {
- data: session,
- update: updateSession,
- status: sessionStatus,
- } = useSession();
-
- const mutation = api.userAccount.setV4BetaEnabled.useMutation();
-
- const isBetaEnabled = session?.user?.v4BetaEnabled ?? false;
- const canToggleV4 = session?.user?.canToggleV4 === true;
- const isInitializing = sessionStatus === "loading";
- const [showIntroDialog, setShowIntroDialog] = useState(false);
- const [pendingOnSuccess, setPendingOnSuccess] =
- useState<SetV4EnabledOptions["onSuccess"]>();
-
- const setBetaEnabled = useCallback(
- (enabled: boolean, options?: SetV4EnabledOptions) => {
- mutation.mutate(
- { enabled },
- {
- onSuccess: async ({ v4BetaEnabled }) => {
- posthog.setPersonProperties({
- [V4_BETA_ENABLED_POSTHOG_PROPERTY]: v4BetaEnabled,
- });
- posthog.register({
- [V4_BETA_ENABLED_POSTHOG_PROPERTY]: v4BetaEnabled,
- });
- setV4BetaEnabledSentryTag(v4BetaEnabled);
- await updateSession();
- await options?.onSuccess?.();
- },
- },
- );
- },
- [mutation, updateSession],
- );
-
- const enableWithIntro = useCallback(
- (options?: SetV4EnabledOptions) => {
- if (
- typeof window !== "undefined" &&
- !localStorage.getItem(INTRO_DIALOG_SEEN_KEY)
- ) {
- setPendingOnSuccess(() => options?.onSuccess);
- setShowIntroDialog(true);
- return;
- }
-
- setBetaEnabled(true, options);
- },
- [setBetaEnabled],
- );
-
- const confirmIntroDialog = useCallback(() => {
- localStorage.setItem(INTRO_DIALOG_SEEN_KEY, "true");
- setShowIntroDialog(false);
- setBetaEnabled(true, { onSuccess: pendingOnSuccess });
- setPendingOnSuccess(undefined);
- }, [setBetaEnabled, pendingOnSuccess]);
-
- const dismissIntroDialog = useCallback(() => {
- setShowIntroDialog(false);
- setPendingOnSuccess(undefined);
- }, []);
-
- return {
- isBetaEnabled,
- canToggleV4,
- isInitializing,
- setBetaEnabled,
- enableWithIntro,
- showIntroDialog,
- confirmIntroDialog,
- dismissIntroDialog,
- isLoading: mutation.isPending,
- };
-}
diff --git a/web/src/features/events/stores/readPathToggleStore.ts b/web/src/features/events/stores/readPathToggleStore.ts
new file mode 100644
index 0000000000..e67b5a9be5
--- /dev/null
+++ b/web/src/features/events/stores/readPathToggleStore.ts
@@ -0,0 +1,28 @@
+import { useStore } from "zustand";
+import { createStore } from "zustand/vanilla";
+
+import { type ResolvedReadPath } from "@/src/features/events/hooks/useReadPath";
+
+type ReadPathToggleState = {
+ /** The read path a toggle is currently committing; null when idle. */
+ pendingReadPath: ResolvedReadPath | null;
+ actions: {
+ begin: (target: ResolvedReadPath) => void;
+ settle: () => void;
+ };
+};
+
+// Global on purpose: the post-toggle redirect remounts the toggle surfaces,
+// and the in-flight intent must survive that remount.
+export const readPathToggleStore = createStore<ReadPathToggleState>()(
+ (set) => ({
+ pendingReadPath: null,
+ actions: {
+ begin: (target) => set({ pendingReadPath: target }),
+ settle: () => set({ pendingReadPath: null }),
+ },
+ }),
+);
+
+export const usePendingReadPath = (): ResolvedReadPath | null =>
+ useStore(readPathToggleStore, (state) => state.pendingReadPath);
diff --git a/web/src/features/experiments/hooks/useExperimentAccess.ts b/web/src/features/experiments/hooks/useExperimentAccess.ts
index 734fc4d099..ab23976860 100644
--- a/web/src/features/experiments/hooks/useExperimentAccess.ts
+++ b/web/src/features/experiments/hooks/useExperimentAccess.ts
@@ -1,7 +1,7 @@
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
export function useExperimentAccess() {
- const { isBetaEnabled: isV4BetaEnabled, isInitializing } = useV4Beta();
+ const { isV4: isV4BetaEnabled, isResolved } = useReadPath();
return {
canAccessExperiments: isV4BetaEnabled,
@@ -9,7 +9,7 @@ export function useExperimentAccess() {
// Experiments beta now follows the v4 / fast-preview beta flag directly.
// There is no separate opt-in toggle anymore.
isExperimentsBetaActive: isV4BetaEnabled,
- isInitializing,
+ isInitializing: !isResolved,
isV4BetaEnabled,
};
}
diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
index 3dbcf7cf43..9649d9ab65 100644
--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx
@@ -2,7 +2,7 @@ import { useSession } from "next-auth/react";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { V4_PREVIEW_LABEL } from "@/src/features/events/lib/v4PreviewLabel";
import { featurePreviewLabels } from "@/src/features/feature-flags/available-flags";
import { api } from "@/src/utils/api";
@@ -23,7 +23,7 @@ export function ControlledFeaturePreviewModal({
onOpenChange,
}: ControlledFeaturePreviewModalProps) {
const authSession = useSession();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const capture = usePostHogClientCapture();
const setFeaturePreviewEnabled =
api.userAccount.setFeaturePreviewEnabled.useMutation({
@@ -52,9 +52,9 @@ export function ControlledFeaturePreviewModal({
authSession.data?.user?.featureFlags.modernSession === true ||
authSession.data?.environment.enableExperimentalFeatures === true,
disabled:
- !isBetaEnabled ||
+ !isV4 ||
authSession.data?.environment.enableExperimentalFeatures === true,
- warningReason: !isBetaEnabled
+ warningReason: !isV4
? `Compact Session View is only available on the events-backed session view. Turn on ${V4_PREVIEW_LABEL} to enable it.`
: authSession.data?.environment.enableExperimentalFeatures === true
? "This preview is enabled by LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES, so a per-user opt-out does not disable it."
diff --git a/web/src/features/monitors/components/MonitorChartPreview.tsx b/web/src/features/monitors/components/MonitorChartPreview.tsx
index 16d7248a13..c188b246b2 100644
--- a/web/src/features/monitors/components/MonitorChartPreview.tsx
+++ b/web/src/features/monitors/components/MonitorChartPreview.tsx
@@ -79,7 +79,7 @@ export const MonitorChartPreview = ({
},
{
trpc: { context: { skipBatch: true } },
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
refetchOnWindowFocus: false,
},
);
@@ -103,7 +103,7 @@ export const MonitorChartPreview = ({
},
{
trpc: { context: { skipBatch: true } },
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
refetchOnWindowFocus: false,
},
);
diff --git a/web/src/features/navigate-detail-pages/DetailPageNav.tsx b/web/src/features/navigate-detail-pages/DetailPageNav.tsx
index 937c86efcd..2cf4682162 100644
--- a/web/src/features/navigate-detail-pages/DetailPageNav.tsx
+++ b/web/src/features/navigate-detail-pages/DetailPageNav.tsx
@@ -11,7 +11,7 @@ import {
useDetailPageLists,
} from "@/src/features/navigate-detail-pages/context";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { cn } from "@/src/utils/tailwind";
import { ArrowDown, ArrowUp } from "lucide-react";
import { useRouter } from "next/router";
@@ -44,7 +44,7 @@ export const DetailPageNav = (props: {
);
const capture = usePostHogClientCapture();
- const { isBetaEnabled: isV4 } = useV4Beta();
+ const { isV4 } = useReadPath();
const router = useRouter();
const currentIndex = entries.findIndex((entry) => entry.id === currentId);
const previousPageEntry =
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index 8e2a964b78..68495f7c97 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -36,7 +36,7 @@ import { JumpToPlaygroundDropdownMenuController } from "@/src/features/playgroun
import { ChatMlArraySchema } from "@/src/components/schemas/ChatMlSchema";
import LegacyGenerations from "@/src/components/table/use-cases/observations";
import EventsTable from "@/src/features/events/components/EventsTable";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import {
ChevronDown,
FlaskConical,
@@ -124,7 +124,7 @@ export const PromptDetail = ({
const projectId = useProjectIdFromURL();
const capture = usePostHogClientCapture();
const router = useRouter();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const promptName =
promptNameProp ||
@@ -547,7 +547,7 @@ export const PromptDetail = ({
className="mt-0 mb-2 flex max-h-full min-h-0 flex-1 flex-col overflow-hidden"
>
<div className="flex h-full flex-1 flex-col overflow-hidden">
- {isBetaEnabled ? (
+ {isV4 ? (
<EventsTable
projectId={prompt.projectId}
promptName={prompt.name}
diff --git a/web/src/features/scores-chart-view/components/ScoresChartView.tsx b/web/src/features/scores-chart-view/components/ScoresChartView.tsx
index 26c0dfa9d1..16afb95970 100644
--- a/web/src/features/scores-chart-view/components/ScoresChartView.tsx
+++ b/web/src/features/scores-chart-view/components/ScoresChartView.tsx
@@ -31,7 +31,7 @@ import { AddToDashboardButton } from "@/src/features/chart-view/components/AddTo
* dropped from the chart query rather than erroring — it keeps narrowing the
* table underneath.
*
- * `viewVersion` MUST come from the caller's own `isBetaEnabled` check (the
+ * `viewVersion` MUST come from the caller's own `isV4` check (the
* same one `scores.tsx` already uses to pick `scoresV3`/`scoresV4` for the
* table rows, and the same one `ChartScores`/`WidgetForm` use as
* `metricsVersion`/`activeVersion`) — hardcoding "v2" here would run the
@@ -79,7 +79,7 @@ export function ScoresChartView({
{ projectId, query, version: viewVersion },
{
enabled: validRange,
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
trpc: { context: { skipBatch: true } },
},
);
diff --git a/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx b/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx
index 12b1664a8a..e202dd968a 100644
--- a/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx
+++ b/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx
@@ -60,7 +60,7 @@ export function ScoresOutlierStrip({
fromTimestamp: Date;
toTimestamp: Date;
onSelectRange: (range: { from: Date; to: Date }) => void;
- /** Must match the caller's own `isBetaEnabled` check — see `ScoresChartView`'s doc comment. */
+ /** Must match the caller's own `isV4` check — see `ScoresChartView`'s doc comment. */
viewVersion: ViewVersion;
}) {
const capture = usePostHogClientCapture();
@@ -162,7 +162,7 @@ export function ScoresOutlierStrip({
// change (drill-in, Back, preset hop) shows the skeleton instead.
placeholderData: (prev, prevQuery) =>
prev && isSameGridAsCurrent(prevQuery) ? prev : undefined,
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
trpc: { context: { skipBatch: true } },
},
);
@@ -174,7 +174,7 @@ export function ScoresOutlierStrip({
// Same same-grid placeholder reuse as `countQuery` above.
placeholderData: (prev, prevQuery) =>
prev && isSameGridAsCurrent(prevQuery) ? prev : undefined,
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
trpc: { context: { skipBatch: true } },
},
);
diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.md
index 4807e78eb2..88500f677b 100644
--- a/web/src/features/search-bar/README.md
+++ b/web/src/features/search-bar/README.md
@@ -19,7 +19,7 @@ tables (no opt-in). Based on the `langfuse-search-bar` prototype.
(`!hideControls && !externalFilterState && !peekContext && !userId && !sessionId`).
The **v4 beta** gate is implicit: `EventsTable` only mounts on the v4
Observations/Traces tables, so call sites still read as
- `isBetaEnabled && useSearchBarEnabled()`.
+ `isV4 && useSearchBarEnabled()`.
- The search bar is not a Feature Preview and has no user or organization
toggle.
diff --git a/web/src/features/search-bar/hooks/useSearchBarEnabled.ts b/web/src/features/search-bar/hooks/useSearchBarEnabled.ts
index 70d9a36aef..e17f55d8ce 100644
--- a/web/src/features/search-bar/hooks/useSearchBarEnabled.ts
+++ b/web/src/features/search-bar/hooks/useSearchBarEnabled.ts
@@ -2,7 +2,7 @@
* Whether the grammar search bar should render. It is now **generally available
* on the v4 events tables** — every user gets it, no longer a per-user Feature
* Preview opt-in. The bar still only renders on the v4 Observations/Traces
- * tables, so call sites keep gating on `isBetaEnabled && useSearchBarEnabled()`
+ * tables, so call sites keep gating on `isV4 && useSearchBarEnabled()`
* (EventsTable only mounts in v4 mode, so the v4 gate is implicit there).
*/
export function useSearchBarEnabled(): boolean {
diff --git a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
index df5854aadc..a9fb36f072 100644
--- a/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/ConnectedObservationDetailView.tsx
@@ -10,7 +10,7 @@
* Hooks:
* - useViewPreferences() - for JSON view preference
* - useState() - for tab selection
- * - useV4Beta() - for v4 mode detection (enables log tab)
+ * - useReadPath() - for v4 mode detection (enables log tab)
*
* Re-renders when:
* - Observation prop changes (new observation selected)
@@ -56,7 +56,7 @@ import { api } from "@/src/utils/api";
// Extracted components
import { ObservationDetailViewHeader } from "@/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader";
import { TraceLogView } from "../TraceLogView/TraceLogView";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { TRACE_VIEW_CONFIG } from "@/src/features/traces/constants/traceViewConfig";
import {
aggregateTraceMetrics,
@@ -86,7 +86,7 @@ export function ConnectedObservationDetailView({
const utils = api.useUtils();
// V4 beta mode and observations for log tab
- const { isBetaEnabled: isV4Enabled } = useV4Beta();
+ const { isV4: isV4Enabled } = useReadPath();
const {
observations,
roots,
diff --git a/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx b/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx
index 0f6ae8e45e..f0612dd6fc 100644
--- a/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx
+++ b/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx
@@ -56,7 +56,7 @@ import { type AggregatedTraceMetrics } from "@/src/features/traces/fns/traceAggr
import type Decimal from "decimal.js";
import { DetailHeaderActionsMenuController } from "@/src/features/traces/components/DetailHeaderActionsMenuController";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
import { Button } from "@/src/components/ui/button";
import { ActionButtonCountBadge } from "@/src/components/ui/action-button-count-badge";
@@ -133,7 +133,7 @@ export const ObservationDetailViewHeader = memo(
}: ObservationDetailViewHeaderProps) {
const { isAnnotationMode } = useViewPreferences();
const isMobile = useIsMobile();
- const { isBetaEnabled: isV4Enabled } = useV4Beta();
+ const { isV4: isV4Enabled } = useReadPath();
const { trace, serverScores } = useTraceData();
// Get trace-level scores for V4 dual annotation
diff --git a/web/src/features/traces/components/TraceLogView/useLogViewObservationIO.ts b/web/src/features/traces/components/TraceLogView/useLogViewObservationIO.ts
index 1ffe627429..bfcb5a4cdf 100644
--- a/web/src/features/traces/components/TraceLogView/useLogViewObservationIO.ts
+++ b/web/src/features/traces/components/TraceLogView/useLogViewObservationIO.ts
@@ -9,7 +9,7 @@ import { useMemo } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { api, sendAsPostOption } from "@/src/utils/api";
import { type FlatLogItem } from "./log-view-types";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
export interface UseLogViewObservationIOParams {
observationId: string;
@@ -33,7 +33,7 @@ export function useLogViewObservationIO({
startTime,
enabled,
}: UseLogViewObservationIOParams) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// Old path: fetch from observations table (beta OFF)
const observationsQuery = api.observations.byId.useQuery(
@@ -44,7 +44,7 @@ export function useLogViewObservationIO({
startTime,
},
{
- enabled: enabled && !isBetaEnabled,
+ enabled: enabled && !isV4,
staleTime: Infinity,
refetchOnWindowFocus: false,
},
@@ -62,14 +62,14 @@ export function useLogViewObservationIO({
},
{
...sendAsPostOption,
- enabled: enabled && isBetaEnabled,
+ enabled: enabled && isV4,
staleTime: Infinity,
refetchOnWindowFocus: false,
select: (data) => data[0], // Extract single result from batch
},
);
- if (isBetaEnabled) {
+ if (isV4) {
return {
data: eventsQuery.data,
isLoading: eventsQuery.isLoading,
diff --git a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx
index caaf3da728..ad749c9058 100644
--- a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx
+++ b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx
@@ -13,7 +13,7 @@ import { useSearch } from "@/src/features/traces/contexts/SearchContext";
import { useSelection } from "@/src/features/traces/contexts/SelectionContext";
import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";
import { useTraceGraphData } from "@/src/features/traces/contexts/TraceGraphDataContext";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { Command, CommandInput } from "@/src/components/ui/command";
import { Button } from "@/src/components/ui/button";
import {
@@ -94,7 +94,7 @@ function TracePanelNavigationHeaderExpanded({
const { expandAll, collapseAll, collapsedNodes } = useSelection();
const { roots, trace, observations } = useTraceData();
const { isGraphViewAvailable } = useTraceGraphData();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const [viewMode, setViewMode] = useQueryParam("view", StringParam);
const capture = usePostHogClientCapture();
const analyticsDimensions = useTraceAnalyticsDimensions();
@@ -149,7 +149,7 @@ function TracePanelNavigationHeaderExpanded({
useWatchedPromiseCallback(async () => {
capture("trace_detail:download_button_click", analyticsDimensions);
try {
- if (!isBetaEnabled) {
+ if (!isV4) {
downloadLegacyTraceAsJson({
trace,
observations,
@@ -174,7 +174,7 @@ function TracePanelNavigationHeaderExpanded({
: "Failed to download trace JSON",
);
}
- }, [isBetaEnabled, observations, trace, capture, analyticsDimensions]);
+ }, [isV4, observations, trace, capture, analyticsDimensions]);
const isTimelineView = viewMode === "timeline";
diff --git a/web/src/features/traces/contexts/TraceGraphDataContext.tsx b/web/src/features/traces/contexts/TraceGraphDataContext.tsx
index 24924e6cc3..131d6e0a4c 100644
--- a/web/src/features/traces/contexts/TraceGraphDataContext.tsx
+++ b/web/src/features/traces/contexts/TraceGraphDataContext.tsx
@@ -10,7 +10,7 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
import { api } from "@/src/utils/api";
import { type AgentGraphDataResponse } from "@/src/features/trace-graph-view/types";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
const MAX_NODES_FOR_GRAPH_UI = 5000;
@@ -56,7 +56,7 @@ export function TraceGraphDataProvider({
traceId,
observations,
}: TraceGraphDataProviderProps) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// Skip graph data entirely for large traces to avoid performance issues
const exceedsThreshold = observations.length >= MAX_NODES_FOR_GRAPH_UI;
@@ -105,17 +105,17 @@ export function TraceGraphDataProvider({
// Beta OFF: Query from observations table (existing behavior)
const tracesQuery = api.traces.getAgentGraphData.useQuery(queryInput, {
...queryOptions,
- enabled: queryEnabled && !isBetaEnabled,
+ enabled: queryEnabled && !isV4,
});
// Beta ON: Query from events table (v4)
const eventsQuery = api.events.getAgentGraphData.useQuery(queryInput, {
...queryOptions,
- enabled: queryEnabled && isBetaEnabled,
+ enabled: queryEnabled && isV4,
});
// Use appropriate query based on beta toggle
- const query = isBetaEnabled ? eventsQuery : tracesQuery;
+ const query = isV4 ? eventsQuery : tracesQuery;
const agentGraphData = useMemo(() => query.data ?? [], [query.data]);
diff --git a/web/src/features/traces/hooks/useParsedObservation.ts b/web/src/features/traces/hooks/useParsedObservation.ts
index 92881f6099..8bdc3b8abb 100644
--- a/web/src/features/traces/hooks/useParsedObservation.ts
+++ b/web/src/features/traces/hooks/useParsedObservation.ts
@@ -14,7 +14,7 @@
import { useQuery } from "@tanstack/react-query";
import { useMemo, useEffect } from "react";
import { api, sendAsPostOption } from "@/src/utils/api";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { type EventBatchIOOutput } from "@/src/features/events/server/eventsRouter";
import {
type ObservationReturnTypeWithMetadata,
@@ -207,7 +207,7 @@ export function useParsedObservation({
startTime,
baseObservation,
}: UseParsedObservationParams) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// Step 1a: Fetch raw observation data from observations table (beta OFF)
const observationQuery = api.observations.byId.useQuery(
@@ -218,7 +218,7 @@ export function useParsedObservation({
startTime,
},
{
- enabled: !isBetaEnabled,
+ enabled: !isV4,
staleTime: 5 * 60 * 1000, // 5 minutes
},
);
@@ -235,14 +235,14 @@ export function useParsedObservation({
},
{
...sendAsPostOption,
- enabled: isBetaEnabled,
+ enabled: isV4,
staleTime: 5 * 60 * 1000, // 5 minutes
select: (data) => data[0], // Extract single result from batch
},
);
const mergedObservation = useMemo<ParsedObservationResult>(() => {
- if (isBetaEnabled) {
+ if (isV4) {
if (baseObservation && eventsQuery.data) {
return {
...baseObservation,
@@ -257,20 +257,20 @@ export function useParsedObservation({
}
// Beta OFF: return full observation from observations table
return observationQuery.data;
- }, [isBetaEnabled, baseObservation, eventsQuery.data, observationQuery.data]);
+ }, [isV4, baseObservation, eventsQuery.data, observationQuery.data]);
// TODO: remove when going into prod
// Log warning if baseObservation missing when beta ON (helps catch issues in testing)
useEffect(() => {
- if (isBetaEnabled && eventsQuery.data && !baseObservation) {
+ if (isV4 && eventsQuery.data && !baseObservation) {
console.warn(
"[useParsedObservation] baseObservation missing - JumpToPlaygroundButton may not work correctly",
{ observationId },
);
}
- }, [isBetaEnabled, eventsQuery.data, baseObservation, observationId]);
+ }, [isV4, eventsQuery.data, baseObservation, observationId]);
- const isLoadingRaw = isBetaEnabled
+ const isLoadingRaw = isV4
? eventsQuery.isLoading
: observationQuery.isLoading;
diff --git a/web/src/features/traces/hooks/usePrefetchObservation.ts b/web/src/features/traces/hooks/usePrefetchObservation.ts
index 9ae7827d44..0ea6fb3abf 100644
--- a/web/src/features/traces/hooks/usePrefetchObservation.ts
+++ b/web/src/features/traces/hooks/usePrefetchObservation.ts
@@ -1,5 +1,5 @@
import { api, sendAsPostOption } from "@/src/utils/api";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
export type UsePrefetchObservationParams = {
projectId: string;
@@ -13,14 +13,14 @@ export function usePrefetchObservation({
projectId,
}: UsePrefetchObservationParams) {
const utils = api.useUtils();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const prefetch = (
observationId: string,
traceId: string,
startTime?: Date,
) => {
- if (isBetaEnabled) {
+ if (isV4) {
// Beta ON: prefetch from events table via batchIO
if (!startTime) return;
utils.events.batchIO.prefetch(
diff --git a/web/src/features/traces/hooks/useTraceAnalyticsDimensions.ts b/web/src/features/traces/hooks/useTraceAnalyticsDimensions.ts
index 477e7ff6b3..11563f734c 100644
--- a/web/src/features/traces/hooks/useTraceAnalyticsDimensions.ts
+++ b/web/src/features/traces/hooks/useTraceAnalyticsDimensions.ts
@@ -1,6 +1,6 @@
import { useMemo } from "react";
import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
/**
* Shared segmentation dimensions for every `trace_detail:*` analytics event:
@@ -15,10 +15,7 @@ import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
*/
export function useTraceAnalyticsDimensions() {
const { traceContext } = useViewPreferences();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
- return useMemo(
- () => ({ traceContext, isV4: isBetaEnabled }),
- [traceContext, isBetaEnabled],
- );
+ return useMemo(() => ({ traceContext, isV4: isV4 }), [traceContext, isV4]);
}
diff --git a/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx b/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx
index adf7987b26..e9cfe17884 100644
--- a/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx
+++ b/web/src/features/traces/hooks/useTraceDetailData.clienttest.tsx
@@ -5,21 +5,21 @@ import { useTraceDetailData } from "@/src/features/traces/hooks/useTraceDetailDa
// Created via vi.hoisted so they exist before the hoisted vi.mock factories run.
const {
- mockUseV4Beta,
+ mockUseReadPath,
mockUseSession,
mockUseEventsTraceData,
mockTracesQuery,
mockTraceReadConfigQuery,
} = vi.hoisted(() => ({
- mockUseV4Beta: vi.fn(),
+ mockUseReadPath: vi.fn(),
mockUseSession: vi.fn(),
mockUseEventsTraceData: vi.fn(),
mockTracesQuery: vi.fn(),
mockTraceReadConfigQuery: vi.fn(),
}));
-vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
- useV4Beta: () => mockUseV4Beta(),
+vi.mock("@/src/features/events/hooks/useReadPath", () => ({
+ useReadPath: () => mockUseReadPath(),
}));
vi.mock("next-auth/react", () => ({
useSession: () => mockUseSession(),
@@ -53,7 +53,7 @@ const render = () =>
describe("useTraceDetailData (beta / events path)", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockUseV4Beta.mockReturnValue({ isBetaEnabled: true });
+ mockUseReadPath.mockReturnValue({ isV4: true });
mockUseSession.mockReturnValue({ status: "authenticated" });
mockTraceReadConfigQuery.mockReturnValue({
data: undefined,
@@ -111,7 +111,7 @@ describe("useTraceDetailData (beta / events path)", () => {
describe("useTraceDetailData endpoint routing", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockUseV4Beta.mockReturnValue({ isBetaEnabled: false });
+ mockUseReadPath.mockReturnValue({ isV4: false });
mockTraceReadConfigQuery.mockReturnValue({
data: undefined,
isLoading: false,
@@ -169,7 +169,7 @@ describe("useTraceDetailData endpoint routing", () => {
it("uses events endpoints for authenticated beta users", () => {
mockUseSession.mockReturnValue({ status: "authenticated" });
- mockUseV4Beta.mockReturnValue({ isBetaEnabled: true });
+ mockUseReadPath.mockReturnValue({ isV4: true });
render();
diff --git a/web/src/features/traces/hooks/useTraceDetailData.ts b/web/src/features/traces/hooks/useTraceDetailData.ts
index a3fc31c092..b5306a9b10 100644
--- a/web/src/features/traces/hooks/useTraceDetailData.ts
+++ b/web/src/features/traces/hooks/useTraceDetailData.ts
@@ -1,5 +1,5 @@
import { api } from "@/src/utils/api";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";
import { useSession } from "next-auth/react";
@@ -21,7 +21,7 @@ export function useTraceDetailData({
timestamp?: Date;
enabled?: boolean;
}) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const { status: sessionStatus } = useSession();
const isUnauthenticated = sessionStatus === "unauthenticated";
const traceReadConfig = api.public.traceReadConfig.useQuery(undefined, {
@@ -35,7 +35,7 @@ export function useTraceDetailData({
traceReadConfig.data?.v4WriteMode === "dual" ||
traceReadConfig.data?.v4WriteMode === "events_only";
const useEventsTraceSource =
- isBetaEnabled || (isUnauthenticated && unauthenticatedEventsReadEnabled);
+ isV4 || (isUnauthenticated && unauthenticatedEventsReadEnabled);
// Old path: traces table (beta OFF).
const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery(
diff --git a/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx b/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
index 2d3d6ead94..e1cfda2c27 100644
--- a/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
@@ -167,7 +167,7 @@ const mocks = vi.hoisted(() => ({
legacyIntegrations: ["PostHog", "Mixpanel", "Blob Storage"],
},
canToggleV4: true,
- isBetaEnabled: true,
+ isV4: true,
hasApiKeyCreateAccess: true,
canUpdateOrgSettings: true,
aiFeaturesEnabled: true,
@@ -245,17 +245,17 @@ vi.mock("@/src/features/in-app-agent/components/InAppAiAgentProvider", () => ({
}),
}));
-// The toggle row pulls in session + tRPC state via useV4Beta; stub it so the
+// The toggle row pulls in session + tRPC state via useReadPath; stub it so the
// content tests need no SessionProvider or tRPC client.
vi.mock("@/src/features/events/components/V4SidebarToggle", () => ({
V4PreviewToggleRow: () => null,
}));
// The details content reads canToggleV4 to gate the toggle section's copy.
-vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
- useV4Beta: () => ({
+vi.mock("@/src/features/events/hooks/useReadPath", () => ({
+ useReadPath: () => ({
canToggleV4: mocks.canToggleV4,
- isBetaEnabled: mocks.isBetaEnabled,
+ isV4: mocks.isV4,
}),
}));
@@ -309,7 +309,7 @@ describe("V4MigrationDetailsContent", () => {
};
mocks.migrationData.experimentInstrumentationUpgradePath = null;
mocks.canToggleV4 = true;
- mocks.isBetaEnabled = true;
+ mocks.isV4 = true;
mocks.canUpdateOrgSettings = true;
mocks.aiFeaturesEnabled = true;
mocks.migrationData.sdk = cleanSdkState();
@@ -1010,7 +1010,7 @@ describe("V4MigrationDetailsContent", () => {
});
it("renders the public key as plain text when the v4 preview is off", () => {
- mocks.isBetaEnabled = false;
+ mocks.isV4 = false;
mocks.migrationData.sdk = {
status: "legacy",
sdkUsageSeries: [
diff --git a/web/src/features/v4-migration/V4MigrationContent.tsx b/web/src/features/v4-migration/V4MigrationContent.tsx
index 91045d0f86..cee6377864 100644
--- a/web/src/features/v4-migration/V4MigrationContent.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.tsx
@@ -52,7 +52,7 @@ import {
type MigrationCountState,
type ProjectMigrationReadiness,
} from "@/src/features/v4-migration/migrationData";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { numberFormatter } from "@/src/utils/numbers";
import { formatCompactRelativeTime } from "@/src/utils/dates";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
@@ -1495,12 +1495,12 @@ export function V4MigrationDetailsContent({
projectId,
enabled: Boolean(projectId),
});
- const { canToggleV4, isBetaEnabled } = useV4Beta();
+ const { canToggleV4, isV4 } = useReadPath();
// Evidence links target the v4 events table; with the v4 preview off the
// route renders the v3 observations table, which cannot express the
// ingestionApiKey filter — the link would open an unfiltered table. Keep
// the key as plain text there instead of a misleading link.
- const evidenceProjectId = isBetaEnabled ? projectId : undefined;
+ const evidenceProjectId = isV4 ? projectId : undefined;
// PostHog is the external system here: the panel's checks resolve
// asynchronously after open, so the "how much work was shown" event can
diff --git a/web/src/features/v4-migration/V4MigrationDelayBadge.clienttest.tsx b/web/src/features/v4-migration/V4MigrationDelayBadge.clienttest.tsx
index 06ae234eea..a7a83eac4c 100644
--- a/web/src/features/v4-migration/V4MigrationDelayBadge.clienttest.tsx
+++ b/web/src/features/v4-migration/V4MigrationDelayBadge.clienttest.tsx
@@ -121,7 +121,7 @@ const mocks = vi.hoisted(() => ({
} as V4MigrationSdkState,
v4UpgradeUiEnabled: true,
forceV3: false,
- isBetaEnabled: false,
+ isV4: false,
projectId: "project-1",
openMigrationPanel: vi.fn(),
capture: vi.fn(),
@@ -136,8 +136,8 @@ vi.mock("@/src/features/v4-migration/useForceV3Experience", () => ({
useForceV3Experience: () => mocks.forceV3,
}));
-vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
- useV4Beta: () => ({ isBetaEnabled: mocks.isBetaEnabled }),
+vi.mock("@/src/features/events/hooks/useReadPath", () => ({
+ useReadPath: () => ({ isV4: mocks.isV4 }),
}));
vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
@@ -199,7 +199,7 @@ describe("V4MigrationDelayBadge", () => {
vi.clearAllMocks();
mocks.v4UpgradeUiEnabled = true;
mocks.forceV3 = false;
- mocks.isBetaEnabled = false;
+ mocks.isV4 = false;
mocks.projectId = "project-1";
setSdk("latest", [makeSdkUsageSeries({})]);
});
@@ -286,7 +286,7 @@ describe("V4MigrationDelayBadge", () => {
it("stays hidden for forced-v3 projects while they view v3", () => {
// On v3 views the legacy tables are real-time — no delay to announce.
mocks.forceV3 = true;
- mocks.isBetaEnabled = false;
+ mocks.isV4 = false;
setSdk("legacy", [outdatedSdkSeries()]);
render(<V4MigrationDelayBadge page="traces" />);
expect(screen.queryByText("New data in ~15 min")).not.toBeInTheDocument();
@@ -294,7 +294,7 @@ describe("V4MigrationDelayBadge", () => {
it("opens the partner FAQ instead of the panel for forced-v3 projects on v4", () => {
mocks.forceV3 = true;
- mocks.isBetaEnabled = true;
+ mocks.isV4 = true;
setSdk("legacy", [outdatedSdkSeries()]);
const windowOpen = vi.spyOn(window, "open").mockImplementation(() => null);
diff --git a/web/src/features/v4-migration/V4MigrationDelayBadge.tsx b/web/src/features/v4-migration/V4MigrationDelayBadge.tsx
index ffcc5cba7f..5f7691c10e 100644
--- a/web/src/features/v4-migration/V4MigrationDelayBadge.tsx
+++ b/web/src/features/v4-migration/V4MigrationDelayBadge.tsx
@@ -21,7 +21,7 @@ import {
} from "@/src/features/v4-migration/sdkVersionStatus";
import { EvaluatorMigrationDialog } from "@/src/features/v4-migration/EvaluatorMigrationDialog";
import { buildDeprecatedRulesUrl } from "@/src/features/v4-migration/evaluatorMigrationUrls";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
// The pill's description finishes expanding after 300ms (V4MigrationBadgeContent),
// so a 500ms dwell means the full text was on screen — a drive-by mouse pass
@@ -38,12 +38,12 @@ export function V4MigrationDelayBadge({
const openMigrationPanel = useOpenV4MigrationPanel();
const { project } = useQueryProject();
const forceV3 = useForceV3Experience(project?.id);
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const capture = usePostHogClientCapture();
// Forced-v3 projects still see the data-delay badge, but it points at the
// partner FAQ instead of the migration panel
- const enabled = v4UpgradeUiFlagEnabled && (!forceV3 || isBetaEnabled);
+ const enabled = v4UpgradeUiFlagEnabled && (!forceV3 || isV4);
const sdk = useProjectV4SdkData({
projectId: project?.id,
enabled: enabled && Boolean(project),
diff --git a/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsx b/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsx
index 953438e1f9..2cc535c225 100644
--- a/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsx
+++ b/web/src/features/v4-migration/V4MigrationStatusPage.clienttest.tsx
@@ -24,7 +24,7 @@ const mocks = vi.hoisted(() => ({
evalCount: 1,
lastTracePending: false,
canToggleV4: true,
- isBetaEnabled: false,
+ isV4: false,
// Cloud is bound by the dated v3 sunset; self-hosted is not.
hasDeadline: true,
}));
@@ -104,10 +104,10 @@ vi.mock("@/src/features/v4-migration/useV4UpgradeUiEnabled", () => ({
useV4UpgradeUiEnabled: () => true,
}));
-vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
- useV4Beta: () => ({
+vi.mock("@/src/features/events/hooks/useReadPath", () => ({
+ useReadPath: () => ({
canToggleV4: mocks.canToggleV4,
- isBetaEnabled: mocks.isBetaEnabled,
+ isV4: mocks.isV4,
}),
}));
@@ -169,7 +169,7 @@ describe("V4MigrationStatusPage", () => {
mocks.lastTracePending = false;
mocks.canToggleV4 = true;
mocks.hasDeadline = true;
- mocks.isBetaEnabled = false;
+ mocks.isV4 = false;
});
it("keeps the project table readable through horizontal scrolling", () => {
@@ -260,7 +260,7 @@ describe("V4MigrationStatusPage", () => {
});
it("offers v3 users a switch to the latest UI without a sunset note", () => {
- mocks.isBetaEnabled = false;
+ mocks.isV4 = false;
render(<V4MigrationStatusPage />);
@@ -274,7 +274,7 @@ describe("V4MigrationStatusPage", () => {
});
it("warns v4 users about the v3 sunset when offering the switch back", () => {
- mocks.isBetaEnabled = true;
+ mocks.isV4 = true;
render(<V4MigrationStatusPage />);
@@ -328,7 +328,7 @@ describe("V4MigrationStatusPage", () => {
});
it("drops the dated sunset from the switch-back warning when self-hosted", () => {
- mocks.isBetaEnabled = true;
+ mocks.isV4 = true;
mocks.hasDeadline = false;
render(<V4MigrationStatusPage />);
diff --git a/web/src/features/v4-migration/V4MigrationStatusPage.tsx b/web/src/features/v4-migration/V4MigrationStatusPage.tsx
index cbf45fc152..fb379b6029 100644
--- a/web/src/features/v4-migration/V4MigrationStatusPage.tsx
+++ b/web/src/features/v4-migration/V4MigrationStatusPage.tsx
@@ -41,7 +41,7 @@ import {
import { PARTNER_INTEGRATION_FAQ_URL } from "@/src/features/v4-migration/partnerIntegrationDocs";
import { V4MigrationLoadingState } from "@/src/features/v4-migration/V4MigrationLoadingState";
import { V4PreviewToggleRow } from "@/src/features/events/components/V4SidebarToggle";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
const V4_DOCS_URL = "https://langfuse.com/docs/v4";
const SDK_UPGRADE_URL =
@@ -702,7 +702,7 @@ function V4MigrationStatusPageContent() {
// Hides itself when the session cannot toggle v4 (legacy/events_only write
// mode, post-rollout auto-enrollment).
function SwitchBackSection() {
- const { canToggleV4, isBetaEnabled } = useV4Beta();
+ const { canToggleV4, isV4 } = useReadPath();
const hasDeadline = useHasV4MigrationDeadline();
if (!canToggleV4) {
@@ -712,12 +712,12 @@ function SwitchBackSection() {
return (
<div className="mt-6">
<p className="text-base font-bold">
- {isBetaEnabled
+ {isV4
? "Need to switch back to the legacy UI (v3)?"
: "Switch back to the latest UI (v4)"}
</p>
<div className="flex flex-col gap-4 pt-4">
- {isBetaEnabled && (
+ {isV4 && (
<p className="text-muted-foreground text-sm leading-relaxed">
The features powering the legacy v3 UI will be sunset{" "}
{hasDeadline
diff --git a/web/src/features/widgets/components/DashboardGrid.tsx b/web/src/features/widgets/components/DashboardGrid.tsx
index 626a4bb694..eeedbe3948 100644
--- a/web/src/features/widgets/components/DashboardGrid.tsx
+++ b/web/src/features/widgets/components/DashboardGrid.tsx
@@ -8,6 +8,7 @@ import {
type PresetPlacement,
} from "../components/PresetDashboardWidget";
import { DashboardWidget } from "@/src/features/widgets";
+import { type ResolvedReadPath } from "@/src/features/events/hooks/useReadPath";
import { type FilterState } from "@langfuse/shared";
import { useState, useEffect, useRef } from "react";
@@ -71,6 +72,7 @@ export function DashboardGrid({
canEdit,
dashboardId,
projectId,
+ readPath,
dateRange,
filterState,
onDeleteWidget,
@@ -86,6 +88,8 @@ export function DashboardGrid({
canEdit: boolean;
dashboardId: string;
projectId: string;
+ /** Resolved by the page controller — widgets must not guess the version. */
+ readPath: ResolvedReadPath;
dateRange: { from: Date; to: Date } | undefined;
filterState: FilterState;
onDeleteWidget: (tileId: string) => void;
@@ -168,6 +172,7 @@ export function DashboardGrid({
<PresetDashboardWidget
dashboardId={dashboardId}
projectId={projectId}
+ readPath={readPath}
placement={widget}
dateRange={dateRange}
filterState={filterState}
@@ -182,6 +187,7 @@ export function DashboardGrid({
<DashboardWidget
dashboardId={dashboardId}
projectId={projectId}
+ readPath={readPath}
placement={widget}
dateRange={dateRange}
filterState={filterState}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index 90a4929bdb..84962cbb73 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -62,7 +62,7 @@ import {
getChartLoadingProgress,
getChartLoadingStateProps,
} from "@/src/features/widgets/chart-library/chartLoadingStateUtils";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { type ResolvedReadPath } from "@/src/features/events/hooks/useReadPath";
import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";
import { CopyWidgetDialog } from "@/src/features/widgets/components/CopyWidgetDialog";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
@@ -81,6 +81,7 @@ export interface WidgetPlacement {
export function DashboardWidget({
projectId,
dashboardId,
+ readPath,
placement,
dateRange,
filterState,
@@ -93,6 +94,8 @@ export function DashboardWidget({
}: {
projectId: string;
dashboardId: string;
+ /** Resolved by the page controller — the widget must not guess the version. */
+ readPath: ResolvedReadPath;
placement: WidgetPlacement;
dateRange: { from: Date; to: Date } | undefined;
filterState: FilterState;
@@ -119,7 +122,7 @@ export function DashboardWidget({
const router = useRouter();
const utils = api.useUtils();
const capture = usePostHogClientCapture();
- const { isBetaEnabled } = useV4Beta();
+ const isV4 = readPath === "v4";
const widget = api.dashboardWidgets.get.useQuery(
{
widgetId: placement.widgetId,
@@ -139,7 +142,7 @@ export function DashboardWidget({
filters: widget.data?.filters ?? [],
},
persistedMinVersion: widget.data?.minVersion,
- newestReadableVersion: isBetaEnabled ? "v2" : "v1",
+ newestReadableVersion: isV4 ? "v2" : "v1",
});
const hasRbacCUDAccess = useHasProjectAccess({
projectId,
@@ -271,11 +274,11 @@ export function DashboardWidget({
},
queryId: `${schedulerId ?? `dashboard-widget:${placement.id}`}:execute`,
meta: {
- silentHttpCodes: [422],
+ silentHttpCodes: [412, 422],
},
refreshKey: retryCount,
useSSE: shouldUseWidgetSSE({
- isV4Enabled: isBetaEnabled,
+ isV4Enabled: isV4,
version: metricsVersion,
}),
enabled:
@@ -289,7 +292,7 @@ export function DashboardWidget({
errorMessage: queryResult.error,
});
const usesBackendProgress = shouldUseWidgetSSE({
- isV4Enabled: isBetaEnabled,
+ isV4Enabled: isV4,
version: metricsVersion,
});
const loadingStateLayout =
@@ -476,9 +479,9 @@ export function DashboardWidget({
view as z.infer<typeof views>,
mergedFilters,
dateRange,
- isBetaEnabled ? "v4" : "v3",
+ readPath,
);
- }, [projectId, widget.data, filterState, dateRange, isBetaEnabled]);
+ }, [projectId, widget.data, filterState, dateRange, readPath]);
const handleViewAsTable = () => {
if (!tableView) return;
diff --git a/web/src/features/widgets/components/InlineWidget.tsx b/web/src/features/widgets/components/InlineWidget.tsx
index d297787e7c..900773cd4d 100644
--- a/web/src/features/widgets/components/InlineWidget.tsx
+++ b/web/src/features/widgets/components/InlineWidget.tsx
@@ -22,7 +22,7 @@ import {
type WidgetChartConfig,
} from "@/src/features/widgets/utils";
import { isTimeSeriesChart } from "@/src/features/widgets/chart-library/utils";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { cn } from "@/src/utils/tailwind";
// ============================================================================
@@ -129,7 +129,9 @@ export function WidgetContent({
entityDimensionLabelMap,
hideXAxisLabels,
}: WidgetContentProps) {
- const { isBetaEnabled } = useV4Beta();
+ // Transport-only: `version` is a prop here, so an unresolved session can
+ // never change WHAT is queried — only whether it streams (SSE) or not.
+ const { isV4 } = useReadPath();
const [retryCount, setRetryCount] = useState(0);
const handleRetry = useCallback(() => {
@@ -151,11 +153,11 @@ export function WidgetContent({
},
queryId: schedulerId,
meta: {
- silentHttpCodes: [422],
+ silentHttpCodes: [412, 422],
},
refreshKey: retryCount,
useSSE: shouldUseWidgetSSE({
- isV4Enabled: isBetaEnabled,
+ isV4Enabled: isV4,
version,
}),
enabled: !isExternalLoading,
@@ -317,7 +319,7 @@ export function WidgetContent({
});
const usesBackendProgress = shouldUseWidgetSSE({
- isV4Enabled: isBetaEnabled,
+ isV4Enabled: isV4,
version,
});
diff --git a/web/src/features/widgets/components/PresetDashboardWidget.tsx b/web/src/features/widgets/components/PresetDashboardWidget.tsx
index d1b9a4998b..769c939af0 100644
--- a/web/src/features/widgets/components/PresetDashboardWidget.tsx
+++ b/web/src/features/widgets/components/PresetDashboardWidget.tsx
@@ -9,7 +9,7 @@ import {
import { type FilterState } from "@langfuse/shared";
import { type ViewVersion } from "@langfuse/shared/query";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { type ResolvedReadPath } from "@/src/features/events/hooks/useReadPath";
import { findClosestDashboardInterval } from "@/src/utils/date-range-utils";
import {
getHomePreset,
@@ -46,6 +46,7 @@ export interface PresetPlacement {
export function PresetDashboardWidget({
projectId,
dashboardId,
+ readPath,
placement,
dateRange,
filterState,
@@ -58,6 +59,8 @@ export function PresetDashboardWidget({
}: {
projectId: string;
dashboardId: string;
+ /** Resolved by the page controller — the card must not guess the version. */
+ readPath: ResolvedReadPath;
placement: PresetPlacement;
dateRange: { from: Date; to: Date } | undefined;
filterState: FilterState;
@@ -78,8 +81,7 @@ export function PresetDashboardWidget({
*/
onDuplicatePreset?: (anchor: PresetPlacement) => void;
}) {
- const { isBetaEnabled } = useV4Beta();
- const metricsVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";
+ const metricsVersion: ViewVersion = readPath === "v4" ? "v2" : "v1";
// Presets on project-owned dashboards (e.g. a clone of the curated Home)
// can be moved/removed, but their content stays fixed until extended into a
diff --git a/web/src/features/widgets/components/SelectWidgetDialog.tsx b/web/src/features/widgets/components/SelectWidgetDialog.tsx
index 26cd2f6c3b..b72ff5ed03 100644
--- a/web/src/features/widgets/components/SelectWidgetDialog.tsx
+++ b/web/src/features/widgets/components/SelectWidgetDialog.tsx
@@ -29,7 +29,7 @@ import {
getSuggestedHomePresetIds,
HOME_PRESET_METADATA,
} from "@/src/features/dashboard/components/home-preset-registry";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import { InAppAgentWidgetComposer } from "@/src/features/in-app-agent/components/InAppAgentWidgetComposer";
@@ -138,8 +138,8 @@ export function SelectWidgetDialog({
// Suggestions obey the same view allowlist the widget editor uses for new
// definitions, so v4 users are never offered a v3 trace-based widget.
// Legacy trace widgets stay listed and editable under /widgets. (LFE-14444)
- const { isBetaEnabled, isInitializing } = useV4Beta();
- const suggestedVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";
+ const { isV4, isResolved } = useReadPath();
+ const suggestedVersion: ViewVersion = isV4 ? "v2" : "v1";
const allProjectWidgets = widgets.data?.widgets ?? [];
const projectWidgets = allProjectWidgets.filter((widget) =>
isSuggestedWidgetView(widget.view, suggestedVersion),
@@ -173,9 +173,9 @@ export function SelectWidgetDialog({
</DialogHeader>
<DialogBody>
- {/* isInitializing: an unresolved session reads as v1, which would
+ {/* !isResolved: an unresolved session reads as v3, which would
briefly offer the unfiltered list to a v4 user. */}
- {widgets.isPending || isInitializing ? (
+ {widgets.isPending || !isResolved ? (
<div className="py-8 text-center">Loading widgets...</div>
) : widgets.isError ? (
<div className="text-destructive py-8 text-center">
diff --git a/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx b/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx
index 6282d2821c..5ce5f21bbe 100644
--- a/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx
+++ b/web/src/features/widgets/components/WidgetForm.observationNameOptions.clienttest.tsx
@@ -33,8 +33,8 @@ vi.mock("@/src/utils/api", () => ({
}));
// Force the v1 path, which sources the observation-name picker from generations.
-vi.mock("@/src/features/events/hooks/useV4Beta", () => ({
- useV4Beta: () => ({ isBetaEnabled: false }),
+vi.mock("@/src/features/events/hooks/useReadPath", () => ({
+ useReadPath: () => ({ isV4: false }),
}));
vi.mock("next/router", () => ({
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 0ec6832077..8f0e511ca4 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -50,7 +50,7 @@ import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
import { type z } from "zod";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { Input } from "@/src/components/ui/input";
import startCase from "lodash/startCase";
import { DatePickerWithRange } from "@/src/components/date-picker";
@@ -222,13 +222,13 @@ export function WidgetForm({
onSave: (widgetData: WidgetSavePayload) => void;
widgetId?: string;
}) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// The initial widget's persisted version is a local hint frozen at mount.
// The resolver and live viewVersion additionally derive v2 from the current
// form shape; the server derives the value that gets persisted.
const baseMinVersion = deriveWidgetBaseMinVersion(initialValues);
- const activeVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";
+ const activeVersion: ViewVersion = isV4 ? "v2" : "v1";
// The auto-suggestions change on every keystroke; a ref keeps the resolver
// closure from being rebuilt on each one (the filled name/description do not
@@ -581,7 +581,7 @@ export function WidgetForm({
},
{
trpc: { context: { skipBatch: true } },
- meta: { silentHttpCodes: [422] },
+ meta: { silentHttpCodes: [412, 422] },
enabled: queryValidation.valid,
},
);
@@ -871,12 +871,12 @@ export function WidgetForm({
<CardHeader>
<div className="flex items-start justify-between gap-3">
<CardTitle>Widget Configuration</CardTitle>
- {!widgetId && isBetaEnabled && (
+ {!widgetId && isV4 && (
<WidgetImporter
projectId={projectId}
viewVersion={viewVersion}
dateRange={dateRange}
- isBetaEnabled={isBetaEnabled}
+ isV4={isV4}
onImport={handleImportedWidget}
/>
)}
@@ -886,7 +886,7 @@ export function WidgetForm({
</CardDescription>
</CardHeader>
<CardContent className="space-y-4 overflow-y-auto">
- {isBetaEnabled && selectedView === "traces" && (
+ {isV4 && selectedView === "traces" && (
<Alert
variant="default"
className="border-yellow-500/50 bg-yellow-50 dark:bg-yellow-950/20"
diff --git a/web/src/features/widgets/components/WidgetImporter.clienttest.tsx b/web/src/features/widgets/components/WidgetImporter.clienttest.tsx
index 63fb844425..9bb183a246 100644
--- a/web/src/features/widgets/components/WidgetImporter.clienttest.tsx
+++ b/web/src/features/widgets/components/WidgetImporter.clienttest.tsx
@@ -56,7 +56,7 @@ describe("runImport", () => {
await runImport({
file: fileFor({ ...baseWidget, filters: [] }),
optionSets: { observationLevels: [] },
- isBetaEnabled: false,
+ isV4: false,
onImport,
});
@@ -71,7 +71,7 @@ describe("runImport", () => {
await runImport({
file: { text: async () => "not json" } as File,
optionSets: { observationLevels: [] },
- isBetaEnabled: false,
+ isV4: false,
onImport,
});
@@ -99,7 +99,7 @@ describe("runImport", () => {
],
}),
optionSets: { observationLevels: [], environmentValues: [] },
- isBetaEnabled: false,
+ isV4: false,
onImport,
});
diff --git a/web/src/features/widgets/components/WidgetImporter.tsx b/web/src/features/widgets/components/WidgetImporter.tsx
index 2f52b2e37a..377d7aa44e 100644
--- a/web/src/features/widgets/components/WidgetImporter.tsx
+++ b/web/src/features/widgets/components/WidgetImporter.tsx
@@ -24,13 +24,13 @@ export const WidgetImporter = ({
projectId,
viewVersion,
dateRange,
- isBetaEnabled,
+ isV4,
onImport,
}: {
projectId: string;
viewVersion: ViewVersion;
dateRange: { from: Date; to: Date } | undefined;
- isBetaEnabled: boolean;
+ isV4: boolean;
onImport: (snapshot: ImportedWidgetFormSnapshot) => void;
}) => {
const importInputRef = useRef<HTMLInputElement>(null);
@@ -53,7 +53,7 @@ export const WidgetImporter = ({
dateRange,
});
- await runImport({ file, optionSets, isBetaEnabled, onImport });
+ await runImport({ file, optionSets, isV4, onImport });
};
return (
@@ -176,14 +176,14 @@ function buildImportOptionSets(params: {
async function runImport(params: {
file: File;
optionSets: WidgetImportOptionSets;
- isBetaEnabled: boolean;
+ isV4: boolean;
onImport: (snapshot: ImportedWidgetFormSnapshot) => void;
}): Promise<void> {
try {
const result = await importWidgetFile({
file: params.file,
optionSets: params.optionSets,
- isBetaEnabled: params.isBetaEnabled,
+ isV4: params.isV4,
});
params.onImport(result.snapshot);
diff --git a/web/src/features/widgets/utils.ts b/web/src/features/widgets/utils.ts
index 684d3aceb9..9ab5fde0d6 100644
--- a/web/src/features/widgets/utils.ts
+++ b/web/src/features/widgets/utils.ts
@@ -233,10 +233,8 @@ export function buildWidgetDescription({
* remains excluded from the public `viewsV2` API enum. Existing trace widgets
* are still supported by the internal events-backed v2 query declaration.
*/
-export function getDefaultView(
- isBetaEnabled: boolean,
-): "traces" | "observations" {
- return isBetaEnabled ? "observations" : "traces";
+export function getDefaultView(isV4: boolean): "traces" | "observations" {
+ return isV4 ? "observations" : "traces";
}
/**
diff --git a/web/src/features/widgets/utils/import-export-utils.clienttest.ts b/web/src/features/widgets/utils/import-export-utils.clienttest.ts
index 44badfdd3d..46b0124408 100644
--- a/web/src/features/widgets/utils/import-export-utils.clienttest.ts
+++ b/web/src/features/widgets/utils/import-export-utils.clienttest.ts
@@ -148,7 +148,7 @@ describe("parseAndNormalizeImportedWidget", () => {
optionSets: {
observationLevels: [],
},
- isBetaEnabled: true,
+ isV4: true,
});
expect(result.snapshot.selectedView).toBe("traces");
@@ -171,7 +171,7 @@ describe("parseAndNormalizeImportedWidget", () => {
chartConfig: { type: "VERTICAL_BAR" },
filters: [rootFilter],
},
- isBetaEnabled: false,
+ isV4: false,
});
expect(result.widget.minVersion).toBe(1);
@@ -199,7 +199,7 @@ describe("parseAndNormalizeImportedWidget", () => {
}),
} as File,
optionSets: { observationLevels: [] },
- isBetaEnabled: true,
+ isV4: true,
});
expect(result.snapshot).toMatchObject({
@@ -227,7 +227,7 @@ describe("parseAndNormalizeImportedWidget", () => {
optionSets: {
observationLevels: [],
},
- isBetaEnabled: false,
+ isV4: false,
});
expect(result.snapshot.widgetName).toBe("Imported widget");
@@ -246,7 +246,7 @@ describe("parseAndNormalizeImportedWidget", () => {
optionSets: {
observationLevels: [],
},
- isBetaEnabled: false,
+ isV4: false,
}),
).rejects.toThrow();
});
@@ -286,21 +286,21 @@ describe("parsePastedWidget", () => {
};
it("ignores non-JSON text", () => {
- expect(parsePastedWidget("hello world", { isBetaEnabled: false })).toEqual({
+ expect(parsePastedWidget("hello world", { isV4: false })).toEqual({
status: "not-widget",
});
});
it("ignores JSON without the widget envelope", () => {
expect(
- parsePastedWidget(JSON.stringify(baseWidget), { isBetaEnabled: false }),
+ parsePastedWidget(JSON.stringify(baseWidget), { isV4: false }),
).toEqual({ status: "not-widget" });
});
it("parses an enveloped widget export", () => {
const result = parsePastedWidget(
JSON.stringify(buildWidgetExport(baseWidget)),
- { isBetaEnabled: false },
+ { isV4: false },
);
expect(result.status).toBe("widget");
@@ -316,7 +316,7 @@ describe("parsePastedWidget", () => {
...buildWidgetExport(baseWidget),
version: WIDGET_FILE_FORMAT_VERSION + 1,
}),
- { isBetaEnabled: false },
+ { isV4: false },
);
expect(result.status).toBe("invalid");
@@ -332,7 +332,7 @@ describe("parsePastedWidget", () => {
// chartConfig.type no longer matches chartType
chartConfig: { type: "PIE" },
}),
- { isBetaEnabled: false },
+ { isV4: false },
);
expect(result.status).toBe("invalid");
diff --git a/web/src/features/widgets/utils/import-export-utils.ts b/web/src/features/widgets/utils/import-export-utils.ts
index 5fa9a69119..2dfef8060e 100644
--- a/web/src/features/widgets/utils/import-export-utils.ts
+++ b/web/src/features/widgets/utils/import-export-utils.ts
@@ -467,7 +467,7 @@ function normalizeImportedWidgetVersion(widget: WidgetImport): WidgetImport {
export function parseImportedWidgetJson(params: {
parsedJson: unknown;
optionSets?: WidgetImportOptionSets;
- isBetaEnabled: boolean;
+ isV4: boolean;
}): { widget: WidgetImport; removedValues: boolean; removedFilters: boolean } {
const allowedValuesByColumn = params.optionSets
? buildWidgetImportAllowedValues(params.optionSets, params.parsedJson)
@@ -493,7 +493,7 @@ export function parseImportedWidgetJson(params: {
filters: normalizedWidget.filters,
},
baseMinVersion: normalizedWidget.minVersion ?? 1,
- activeVersion: params.isBetaEnabled ? "v2" : "v1",
+ activeVersion: params.isV4 ? "v2" : "v1",
});
validateImportedWidget({
@@ -507,7 +507,7 @@ export function parseImportedWidgetJson(params: {
export async function importWidgetFile(params: {
file: File;
optionSets: WidgetImportOptionSets;
- isBetaEnabled: boolean;
+ isV4: boolean;
}): Promise<ImportedWidgetResult> {
const rawContent = await params.file.text();
const parsedJson: unknown = JSON.parse(rawContent);
@@ -515,7 +515,7 @@ export async function importWidgetFile(params: {
const { widget, removedValues, removedFilters } = parseImportedWidgetJson({
parsedJson,
optionSets: params.optionSets,
- isBetaEnabled: params.isBetaEnabled,
+ isV4: params.isV4,
});
return {
@@ -538,7 +538,7 @@ export type PastedWidgetParseResult =
*/
export function parsePastedWidget(
text: string,
- params: { isBetaEnabled: boolean },
+ params: { isV4: boolean },
): PastedWidgetParseResult {
let parsedJson: unknown;
try {
@@ -565,7 +565,7 @@ export function parsePastedWidget(
try {
const { widget, removedFilters } = parseImportedWidgetJson({
parsedJson,
- isBetaEnabled: params.isBetaEnabled,
+ isV4: params.isV4,
});
return { status: "widget", widget, removedFilters };
} catch {
diff --git a/web/src/hooks/useDashboardFilterOptions.ts b/web/src/hooks/useDashboardFilterOptions.ts
index 4b49c648cf..caafe7af2b 100644
--- a/web/src/hooks/useDashboardFilterOptions.ts
+++ b/web/src/hooks/useDashboardFilterOptions.ts
@@ -9,13 +9,13 @@ import {
type UseDashboardFilterOptionsParams = {
projectId: string;
- isBetaEnabled: boolean;
+ isV4: boolean;
timeRange: TimeRange;
};
export function useDashboardFilterOptions({
projectId,
- isBetaEnabled,
+ isV4,
timeRange,
}: UseDashboardFilterOptionsParams) {
const commonQueryOptions = {
@@ -86,28 +86,24 @@ export function useDashboardFilterOptions({
// a "Bad Request" toast.
const traceFilterOptions = api.traces.filterOptions.useQuery(
{ projectId, timestampFilter: traceTimestampFilter },
- { ...commonQueryOptions, enabled: Boolean(projectId) && !isBetaEnabled },
+ { ...commonQueryOptions, enabled: Boolean(projectId) && !isV4 },
);
const eventsFilterOptions = api.events.filterOptions.useQuery(
{ projectId, startTimeFilter },
- { ...commonQueryOptions, enabled: Boolean(projectId) && isBetaEnabled },
+ { ...commonQueryOptions, enabled: Boolean(projectId) && isV4 },
);
const nameOptions = useMemo(
() =>
- isBetaEnabled
+ isV4
? normalizeSingleValueOptions(eventsFilterOptions.data?.traceName)
: normalizeSingleValueOptions(traceFilterOptions.data?.name),
- [
- isBetaEnabled,
- eventsFilterOptions.data?.traceName,
- traceFilterOptions.data?.name,
- ],
+ [isV4, eventsFilterOptions.data?.traceName, traceFilterOptions.data?.name],
);
const tagsOptions = sortOptionValues(
- isBetaEnabled
+ isV4
? (eventsFilterOptions.data?.traceTags ?? [])
: (traceFilterOptions.data?.tags ?? []),
);
diff --git a/web/src/pages/api/dashboard/execute-query-stream.ts b/web/src/pages/api/dashboard/execute-query-stream.ts
index a6a0dd9d76..25154ac2fa 100644
--- a/web/src/pages/api/dashboard/execute-query-stream.ts
+++ b/web/src/pages/api/dashboard/execute-query-stream.ts
@@ -41,10 +41,12 @@ function formatSSEEvent(event: SSEEvent): string {
}
}
+// `version` is required on purpose — see dashboard.executeQuery: an implicit
+// v1 default let unresolved-session clients silently pick the read path.
const inputSchema = z.object({
projectId: z.string(),
query: customQuery,
- version: viewVersions.optional().default("v1"),
+ version: viewVersions,
});
export default async function handler(
diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
index ddeb7308a3..959527d9ea 100644
--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
@@ -1,6 +1,9 @@
import { useRouter } from "next/router";
import { api } from "@/src/utils/api";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import {
+ useReadPath,
+ type ResolvedReadPath,
+} from "@/src/features/events/hooks/useReadPath";
import { useDashboardFilterOptions } from "@/src/hooks/useDashboardFilterOptions";
import Page from "@/src/components/layouts/page";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
@@ -98,7 +101,33 @@ function placementNextTo(anchor: DashboardPlacement) {
};
}
+// Controller: no widget query may fire before the session resolves the v3/v4
+// read path — an unresolved session used to read as v3 and fire a wave of
+// legacy-table queries that was thrown away once the session landed.
export default function DashboardDetail() {
+ const router = useRouter();
+ const { projectId } = router.query as { projectId: string };
+ const { readPath } = useReadPath();
+ if (readPath === "unknown") {
+ return (
+ <Page
+ withPadding
+ scrollable
+ headerProps={{
+ title: "Dashboard",
+ breadcrumb: [
+ { name: "Dashboards", href: `/project/${projectId}/dashboards` },
+ ],
+ }}
+ >
+ <NoDataOrLoading isLoading />
+ </Page>
+ );
+ }
+ return <DashboardDetailView readPath={readPath} />;
+}
+
+function DashboardDetailView({ readPath }: { readPath: ResolvedReadPath }) {
const router = useRouter();
const utils = api.useUtils();
const capture = usePostHogClientCapture();
@@ -110,7 +139,7 @@ export default function DashboardDetail() {
};
const lookbackLimit = useEntitlementLimit("data-access-days");
- const { isBetaEnabled } = useV4Beta();
+ const isV4 = readPath === "v4";
// Fetch dashboard data
const dashboard = api.dashboard.getDashboard.useQuery({
@@ -558,7 +587,7 @@ export default function DashboardDetail() {
);
return;
}
- const parsed = parsePastedWidget(text, { isBetaEnabled });
+ const parsed = parsePastedWidget(text, { isV4 });
if (parsed.status === "not-widget") {
const preset = parsePastedPreset(text);
if (preset.status === "preset") {
@@ -588,13 +617,7 @@ export default function DashboardDetail() {
}
await handleParsedWidgetPaste(parsed, source, anchor);
},
- [
- capture,
- dashboardId,
- handleParsedWidgetPaste,
- handlePastedPreset,
- isBetaEnabled,
- ],
+ [capture, dashboardId, handleParsedWidgetPaste, handlePastedPreset, isV4],
);
// Cmd/Ctrl+V on the dashboard pastes a copied widget. Only intercepts when
@@ -614,7 +637,7 @@ export default function DashboardDetail() {
}
const text = event.clipboardData?.getData("text/plain");
if (!text) return;
- const parsed = parsePastedWidget(text, { isBetaEnabled });
+ const parsed = parsePastedWidget(text, { isV4 });
if (parsed.status === "not-widget") {
const preset = parsePastedPreset(text);
// Neither widget nor preset payload: leave the event alone (silent,
@@ -641,7 +664,7 @@ export default function DashboardDetail() {
return () => document.removeEventListener("paste", onPaste);
}, [
hasCUDAccess,
- isBetaEnabled,
+ isV4,
handleParsedWidgetPaste,
handlePastedPreset,
capture,
@@ -652,8 +675,8 @@ export default function DashboardDetail() {
// holding a pasteable payload, where the browser lets us check silently.
const [isDashboardMenuOpen, setIsDashboardMenuOpen] = useState(false);
const isPasteablePayload = useCallback(
- (text: string) => isPasteablePlacementPayload(text, { isBetaEnabled }),
- [isBetaEnabled],
+ (text: string) => isPasteablePlacementPayload(text, { isV4 }),
+ [isV4],
);
const clipboardProbe = useClipboardWidgetProbe(
isDashboardMenuOpen && hasCUDAccess,
@@ -792,7 +815,7 @@ export default function DashboardDetail() {
async (file: File) => {
const text = await file.text();
- const dashboardResult = parseDashboardImport(text, { isBetaEnabled });
+ const dashboardResult = parseDashboardImport(text, { isV4 });
if (dashboardResult.status === "dashboard") {
await handleDashboardImport(dashboardResult.dashboard);
return;
@@ -811,7 +834,7 @@ export default function DashboardDetail() {
return;
}
- const widgetResult = parsePastedWidget(text, { isBetaEnabled });
+ const widgetResult = parsePastedWidget(text, { isV4 });
if (widgetResult.status === "not-widget") {
const preset = parsePastedPreset(text);
if (preset.status === "preset") {
@@ -842,7 +865,7 @@ export default function DashboardDetail() {
await handleParsedWidgetPaste(widgetResult, "drop");
},
[
- isBetaEnabled,
+ isV4,
handleDashboardImport,
handleParsedWidgetPaste,
handlePastedPreset,
@@ -900,7 +923,7 @@ export default function DashboardDetail() {
const { nameOptions, tagsOptions } = useDashboardFilterOptions({
projectId,
- isBetaEnabled,
+ isV4,
timeRange,
});
@@ -1375,6 +1398,7 @@ export default function DashboardDetail() {
<div>
<DashboardGrid
key={gridResetKey}
+ readPath={readPath}
widgets={dashboardDefinition.widgets}
onChange={(updatedWidgets) => {
if (isLockedEditable) {
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index 2a18480e95..ad4d4a47bb 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -27,7 +27,10 @@ import {
convertSelectedEnvironmentsToFilter,
useEnvironmentFilter,
} from "@/src/hooks/useEnvironmentFilter";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import {
+ useReadPath,
+ type ResolvedReadPath,
+} from "@/src/features/events/hooks/useReadPath";
import { type ViewVersion } from "@langfuse/shared/query";
import { useEnvironmentFilterOptionsCache } from "@/src/hooks/use-environment-filter-options-cache";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
@@ -45,14 +48,30 @@ import { Button } from "@/src/components/ui/button";
import { DashboardGrid } from "@/src/features/widgets/components/DashboardGrid";
import { HomeDashboardSelect } from "@/src/features/dashboard/components/HomeDashboardSelect";
+// Controller: no widget query may fire before the session resolves the v3/v4
+// read path — an unresolved session used to read as v3, fire a full wave of
+// legacy-table queries, then re-run the whole dashboard on v4 once the
+// session landed (via the scheduler reset key below).
export default function Dashboard() {
+ const { readPath } = useReadPath();
+ if (readPath === "unknown") {
+ return (
+ <Page withPadding scrollable headerProps={{ title: "Home" }}>
+ <NoDataOrLoading isLoading />
+ </Page>
+ );
+ }
+ return <HomeDashboard readPath={readPath} />;
+}
+
+function HomeDashboard({ readPath }: { readPath: ResolvedReadPath }) {
const router = useRouter();
const utils = api.useUtils();
const capture = usePostHogClientCapture();
const projectId = router.query.projectId as string;
const { timeRange, setTimeRange } = useDashboardDateRange();
- const { isBetaEnabled } = useV4Beta();
- const metricsVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";
+ const isV4 = readPath === "v4";
+ const metricsVersion: ViewVersion = isV4 ? "v2" : "v1";
const absoluteTimeRange = useMemo(
() => toAbsoluteTimeRange(timeRange) ?? undefined,
@@ -69,7 +88,7 @@ export default function Dashboard() {
const { nameOptions, tagsOptions } = useDashboardFilterOptions({
projectId,
- isBetaEnabled,
+ isV4,
timeRange,
});
@@ -381,6 +400,7 @@ export default function Dashboard() {
canEdit={false}
dashboardId={dashboardId}
projectId={projectId}
+ readPath={readPath}
dateRange={absoluteTimeRange}
filterState={gridFilterState}
onDeleteWidget={() => undefined}
diff --git a/web/src/pages/project/[projectId]/observations/index.tsx b/web/src/pages/project/[projectId]/observations/index.tsx
index c9ac0ecff1..e48b40feff 100644
--- a/web/src/pages/project/[projectId]/observations/index.tsx
+++ b/web/src/pages/project/[projectId]/observations/index.tsx
@@ -7,7 +7,7 @@ import {
getTracingTabs,
TRACING_TABS,
} from "@/src/features/navigation/utils/tracing-tabs";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import ObservationsEventsTable from "@/src/features/events/components/EventsTable";
import { useQueryProject } from "@/src/features/projects/hooks";
import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDelayBadge";
@@ -15,7 +15,7 @@ import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDe
export default function Generations() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const { isBetaEnabled, isInitializing } = useV4Beta();
+ const { isV4, isResolved } = useReadPath();
const { project } = useQueryProject();
// Check if the user has tracing configured
@@ -53,7 +53,7 @@ export default function Generations() {
href: "https://langfuse.com/docs/observability/data-model",
},
tabsProps:
- isBetaEnabled || isInitializing
+ isV4 || !isResolved
? undefined
: {
tabs: getTracingTabs(projectId),
@@ -65,14 +65,14 @@ export default function Generations() {
{/* Show onboarding screen if user has no traces */}
{showOnboarding ? (
<TracesOnboarding projectId={projectId} />
- ) : isInitializing ? (
+ ) : !isResolved ? (
<>
{/* Wait for the beta flag before mounting either table. Otherwise the
legacy table can briefly mount, restore a v3 saved view, and
promote its viewId into the URL before the correct mode
resolves. */}
</>
- ) : isBetaEnabled ? (
+ ) : isV4 ? (
<ObservationsEventsTable
projectId={projectId}
showControlsInPageHeader
diff --git a/web/src/pages/project/[projectId]/sessions/[sessionId].tsx b/web/src/pages/project/[projectId]/sessions/[sessionId].tsx
index 66ceee57f8..c95747bc0a 100644
--- a/web/src/pages/project/[projectId]/sessions/[sessionId].tsx
+++ b/web/src/pages/project/[projectId]/sessions/[sessionId].tsx
@@ -1,5 +1,5 @@
import { SessionEventsPage, SessionPage } from "@/src/components/session";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import {
RouteParamsPendingFallback,
useReadyRouteParams,
@@ -7,13 +7,13 @@ import {
export default function Session() {
const route = useReadyRouteParams(["projectId", "sessionId"]);
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
if (!route.ready) return <RouteParamsPendingFallback />;
const { projectId, sessionId } = route.params;
- return isBetaEnabled ? (
+ return isV4 ? (
<SessionEventsPage sessionId={sessionId} projectId={projectId} />
) : (
<SessionPage sessionId={sessionId} projectId={projectId} />
diff --git a/web/src/pages/project/[projectId]/sessions/index.tsx b/web/src/pages/project/[projectId]/sessions/index.tsx
index 0672b31b37..21e0dca5e7 100644
--- a/web/src/pages/project/[projectId]/sessions/index.tsx
+++ b/web/src/pages/project/[projectId]/sessions/index.tsx
@@ -4,17 +4,17 @@ import SessionsTable from "@/src/components/table/use-cases/sessions";
import Page from "@/src/components/layouts/page";
import { SessionsOnboarding } from "@/src/components/onboarding/SessionsOnboarding";
import { api } from "@/src/utils/api";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
export default function Sessions() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const { data: hasAnySession, isLoading } = api.sessions.hasAny.useQuery(
{ projectId },
{
- enabled: !!projectId && !isBetaEnabled,
+ enabled: !!projectId && !isV4,
trpc: {
context: {
skipBatch: true,
@@ -28,7 +28,7 @@ export default function Sessions() {
api.sessions.hasAnyFromEvents.useQuery(
{ projectId },
{
- enabled: !!projectId && isBetaEnabled,
+ enabled: !!projectId && isV4,
trpc: {
context: {
skipBatch: true,
@@ -38,8 +38,8 @@ export default function Sessions() {
},
);
- const hasSessions = isBetaEnabled ? hasAnySessionFromEvents : hasAnySession;
- const isLoadingSessions = isBetaEnabled ? isLoadingFromEvents : isLoading;
+ const hasSessions = isV4 ? hasAnySessionFromEvents : hasAnySession;
+ const isLoadingSessions = isV4 ? isLoadingFromEvents : isLoading;
const showOnboarding = !isLoadingSessions && !hasSessions;
return (
@@ -75,7 +75,7 @@ export default function Sessions() {
) : (
<SessionsTable
projectId={projectId}
- isBetaEnabled={isBetaEnabled}
+ isV4={isV4}
showControlsInPageHeader
/>
)}
diff --git a/web/src/pages/project/[projectId]/traces/index.tsx b/web/src/pages/project/[projectId]/traces/index.tsx
index be7320b7fc..30e62aec5a 100644
--- a/web/src/pages/project/[projectId]/traces/index.tsx
+++ b/web/src/pages/project/[projectId]/traces/index.tsx
@@ -7,7 +7,7 @@ import {
getTracingTabs,
TRACING_TABS,
} from "@/src/features/navigation/utils/tracing-tabs";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import ObservationsEventsTable from "@/src/features/events/components/EventsTable";
import { useQueryProject } from "@/src/features/projects/hooks";
import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDelayBadge";
@@ -15,7 +15,7 @@ import { V4MigrationDelayBadge } from "@/src/features/v4-migration/V4MigrationDe
export default function Traces() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const { isBetaEnabled, isInitializing } = useV4Beta();
+ const { isV4, isResolved } = useReadPath();
const { project } = useQueryProject();
// Check if the user has tracing configured
@@ -81,7 +81,7 @@ export default function Traces() {
href: "https://langfuse.com/docs/observability/data-model",
},
tabsProps:
- isBetaEnabled || isInitializing
+ isV4 || !isResolved
? undefined
: {
tabs: getTracingTabs(projectId),
@@ -89,14 +89,14 @@ export default function Traces() {
},
}}
>
- {isInitializing ? (
+ {!isResolved ? (
<>
{/* Wait for the beta flag before mounting either table. Otherwise the
legacy table can briefly mount, restore a v3 saved view, and
promote its viewId into the URL before the correct mode
resolves. */}
</>
- ) : isBetaEnabled ? (
+ ) : isV4 ? (
<ObservationsEventsTable
projectId={projectId}
showControlsInPageHeader
diff --git a/web/src/pages/project/[projectId]/users/[userId].tsx b/web/src/pages/project/[projectId]/users/[userId].tsx
index a908afb36d..8b0fb45cae 100644
--- a/web/src/pages/project/[projectId]/users/[userId].tsx
+++ b/web/src/pages/project/[projectId]/users/[userId].tsx
@@ -15,7 +15,7 @@ import { Badge } from "@/src/components/ui/badge";
import { ActionButton } from "@/src/components/ActionButton";
import { LayoutDashboard } from "lucide-react";
import Page from "@/src/components/layouts/page";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { ObservationsEventsTable } from "@/src/features/events/components";
const tabs = ["Traces", "Sessions", "Scores"] as const;
@@ -39,14 +39,14 @@ function UserDetailPage({
userId: string;
}) {
const router = useRouter();
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
const userV3 = api.users.byId.useQuery(
{
projectId: projectId,
userId,
},
- { enabled: Boolean(projectId) && Boolean(userId) && !isBetaEnabled },
+ { enabled: Boolean(projectId) && Boolean(userId) && !isV4 },
);
const userV4 = api.users.byIdFromEvents.useQuery(
@@ -54,10 +54,10 @@ function UserDetailPage({
projectId: projectId,
userId,
},
- { enabled: Boolean(projectId) && Boolean(userId) && isBetaEnabled },
+ { enabled: Boolean(projectId) && Boolean(userId) && isV4 },
);
- const user = isBetaEnabled ? userV4 : userV3;
+ const user = isV4 ? userV4 : userV3;
const [currentTab, setCurrentTab] = useQueryParam(
"tab",
@@ -135,7 +135,7 @@ function UserDetailPage({
Active:{" "}
{user.data.firstTrace
? `${user.data.firstTrace.toLocaleString()} - ${user.data.lastTrace?.toLocaleString()}`
- : isBetaEnabled
+ : isV4
? "No activity yet"
: "No traces yet"}
</Badge>
@@ -205,9 +205,9 @@ function ScoresTab({ userId, projectId }: TabProps) {
}
function TracesTab({ userId, projectId }: TabProps) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
- if (isBetaEnabled) {
+ if (isV4) {
return (
<ObservationsEventsTable
projectId={projectId}
@@ -227,14 +227,14 @@ function TracesTab({ userId, projectId }: TabProps) {
}
function SessionsTab({ userId, projectId }: TabProps) {
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
return (
<SessionsTable
projectId={projectId}
userId={userId}
omittedFilter={["userIds"]}
- isBetaEnabled={isBetaEnabled}
+ isV4={isV4}
/>
);
}
diff --git a/web/src/pages/project/[projectId]/users/index.tsx b/web/src/pages/project/[projectId]/users/index.tsx
index 0fd9cb5b07..ada702aa55 100644
--- a/web/src/pages/project/[projectId]/users/index.tsx
+++ b/web/src/pages/project/[projectId]/users/index.tsx
@@ -15,7 +15,7 @@ import { createTextTableColumn } from "@/src/components/design-system/table/colu
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { api } from "@/src/utils/api";
import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";
import { type RouterOutput } from "@/src/utils/types";
@@ -45,13 +45,13 @@ type RowData = {
export default function UsersPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const { isBetaEnabled } = useV4Beta();
+ const { isV4 } = useReadPath();
// Check if the user has any users
const { data: hasAnyUser, isLoading } = api.users.hasAny.useQuery(
{ projectId },
{
- enabled: !!projectId && !isBetaEnabled,
+ enabled: !!projectId && !isV4,
trpc: {
context: {
skipBatch: true,
@@ -65,7 +65,7 @@ export default function UsersPage() {
api.users.hasAnyFromEvents.useQuery(
{ projectId },
{
- enabled: !!projectId && isBetaEnabled,
+ enabled: !!projectId && isV4,
trpc: {
context: {
skipBatch: true,
@@ -75,8 +75,8 @@ export default function UsersPage() {
},
);
- const hasUsers = isBetaEnabled ? hasAnyUserFromEvents : hasAnyUser;
- const isLoadingUsers = isBetaEnabled ? isLoadingFromEvents : isLoading;
+ const hasUsers = isV4 ? hasAnyUserFromEvents : hasAnyUser;
+ const isLoadingUsers = isV4 ? isLoadingFromEvents : isLoading;
const showOnboarding = !isLoadingUsers && !hasUsers;
return (
@@ -109,17 +109,17 @@ export default function UsersPage() {
{showOnboarding ? (
<UsersOnboarding />
) : (
- <UsersTable isBetaEnabled={isBetaEnabled} showControlsInPageHeader />
+ <UsersTable isV4={isV4} showControlsInPageHeader />
)}
</Page>
);
}
const UsersTable = ({
- isBetaEnabled,
+ isV4,
showControlsInPageHeader = false,
}: {
- isBetaEnabled: boolean;
+ isV4: boolean;
showControlsInPageHeader?: boolean;
}) => {
const router = useRouter();
@@ -208,7 +208,7 @@ const UsersTable = ({
projectId,
searchQuery: searchQuery ?? undefined,
},
- { enabled: !isBetaEnabled },
+ { enabled: !isV4 },
);
const userMetricsV3 = api.users.metrics.useQuery(
@@ -218,7 +218,7 @@ const UsersTable = ({
filter: filterState,
},
{
- enabled: usersV3.isSuccess && !isBetaEnabled,
+ enabled: usersV3.isSuccess && !isV4,
trpc: {
context: {
skipBatch: true,
@@ -235,7 +235,7 @@ const UsersTable = ({
projectId,
searchQuery: searchQuery ?? undefined,
},
- { enabled: isBetaEnabled },
+ { enabled: isV4 },
);
const userMetricsV4 = api.users.metricsFromEvents.useQuery(
@@ -245,7 +245,7 @@ const UsersTable = ({
filter: filterState,
},
{
- enabled: usersV4.isSuccess && isBetaEnabled,
+ enabled: usersV4.isSuccess && isV4,
trpc: {
context: {
skipBatch: true,
@@ -255,8 +255,8 @@ const UsersTable = ({
);
// Select the active query based on beta state
- const users = isBetaEnabled ? usersV4 : usersV3;
- const userMetrics = isBetaEnabled ? userMetricsV4 : userMetricsV3;
+ const users = isV4 ? usersV4 : usersV3;
+ const userMetrics = isV4 ? userMetricsV4 : userMetricsV3;
type UserCoreOutput = RouterOutput["users"]["all"]["users"][number];
type UserMetricsOutput = RouterOutput["users"]["metrics"][number];
@@ -429,7 +429,7 @@ const UsersTable = ({
lastEvent:
t.lastTrace?.toLocaleString() ?? "No event yet",
totalEvents: compactNumberFormatter(
- isBetaEnabled
+ isV4
? Number(t.totalObservations ?? 0)
: Number(t.totalTraces ?? 0) +
Number(t.totalObservations ?? 0),
diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
index 9375b89cab..2682a944c8 100644
--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
@@ -8,6 +8,7 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"
import { type metricAggregations, type views } from "@langfuse/shared/query";
import { type z } from "zod";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
export default function EditWidget() {
const router = useRouter();
@@ -20,6 +21,9 @@ export default function EditWidget() {
// Fetch the widget details
const utils = api.useUtils();
const capture = usePostHogClientCapture();
+ // The form derives its view/version declaration from the read path at
+ // mount — an unresolved session would seed a v4 user's editor as v3.
+ const { isResolved } = useReadPath();
const { data: widgetData, isLoading: isWidgetLoading } =
api.dashboardWidgets.get.useQuery(
{
@@ -95,7 +99,7 @@ export default function EditWidget() {
},
}}
>
- {!isWidgetLoading && widgetData ? (
+ {!isWidgetLoading && widgetData && isResolved ? (
<WidgetForm
// Remount when the edited widget changes so its loaded values seed
// the form defaults once, rather than syncing via an effect.
diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsx
index dc25e38bf5..e4f6251f2e 100644
--- a/web/src/pages/project/[projectId]/widgets/new.tsx
+++ b/web/src/pages/project/[projectId]/widgets/new.tsx
@@ -9,8 +9,9 @@ import { type metricAggregations, type views } from "@langfuse/shared/query";
import { type z } from "zod";
import { SelectDashboardDialog } from "@/src/features/dashboard/components/SelectDashboardDialog";
import { useState } from "react";
-import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
import { getDefaultView } from "@/src/features/widgets/utils";
+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
export default function NewWidget() {
@@ -19,7 +20,7 @@ export default function NewWidget() {
projectId: string;
dashboardId?: string;
};
- const { isBetaEnabled } = useV4Beta();
+ const { isV4, isResolved } = useReadPath();
const capture = usePostHogClientCapture();
const createWidgetMutation = api.dashboardWidgets.create.useMutation({
@@ -78,6 +79,24 @@ export default function NewWidget() {
const [dashboardDialogOpen, setDashboardDialogOpen] = useState(false);
const [pendingWidgetId, setPendingWidgetId] = useState<string | null>(null);
+ // The form seeds its default view from the read path once, at mount — an
+ // unresolved session would permanently seed the v3 default for a v4 user.
+ if (!isResolved) {
+ return (
+ <Page
+ withPadding
+ headerProps={{
+ title: "New Widget",
+ help: {
+ description: "Create a new widget",
+ },
+ }}
+ >
+ <NoDataOrLoading isLoading />
+ </Page>
+ );
+ }
+
return (
<Page
withPadding
@@ -90,7 +109,7 @@ export default function NewWidget() {
>
<WidgetForm
// No `key` on the beta flag: WidgetForm derives viewVersion (and its
- // available views/measures/filter columns) reactively from isBetaEnabled
+ // available views/measures/filter columns) reactively from isV4
// + the selected view, so a live beta toggle re-derives them without a
// remount — preserving the in-progress form. The only tradeoff is that
// an untouched form's default view no longer auto-switches on toggle;
@@ -100,7 +119,7 @@ export default function NewWidget() {
initialValues={{
name: "",
description: "",
- view: getDefaultView(isBetaEnabled),
+ view: getDefaultView(isV4),
dimension: "none",
measure: "count",
aggregation: "count",