Skip to content

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

refactor(web): thin remaining fat pages into feature Page components (#17716)

Nikita Kabardindf03019f78eb
diff --git a/packages/shared/src/features/prompts/validation.test.ts b/packages/shared/src/features/prompts/validation.test.ts
index 5b8cf751ff..70b5cfaa6d 100644
--- a/packages/shared/src/features/prompts/validation.test.ts
+++ b/packages/shared/src/features/prompts/validation.test.ts
@@ -28,7 +28,7 @@ describe("PromptNameSchema", () => {
// resolve through the catch-all. Deliberately not over-blocked.
// Note: "folder/metrics" stays valid here; the catch-all's `/metrics`
// URL-suffix handling is a separate, pre-existing quirk documented in
- // web/src/pages/project/[projectId]/prompts/[[...folder]].tsx.
+ // web/src/features/prompts/PromptsPage.tsx.
it.each(RESERVED_PROMPT_NAMES)(
"allows '%s' as a folder name or leaf segment",
(name) => {
diff --git a/web/src/__tests__/blob-storage-settings-page.clienttest.tsx b/web/src/__tests__/blob-storage-settings-page.clienttest.tsx
index 83e266e64e..7afee94b84 100644
--- a/web/src/__tests__/blob-storage-settings-page.clienttest.tsx
+++ b/web/src/__tests__/blob-storage-settings-page.clienttest.tsx
@@ -87,9 +87,9 @@ vi.mock("@/src/utils/api", () => ({
},
}));
-import BlobStorageIntegrationSettings from "@/src/pages/project/[projectId]/settings/integrations/blobstorage";
+import BlobStorageIntegrationPage from "@/src/features/blobstorage-integration/BlobStorageIntegrationPage";
-describe("BlobStorageIntegrationSettings entitlement gate", () => {
+describe("BlobStorageIntegrationPage entitlement gate", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.hasAccess = true;
@@ -101,7 +101,7 @@ describe("BlobStorageIntegrationSettings entitlement gate", () => {
});
it("does not fetch config and shows a plan message without scheduled-blob-exports", () => {
- render(<BlobStorageIntegrationSettings />);
+ render(<BlobStorageIntegrationPage />);
expect(
screen.getByText("This feature is not available in your current plan."),
@@ -118,7 +118,7 @@ describe("BlobStorageIntegrationSettings entitlement gate", () => {
mocks.hasEntitlement = true;
mocks.hasAccess = false;
- render(<BlobStorageIntegrationSettings />);
+ render(<BlobStorageIntegrationPage />);
expect(
screen.getByText(
@@ -140,7 +140,7 @@ describe("BlobStorageIntegrationSettings entitlement gate", () => {
isLoading: false,
});
- render(<BlobStorageIntegrationSettings />);
+ render(<BlobStorageIntegrationPage />);
expect(screen.getByText("Blob storage form")).toBeInTheDocument();
expect(screen.queryByText("Loading configuration")).not.toBeInTheDocument();
diff --git a/web/src/features/blobstorage-integration/BlobStorageIntegrationPage.tsx b/web/src/features/blobstorage-integration/BlobStorageIntegrationPage.tsx
new file mode 100644
index 0000000000..4c73ae669a
--- /dev/null
+++ b/web/src/features/blobstorage-integration/BlobStorageIntegrationPage.tsx
@@ -0,0 +1,131 @@
+/* eslint-disable no-nested-ternary */
+import Header from "@/src/components/layouts/header";
+import ContainerPage from "@/src/components/layouts/container-page";
+import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
+import { Button } from "@/src/components/ui/button";
+import { Card } from "@/src/components/ui/card";
+import { IntegrationSettingsSkeleton } from "@/src/features/analytics-integrations/components/IntegrationSettingsSkeleton";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api, type RouterOutputs } from "@/src/utils/api";
+import { deriveSyncStatus } from "@/src/features/blobstorage-integration/deriveSyncStatus";
+import { type BlobStorageSyncStatus } from "@/src/features/blobstorage-integration/types";
+import { BlobStorageIntegrationContainer } from "@/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer";
+import { BlobStorageStatusSection } from "@/src/features/blobstorage-integration/components/BlobStorageStatusSection";
+
+const syncStatusToBadge: Record<BlobStorageSyncStatus, string> = {
+ up_to_date: "active",
+ running: "running",
+ queued: "queued",
+ idle: "pending",
+ disabled: "disabled",
+ error: "error",
+};
+
+const syncStatusFromConfig = (
+ config: NonNullable<RouterOutputs["blobStorageIntegration"]["get"]["config"]>,
+): BlobStorageSyncStatus =>
+ deriveSyncStatus({
+ enabled: config.enabled,
+ lastError: config.lastError,
+ lastSyncAt: config.lastSyncAt ? new Date(config.lastSyncAt) : null,
+ nextSyncAt: config.nextSyncAt ? new Date(config.nextSyncAt) : null,
+ runStartedAt: config.runStartedAt ? new Date(config.runStartedAt) : null,
+ });
+
+export default function BlobStorageIntegrationPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "integrations:CRUD",
+ });
+ const hasEntitlement = useHasEntitlement("scheduled-blob-exports");
+ const canLoadConfig = hasAccess && hasEntitlement;
+ const state = api.blobStorageIntegration.get.useQuery(
+ { projectId },
+ {
+ enabled: canLoadConfig,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: 50 * 60 * 1000, // 50 minutes
+ refetchInterval: (query) => {
+ const cfg = query.state.data?.config;
+ if (!cfg) return false;
+ const status = syncStatusFromConfig(cfg);
+ return status === "running" || status === "queued" ? 5_000 : false;
+ },
+ },
+ );
+
+ const syncStatus =
+ state.isLoading || !canLoadConfig || !state.data?.config
+ ? undefined
+ : syncStatusFromConfig(state.data.config);
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "Blob Storage Integration",
+ breadcrumb: [
+ { name: "Settings", href: `/project/${projectId}/settings` },
+ ],
+ actionButtonsLeft: (
+ <>
+ {syncStatus && <StatusBadge type={syncStatusToBadge[syncStatus]} />}
+ </>
+ ),
+ actionButtonsRight: (
+ <Button asChild variant="secondary">
+ <Link
+ href="https://langfuse.com/docs/api-and-data-platform/features/export-to-blob-storage"
+ target="_blank"
+ >
+ Integration Docs ↗
+ </Link>
+ </Button>
+ ),
+ }}
+ >
+ <p className="text-primary mb-4 text-sm">
+ Configure scheduled exports of your trace data to AWS S3, S3-compatible
+ storages, or Azure Blob Storage. Set up a hourly, daily, or weekly
+ export to your own storage for data analysis or backup purposes. Use the
+ &quot;Validate&quot; button to test your configuration by uploading a
+ small test file, and the &quot;Run Now&quot; button to trigger an
+ immediate export.
+ </p>
+ {!hasEntitlement ? (
+ <p className="text-sm">
+ This feature is not available in your current plan.
+ </p>
+ ) : !hasAccess ? (
+ <p className="text-sm">
+ Your current role does not grant you access to these settings, please
+ reach out to your project admin or owner.
+ </p>
+ ) : (
+ <>
+ {state.data?.config && (
+ <BlobStorageStatusSection config={state.data.config} />
+ )}
+ <Header title="Configuration" className="mt-8" />
+ <Card className="p-3">
+ {!state.data ? (
+ <IntegrationSettingsSkeleton />
+ ) : (
+ <BlobStorageIntegrationContainer
+ config={state.data.config ?? null}
+ projectId={projectId}
+ writeMode={state.data.writeMode}
+ />
+ )}
+ </Card>
+ </>
+ )}
+ </ContainerPage>
+ );
+}
diff --git a/web/src/features/blobstorage-integration/README.md b/web/src/features/blobstorage-integration/README.md
index 7b010f25f9..a9766a16e6 100644
--- a/web/src/features/blobstorage-integration/README.md
+++ b/web/src/features/blobstorage-integration/README.md
@@ -125,7 +125,7 @@ worker picks up the job and sets `runStartedAt`.
configuration form plus sync status display.
**Entry point**:
-`web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx`
+`web/src/features/blobstorage-integration/BlobStorageIntegrationPage.tsx`
owns the lifecycle: the tRPC `get` query (with status-driven refetch
interval), the sync-status badge, and page layout. It mounts the two
feature components below.
diff --git a/web/src/features/dashboard/NewDashboardPage.tsx b/web/src/features/dashboard/NewDashboardPage.tsx
new file mode 100644
index 0000000000..ea2f1ac9c8
--- /dev/null
+++ b/web/src/features/dashboard/NewDashboardPage.tsx
@@ -0,0 +1,122 @@
+import { useState } from "react";
+import { useRouter } from "next/router";
+import { api } from "@/src/utils/api";
+import Page from "@/src/components/layouts/page";
+import { Button } from "@/src/components/ui/button";
+import { Input } from "@/src/components/ui/input";
+import { Textarea } from "@/src/components/ui/textarea";
+import { Label } from "@/src/components/ui/label";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+
+export default function NewDashboardPage() {
+ const router = useRouter();
+ const { projectId } = router.query as { projectId: string };
+
+ // State for new dashboard
+ const [dashboardName, setDashboardName] = useState("New Dashboard");
+ const [dashboardDescription, setDashboardDescription] = useState("");
+
+ // Check project access
+ const hasCUDAccess = useHasProjectAccess({
+ projectId,
+ scope: "dashboards:CUD",
+ });
+
+ // Mutation for creating a new dashboard
+ const createDashboard = api.dashboard.createDashboard.useMutation({
+ onSuccess: (data) => {
+ showSuccessToast({
+ title: "Dashboard created",
+ description: "Your new dashboard has been created successfully",
+ });
+ // Navigate to the newly created dashboard
+ router.push(`/project/${projectId}/dashboards/${data.id}`);
+ },
+ onError: (error) => {
+ showErrorToast("Error creating dashboard", error.message);
+ },
+ });
+
+ // Handle form submission
+ const handleCreateDashboard = () => {
+ if (dashboardName.trim()) {
+ createDashboard.mutate({
+ projectId,
+ name: dashboardName,
+ description: dashboardDescription,
+ });
+ } else {
+ showErrorToast("Validation error", "Dashboard name is required");
+ }
+ };
+
+ return (
+ <Page
+ withPadding
+ headerProps={{
+ title: "Create Dashboard",
+ help: {
+ description: "Create a new dashboard for your project",
+ },
+ actionButtonsRight: (
+ <>
+ <Button
+ variant="outline"
+ onClick={() => router.push(`/project/${projectId}/dashboards`)}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleCreateDashboard}
+ disabled={
+ !dashboardName.trim() ||
+ createDashboard.isPending ||
+ !hasCUDAccess
+ }
+ loading={createDashboard.isPending}
+ >
+ Create
+ </Button>
+ </>
+ ),
+ }}
+ >
+ <div className="mx-auto my-8 max-w-xl space-y-6">
+ <div className="space-y-2">
+ <Label htmlFor="dashboard-name">Dashboard Name</Label>
+ <Input
+ id="dashboard-name"
+ value={dashboardName}
+ onChange={(e) => {
+ setDashboardName(e.target.value);
+ }}
+ placeholder="Enter dashboard name"
+ required
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="dashboard-description">Description</Label>
+ <Textarea
+ id="dashboard-description"
+ value={dashboardDescription}
+ onChange={(e) => {
+ setDashboardDescription(e.target.value);
+ }}
+ placeholder="Describe the purpose of this dashboard. Optional, but very helpful."
+ rows={4}
+ />
+ </div>
+
+ <div className="text-muted-foreground text-sm">
+ <p>
+ After creating the dashboard, you can add widgets to visualize your
+ data.
+ </p>
+ </div>
+ </div>
+ </Page>
+ );
+}
diff --git a/web/src/features/datasets/DatasetItemPage.tsx b/web/src/features/datasets/DatasetItemPage.tsx
new file mode 100644
index 0000000000..29f53c34f5
--- /dev/null
+++ b/web/src/features/datasets/DatasetItemPage.tsx
@@ -0,0 +1,213 @@
+import { DATASET_ITEM_TABS } from "@/src/features/navigation/utils/dataset-item-tabs";
+import { DatasetItemDetailPage } from "@/src/features/datasets/components/DatasetItemDetailPage";
+import { DatasetItemViewModeContent } from "@/src/features/datasets/components/DatasetItemViewModeContent";
+import { DatasetItemVersionedContent } from "@/src/features/datasets/components/DatasetItemVersionedContent";
+import { DatasetVersionHistoryPanel } from "@/src/features/datasets/components/DatasetVersionHistoryPanel";
+import { DatasetVersionWarningBanner } from "@/src/features/datasets/components/DatasetVersionWarningBanner";
+import { api } from "@/src/utils/api";
+import { useDatasetVersion } from "@/src/features/datasets/hooks/useDatasetVersion";
+import { toDatasetSchema } from "@/src/features/datasets/utils/datasetItemUtils";
+import { Switch } from "@/src/components/design-system/Switch/Switch";
+import { Label } from "@/src/components/ui/label";
+import { Button } from "@/src/components/ui/button";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import { History, PanelRightOpen } from "lucide-react";
+import { useState } from "react";
+import {
+ RouteParamsPendingFallback,
+ useReadyRouteParams,
+} from "@/src/hooks/useReadyRouteParams";
+
+export default function DatasetItemPage() {
+ const route = useReadyRouteParams(["projectId", "datasetId", "itemId"]);
+ if (!route.ready) return <RouteParamsPendingFallback />;
+ return (
+ <DatasetItemContent
+ projectId={route.params.projectId}
+ datasetId={route.params.datasetId}
+ itemId={route.params.itemId}
+ />
+ );
+}
+
+function DatasetItemContent({
+ projectId,
+ datasetId,
+ itemId,
+}: {
+ projectId: string;
+ datasetId: string;
+ itemId: string;
+}) {
+ const { selectedVersion, resetToLatest } = useDatasetVersion();
+ const isViewingOldVersion = selectedVersion !== null;
+
+ const [showDiffMode, setShowDiffMode] = useSessionStorage(
+ "datasetItem-showDiff",
+ false,
+ );
+ const [isVersionPanelOpen, setIsVersionPanelOpen] =
+ useState(!!selectedVersion);
+
+ const routeReady =
+ Boolean(projectId) && Boolean(datasetId) && Boolean(itemId);
+
+ // Fetch current item
+ const item = api.datasets.itemByIdAtVersion.useQuery(
+ {
+ datasetId,
+ projectId,
+ datasetItemId: itemId,
+ },
+ {
+ enabled: routeReady,
+ refetchOnWindowFocus: false,
+ },
+ );
+
+ // Fetch item at selected version if viewing old version
+ const itemAtVersion = api.datasets.itemByIdAtVersion.useQuery(
+ {
+ projectId,
+ datasetId,
+ datasetItemId: itemId,
+ version: selectedVersion!,
+ },
+ {
+ enabled: routeReady && selectedVersion !== null,
+ },
+ );
+
+ // Fetch dataset
+ const dataset = api.datasets.byId.useQuery(
+ {
+ datasetId,
+ projectId,
+ },
+ { enabled: routeReady },
+ );
+
+ // Fetch item version history for sidebar indicators
+ const itemVersionHistory = api.datasets.itemVersionHistory.useQuery(
+ {
+ projectId,
+ datasetId,
+ itemId,
+ },
+ { enabled: routeReady },
+ );
+
+ // Check if item was changed at selected version (enables diff toggle)
+ // Use 1 second tolerance to account for potential timestamp precision issues
+ const itemChangedAtVersion =
+ selectedVersion &&
+ itemVersionHistory.data?.some(
+ (v) => Math.abs(v.getTime() - selectedVersion.getTime()) < 1000,
+ );
+
+ return (
+ <DatasetItemDetailPage
+ activeTab={DATASET_ITEM_TABS.ITEM}
+ withPadding={false}
+ >
+ <div className="flex h-full">
+ {/* Main content area */}
+ <div className="relative flex flex-1 flex-col overflow-auto">
+ {/* Sticky banner without padding */}
+ {isViewingOldVersion && selectedVersion && (
+ <div className="sticky top-0 z-10">
+ <DatasetVersionWarningBanner
+ selectedVersion={selectedVersion}
+ resetToLatest={resetToLatest}
+ />
+ </div>
+ )}
+
+ {/* Version panel toggle button */}
+ <div className="bg-background sticky top-0 z-10 flex justify-end border-b p-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setIsVersionPanelOpen(!isVersionPanelOpen)}
+ title={
+ isVersionPanelOpen
+ ? "Hide version history"
+ : "Show version history"
+ }
+ >
+ {isVersionPanelOpen ? (
+ <>
+ <History className="mr-2 h-4 w-4" />
+ Hide Version History
+ </>
+ ) : (
+ <>
+ <PanelRightOpen className="mr-2 h-4 w-4" />
+ Show Version History
+ </>
+ )}
+ </Button>
+ </div>
+
+ {/* Content with padding */}
+ <div className="px-6 py-4">
+ {/* Diff mode toggle */}
+ {isViewingOldVersion && selectedVersion && itemChangedAtVersion && (
+ <div className="mb-4 flex flex-col gap-2">
+ <div className="flex items-center space-x-2">
+ <Switch
+ id="diff-mode"
+ checked={showDiffMode}
+ onCheckedChange={setShowDiffMode}
+ />
+ <Label htmlFor="diff-mode" className="cursor-pointer text-sm">
+ Show diff with latest version
+ </Label>
+ </div>
+ </div>
+ )}
+
+ {/* Item unchanged message */}
+ {isViewingOldVersion &&
+ selectedVersion &&
+ !itemChangedAtVersion && (
+ <div className="text-muted-foreground mb-4 text-sm">
+ Item unchanged in this version
+ </div>
+ )}
+
+ {/* Main content area */}
+ {isViewingOldVersion ? (
+ <DatasetItemVersionedContent
+ itemAtVersion={itemAtVersion.data ?? null}
+ latestItem={item.data ?? null}
+ isLoadingVersioned={itemAtVersion.isLoading}
+ isLoadingLatest={item.isLoading}
+ showDiffMode={showDiffMode}
+ itemChangedAtVersion={!!itemChangedAtVersion}
+ dataset={toDatasetSchema(dataset.data ?? null)}
+ />
+ ) : (
+ <DatasetItemViewModeContent
+ item={item.data ?? null}
+ isLoading={item.isLoading}
+ dataset={toDatasetSchema(dataset.data ?? null)}
+ />
+ )}
+ </div>
+ </div>
+
+ {/* Version history sidebar */}
+ {isVersionPanelOpen && (
+ <div className="w-1/4 shrink-0 border-l">
+ <DatasetVersionHistoryPanel
+ projectId={projectId}
+ datasetId={datasetId}
+ itemVersions={itemVersionHistory.data}
+ />
+ </div>
+ )}
+ </div>
+ </DatasetItemDetailPage>
+ );
+}
diff --git a/web/src/features/datasets/DatasetItemsPage.tsx b/web/src/features/datasets/DatasetItemsPage.tsx
new file mode 100644
index 0000000000..21f9c89bdb
--- /dev/null
+++ b/web/src/features/datasets/DatasetItemsPage.tsx
@@ -0,0 +1,188 @@
+import { api } from "@/src/utils/api";
+import {
+ getDatasetTabs,
+ DATASET_TABS,
+} from "@/src/features/navigation/utils/dataset-tabs";
+import { DatasetItemsTable } from "@/src/features/datasets/components/DatasetItemsTable";
+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import { NewDatasetItemButton } from "@/src/features/datasets/components/NewDatasetItemButton";
+import { UploadDatasetCsvButton } from "@/src/features/datasets/components/UploadDatasetCsvButton";
+import { Button } from "@/src/components/ui/button";
+import { History, MoreVertical } from "lucide-react";
+import Page from "@/src/components/layouts/page";
+import { DatasetItemsOnboarding } from "@/src/components/onboarding/DatasetItemsOnboarding";
+import { SidePanel, SidePanelContent } from "@/src/components/ui/side-panel";
+import { DatasetVersionHistoryPanel } from "@/src/features/datasets/components/DatasetVersionHistoryPanel";
+import { DatasetVersionWarningBanner } from "@/src/features/datasets/components/DatasetVersionWarningBanner";
+import { useState } from "react";
+import { useDatasetVersion } from "@/src/features/datasets/hooks/useDatasetVersion";
+import { getDatasetBreadcrumb } from "@/src/features/datasets/utils/getDatasetBreadcrumb";
+import {
+ RouteParamsPendingFallback,
+ useReadyRouteParams,
+} from "@/src/hooks/useReadyRouteParams";
+import { DatasetActionMenu } from "@/src/features/datasets/components/DatasetActionMenu";
+
+export default function DatasetItemsPage() {
+ const route = useReadyRouteParams(["projectId", "datasetId"]);
+ if (!route.ready) return <RouteParamsPendingFallback />;
+ return (
+ <DatasetItemsView
+ projectId={route.params.projectId}
+ datasetId={route.params.datasetId}
+ />
+ );
+}
+
+function DatasetItemsView({
+ projectId,
+ datasetId,
+}: {
+ projectId: string;
+ datasetId: string;
+}) {
+ const { selectedVersion, resetToLatest } = useDatasetVersion();
+ const isViewingOldVersion = selectedVersion !== null;
+
+ const [isVersionPanelOpen, setIsVersionPanelOpen] = useState(false);
+
+ const dataset = api.datasets.byId.useQuery(
+ {
+ datasetId,
+ projectId,
+ },
+ { enabled: Boolean(projectId) && Boolean(datasetId) },
+ );
+
+ const totalDatasetItemCount = api.datasets.countItemsByDatasetId.useQuery(
+ {
+ projectId,
+ datasetId,
+ },
+ { enabled: Boolean(projectId) && Boolean(datasetId) },
+ );
+
+ const showOnboarding =
+ totalDatasetItemCount.isSuccess && totalDatasetItemCount.data === 0;
+
+ // Fetch change counts since selected version
+ const changeCounts = api.datasets.countChangesSinceVersion.useQuery(
+ {
+ projectId,
+ datasetId,
+ version: selectedVersion!,
+ },
+ {
+ enabled: selectedVersion !== null,
+ },
+ );
+
+ const handlePanelOpenChange = (open: boolean) => {
+ setIsVersionPanelOpen(open);
+ };
+
+ const breadcrumb = getDatasetBreadcrumb(
+ projectId,
+ datasetId,
+ dataset.data?.name,
+ );
+
+ return (
+ <Page
+ headerProps={{
+ title: dataset.data?.name ?? "",
+ itemType: "DATASET",
+ breadcrumb,
+ tabsProps: {
+ tabs: getDatasetTabs(projectId, datasetId),
+ activeTab: DATASET_TABS.ITEMS,
+ },
+ actionButtonsRight: (
+ <>
+ {!showOnboarding && (
+ <>
+ <NewDatasetItemButton
+ projectId={projectId}
+ datasetId={datasetId}
+ />
+ <UploadDatasetCsvButton
+ projectId={projectId}
+ datasetId={datasetId}
+ />
+ </>
+ )}
+ <DetailPageNav
+ currentId={datasetId}
+ path={(entry) =>
+ `/project/${projectId}/datasets/${entry.id}/items/`
+ }
+ listKey="datasets"
+ />
+ <DatasetActionMenu
+ projectId={projectId}
+ datasetId={datasetId}
+ datasetName={dataset.data?.name ?? ""}
+ datasetDescription={dataset.data?.description ?? undefined}
+ datasetMetadata={dataset.data?.metadata}
+ datasetInputSchema={dataset.data?.inputSchema ?? undefined}
+ datasetExpectedOutputSchema={
+ dataset.data?.expectedOutputSchema ?? undefined
+ }
+ >
+ {({ getTriggerProps }) => (
+ <Button
+ variant="outline"
+ size="icon"
+ aria-label="Dataset actions"
+ {...getTriggerProps()}
+ >
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ )}
+ </DatasetActionMenu>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => setIsVersionPanelOpen(!isVersionPanelOpen)}
+ title="Version History"
+ >
+ <History className="h-4 w-4" />
+ </Button>
+ </>
+ ),
+ }}
+ >
+ {showOnboarding ? (
+ <DatasetItemsOnboarding projectId={projectId} datasetId={datasetId} />
+ ) : (
+ <div className="grid flex-1 grid-cols-[1fr_auto] overflow-hidden">
+ <div className="flex h-full flex-col overflow-hidden">
+ {isViewingOldVersion && selectedVersion && (
+ <DatasetVersionWarningBanner
+ selectedVersion={selectedVersion}
+ resetToLatest={resetToLatest}
+ changeCounts={changeCounts.data}
+ />
+ )}
+ <DatasetItemsTable projectId={projectId} datasetId={datasetId} />
+ </div>
+ <SidePanel
+ id="version-history-panel"
+ openState={{
+ open: isVersionPanelOpen,
+ onOpenChange: handlePanelOpenChange,
+ }}
+ mobileTitle="Version History"
+ >
+ <SidePanelContent className="h-full">
+ <DatasetVersionHistoryPanel
+ projectId={projectId}
+ datasetId={datasetId}
+ />
+ </SidePanelContent>
+ </SidePanel>
+ </div>
+ )}
+ </Page>
+ );
+}
diff --git a/web/src/features/datasets/DatasetRunPage.tsx b/web/src/features/datasets/DatasetRunPage.tsx
new file mode 100644
index 0000000000..9b1b4bf04d
--- /dev/null
+++ b/web/src/features/datasets/DatasetRunPage.tsx
@@ -0,0 +1,200 @@
+import { Button } from "@/src/components/ui/button";
+import { JSONView } from "@/src/components/ui/CodeJsonViewer";
+import { DatasetRunItemsByRunTable } from "@/src/features/datasets/components/DatasetRunItemsByRunTable";
+import { DeleteDatasetRunDialogController } from "@/src/features/datasets/components/DeleteDatasetRunDialogController";
+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import { api } from "@/src/utils/api";
+import { Columns3, MoreVertical, Trash } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useEffect } from "react";
+import Page from "@/src/components/layouts/page";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import {
+ SidePanel,
+ SidePanelContent,
+ SidePanelHeader,
+ SidePanelTitle,
+} from "@/src/components/ui/side-panel";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import { getDatasetBreadcrumb } from "@/src/features/datasets/utils/getDatasetBreadcrumb";
+import { useExperimentAccess } from "@/src/features/experiments/hooks/useExperimentAccess";
+import { singleRunToExperimentsUrl } from "@/src/features/experiments/utils/experimentUrlTranslation";
+import { buildLocalIsoDatePresentation } from "@/src/utils/dates";
+
+function DatasetRunLegacy() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const datasetId = router.query.datasetId as string;
+ const runId = router.query.runId as string;
+
+ const dataset = api.datasets.byId.useQuery({
+ datasetId,
+ projectId,
+ });
+ const run = api.datasets.runById.useQuery({
+ datasetId,
+ projectId,
+ runId,
+ });
+ const breadcrumb = getDatasetBreadcrumb(
+ projectId,
+ datasetId,
+ dataset.data?.name,
+ );
+
+ const preparedDate = buildLocalIsoDatePresentation({
+ date: run.data?.datasetVersion,
+ });
+
+ return (
+ <Page
+ headerProps={{
+ title: run.data?.name ?? runId,
+ itemType: "EXPERIMENT",
+ breadcrumb: [
+ ...breadcrumb,
+ {
+ name: "Experiments",
+ href: `/project/${projectId}/datasets/${datasetId}/experiments`,
+ },
+ ],
+ actionButtonsRight: (
+ <>
+ <Link
+ href={{
+ pathname: `/project/${projectId}/datasets/${datasetId}/compare`,
+ query: { runs: [runId] },
+ }}
+ >
+ <Button>
+ <Columns3 className="mr-2 h-4 w-4" />
+ <span>Compare</span>
+ </Button>
+ </Link>
+ <DetailPageNav
+ currentId={runId}
+ path={(entry) =>
+ `/project/${projectId}/datasets/${datasetId}/runs/${entry.id}`
+ }
+ listKey="datasetRuns"
+ />
+ <DeleteDatasetRunDialogController
+ projectId={projectId}
+ datasetRunId={runId}
+ datasetId={datasetId}
+ redirectUrl={`/project/${projectId}/datasets/${datasetId}/experiments`}
+ >
+ {({ disabled, openDialog }) => (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="icon">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem disabled={disabled} onSelect={openDialog}>
+ <Trash className="h-4 w-4" />
+ <span>Delete</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </DeleteDatasetRunDialogController>
+ </>
+ ),
+ }}
+ >
+ <div className="grid flex-1 grid-cols-[1fr_auto] overflow-hidden">
+ <div className="flex h-full flex-col overflow-hidden">
+ <DatasetRunItemsByRunTable
+ projectId={projectId}
+ datasetId={datasetId}
+ datasetRunId={runId}
+ datasetVersion={run.data?.datasetVersion}
+ />
+ </div>
+ <SidePanel
+ mobileTitle="Experiment run details"
+ id="experiment-run-details"
+ >
+ <SidePanelHeader>
+ <SidePanelTitle>Experiment run details</SidePanelTitle>
+ </SidePanelHeader>
+ <SidePanelContent>
+ {run.isPending ? (
+ <Skeleton className="h-full w-full" />
+ ) : (
+ <>
+ {run.data?.datasetVersion && preparedDate && (
+ <div className="flex flex-col gap-2 p-1">
+ <span className="text-sm font-bold">Dataset Version</span>
+ <Link
+ href={`/project/${projectId}/datasets/${datasetId}/items?version=${run.data.datasetVersion.toISOString()}`}
+ className="text-link hover:text-link-hover text-sm"
+ >
+ <span title={preparedDate.title}>
+ {preparedDate.display}
+ </span>
+ </Link>
+ </div>
+ )}
+ {!!run.data?.description && (
+ <JSONView
+ json={run.data.description}
+ title="Description"
+ className="w-full overflow-y-auto"
+ />
+ )}
+ {!!run.data?.metadata && (
+ <JSONView
+ json={run.data.metadata}
+ title="Metadata"
+ className="w-full overflow-y-auto"
+ />
+ )}
+ {!run.data?.description && !run.data?.metadata && (
+ <div className="text-muted-foreground mt-1 px-1 text-sm">
+ No description or metadata for this run
+ </div>
+ )}
+ </>
+ )}
+ </SidePanelContent>
+ </SidePanel>
+ </div>
+ </Page>
+ );
+}
+
+export default function DatasetRunPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const runId = router.query.runId as string;
+ const { isExperimentsBetaActive, isInitializing } = useExperimentAccess();
+
+ useEffect(() => {
+ if (
+ !router.isReady ||
+ isInitializing ||
+ !isExperimentsBetaActive ||
+ !projectId ||
+ !runId
+ ) {
+ return;
+ }
+
+ router.replace(singleRunToExperimentsUrl(projectId, runId));
+ }, [isExperimentsBetaActive, isInitializing, projectId, router, runId]);
+
+ if (!router.isReady || isInitializing || isExperimentsBetaActive) {
+ return <Skeleton className="h-full w-full" />;
+ }
+
+ return <DatasetRunLegacy />;
+}
diff --git a/web/src/features/experiments/ExperimentResultsPage.tsx b/web/src/features/experiments/ExperimentResultsPage.tsx
new file mode 100644
index 0000000000..d6971dfe6f
--- /dev/null
+++ b/web/src/features/experiments/ExperimentResultsPage.tsx
@@ -0,0 +1,204 @@
+import { useRouter } from "next/router";
+import Page from "@/src/components/layouts/page";
+import { api } from "@/src/utils/api";
+import { ExperimentItemsTable } from "@/src/features/experiments/components/table";
+import { ExperimentOverviewPanel } from "@/src/features/experiments/components/ExperimentOverviewPanel";
+import {
+ OverviewPanelLayout,
+ OverviewPanelToggle,
+} from "@/src/components/layouts/overview-panel";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import { useCallback, useEffect } from "react";
+import { ExperimentDisplaySettings } from "@/src/features/experiments/components/ExperimentDisplaySettings";
+import { ExperimentFormatSetting } from "@/src/features/experiments/components/ExperimentFormatSetting";
+import { useExperimentAccess } from "@/src/features/experiments/hooks/useExperimentAccess";
+import { Spinner } from "@/src/components/design-system/Spinner/Spinner";
+import { ExperimentSelectionControls } from "@/src/features/experiments/components/ExperimentSelectionControls";
+import { useIoRenderModeLocalStorage } from "@/src/components/table/data-table-io-render-mode-switch";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import {
+ diffModeChangedProps,
+ layoutChangedProps,
+} from "@/src/features/experiments/lib/analytics";
+import {
+ useExperimentResultsState,
+ type ExperimentDiffMode,
+ type ExperimentResultsLayout,
+} from "@/src/features/experiments/hooks/useExperimentResultsState";
+
+export default function ExperimentResultsPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+
+ const {
+ baselineId,
+ hasBaseline,
+ setBaseline,
+ clearBaseline,
+ comparisonIds,
+ setComparisonIds,
+ layout,
+ setLayout,
+ diffMode,
+ setDiffMode,
+ itemVisibility,
+ setItemVisibility,
+ allExperimentIds,
+ colorExperimentIds,
+ } = useExperimentResultsState();
+ const [ioRenderMode, setIoRenderMode] = useIoRenderModeLocalStorage(
+ "experiment-items",
+ "json",
+ );
+
+ const [isOverviewOpen, setIsOverviewOpen] = useSessionStorage(
+ "overview-panel-experiment-detail",
+ false,
+ );
+
+ const capture = usePostHogClientCapture();
+
+ // Is the new score-matrix layout adopted, and diff mode — Expected → Output
+ // in particular — used at all? Captured on the menu pick rather than on the
+ // URL state, which also changes on navigation, on a restored view, and (for
+ // the layout) as a side effect of choosing Expected → Output.
+ const handleLayoutChange = useCallback(
+ (newLayout: ExperimentResultsLayout) => {
+ if (newLayout !== layout) {
+ capture(
+ "experiment:layout_changed",
+ layoutChangedProps({
+ tableName: "experiment-items",
+ layout: newLayout,
+ comparisonCount: comparisonIds.length,
+ }),
+ );
+ }
+ setLayout(newLayout);
+ },
+ [capture, layout, comparisonIds.length, setLayout],
+ );
+
+ const handleDiffModeChange = useCallback(
+ (newDiffMode: ExperimentDiffMode) => {
+ if (newDiffMode !== diffMode) {
+ capture(
+ "experiment:diff_mode_changed",
+ diffModeChangedProps({
+ tableName: "experiment-items",
+ mode: newDiffMode,
+ comparisonCount: comparisonIds.length,
+ }),
+ );
+ }
+ setDiffMode(newDiffMode);
+ },
+ [capture, diffMode, comparisonIds.length, setDiffMode],
+ );
+
+ const { isExperimentsBetaActive, isInitializing } = useExperimentAccess();
+
+ useEffect(() => {
+ if (isInitializing || isExperimentsBetaActive || !projectId) return;
+
+ router.replace(`/project/${projectId}/datasets`);
+ }, [isExperimentsBetaActive, isInitializing, projectId, router]);
+
+ // Fetch experiment to get dataset ID and other details
+ const { data: experiment } = api.experiments.byId.useQuery(
+ {
+ projectId,
+ experimentId: baselineId ?? "",
+ },
+ {
+ enabled: Boolean(projectId && baselineId) && isExperimentsBetaActive,
+ },
+ );
+
+ // Show spinner while session loads or while redirecting when beta is off
+ if (!isExperimentsBetaActive) {
+ return (
+ <Page headerProps={{ title: "Experiments" }}>
+ <div className="flex h-full items-center justify-center">
+ <Spinner size="xl" variant="muted" />
+ </div>
+ </Page>
+ );
+ }
+
+ return (
+ <Page
+ headerProps={{
+ title: "",
+ itemType: "EXPERIMENT",
+ breadcrumb: [
+ { name: "Experiments", href: `/project/${projectId}/experiments` },
+ ],
+ actionButtonsLeft: (
+ <ExperimentSelectionControls
+ projectId={projectId}
+ baselineId={baselineId}
+ baselineName={experiment?.name}
+ comparisonIds={comparisonIds}
+ colorExperimentIds={colorExperimentIds}
+ selectedExperimentCount={allExperimentIds.length}
+ onBaselineChange={setBaseline}
+ onBaselineClear={clearBaseline}
+ onComparisonIdsChange={setComparisonIds}
+ />
+ ),
+ actionButtonsRight: (
+ <>
+ <ExperimentDisplaySettings
+ layout={layout}
+ onLayoutChange={handleLayoutChange}
+ diffMode={diffMode}
+ onDiffModeChange={handleDiffModeChange}
+ itemVisibility={itemVisibility}
+ onItemVisibilityChange={setItemVisibility}
+ hasComparisons={comparisonIds.length > 0}
+ hasBaseline={hasBaseline}
+ />
+
+ <OverviewPanelToggle
+ open={isOverviewOpen}
+ onOpenChange={setIsOverviewOpen}
+ />
+ </>
+ ),
+ }}
+ >
+ <OverviewPanelLayout
+ open={isOverviewOpen}
+ persistId={`experiment-detail-${baselineId ?? "none"}`}
+ mainContent={
+ <ExperimentItemsTable
+ // The shared table body's memo comparator does not look at the
+ // column definitions, so a format change alone never reaches the
+ // cells. Remounting is what makes the switch take effect.
+ key={ioRenderMode}
+ projectId={projectId}
+ ioRenderMode={ioRenderMode}
+ toolbarSettings={
+ <ExperimentFormatSetting
+ ioRenderMode={ioRenderMode}
+ onIoRenderModeChange={setIoRenderMode}
+ />
+ }
+ />
+ }
+ overviewContent={
+ <ExperimentOverviewPanel
+ key={baselineId ?? "no-baseline"}
+ projectId={projectId}
+ experiment={experiment ?? undefined}
+ />
+ }
+ defaultPrimarySize={75}
+ defaultSecondarySize={25}
+ minPrimarySize={50}
+ maxSecondarySize={40}
+ />
+ </Page>
+ );
+}
diff --git a/web/src/features/posthog-integration/PostHogIntegrationPage.tsx b/web/src/features/posthog-integration/PostHogIntegrationPage.tsx
new file mode 100644
index 0000000000..5a81feb1a5
--- /dev/null
+++ b/web/src/features/posthog-integration/PostHogIntegrationPage.tsx
@@ -0,0 +1,197 @@
+/* eslint-disable no-nested-ternary */
+import { PostHogLogo } from "@/src/components/PosthogLogo";
+import Header from "@/src/components/layouts/header";
+import ContainerPage from "@/src/components/layouts/container-page";
+import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
+import { Button } from "@/src/components/design-system/Button/Button";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { PostHogStatusSection } from "@/src/features/posthog-integration/components/PostHogStatusSection";
+import {
+ PostHogIntegrationForm,
+ type PostHogIntegrationFormValues,
+} from "@/src/features/posthog-integration/components/PostHogIntegrationForm";
+import {
+ LEGACY_ANALYTICS_EXPORTER_CUTOFF,
+ type V4WriteMode,
+ type ExportSourceContext,
+} from "@langfuse/shared";
+// Shared export-source UI adapters; policy in export-source-policy.ts.
+import {
+ buildExportSourceContext,
+ getExportSourceFormValue,
+} from "@/src/features/analytics-integrations/exportSource";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import { useQueryProject } from "@/src/features/projects/hooks";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api } from "@/src/utils/api";
+import { type RouterOutput } from "@/src/utils/types";
+import { Card } from "@/src/components/ui/card";
+import { IntegrationSettingsSkeleton } from "@/src/features/analytics-integrations/components/IntegrationSettingsSkeleton";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useMemo } from "react";
+
+export default function PostHogIntegrationPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "integrations:CRUD",
+ });
+ const state = api.posthogIntegration.get.useQuery(
+ { projectId },
+ {
+ enabled: hasAccess,
+ },
+ );
+
+ const { project } = useQueryProject();
+
+ // A persisted fault outranks active/inactive: it is the state the admin has
+ // to act on, and it is cleared by the next successful sync.
+ const status =
+ state.isLoading || !hasAccess
+ ? undefined
+ : state.data?.config?.lastError
+ ? "error"
+ : state.data?.config?.enabled
+ ? "active"
+ : "inactive";
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "PostHog Integration",
+ breadcrumb: [
+ { name: "Settings", href: `/project/${projectId}/settings` },
+ ],
+ actionButtonsLeft: <>{status && <StatusBadge type={status} />}</>,
+ actionButtonsRight: (
+ <Button
+ href="https://langfuse.com/integrations/analytics/posthog"
+ text="Integration Docs"
+ variant="secondary"
+ />
+ ),
+ }}
+ >
+ <p className="text-primary mb-4 text-sm">
+ We have teamed up with{" "}
+ <Link href="https://posthog.com" className="underline">
+ PostHog
+ </Link>{" "}
+ (OSS product analytics) to make Langfuse events/metrics available in
+ your PostHog dashboards. Upon activation, all historical data from your
+ project will be synced. After the initial sync, new data is
+ automatically synced every hour to keep your PostHog dashboards up to
+ date.
+ </p>
+ {!hasAccess && (
+ <p className="text-sm">
+ You current role does not grant you access to these settings, please
+ reach out to your project admin or owner.
+ </p>
+ )}
+ {hasAccess && (
+ <>
+ <Header title="Configuration" />
+ <Card className="p-3">
+ <PostHogLogo className="text-foreground mb-4 w-36" />
+ {!state.data || !project ? (
+ <IntegrationSettingsSkeleton />
+ ) : (
+ <ConnectedPostHogIntegrationForm
+ // Draft lifetime = entity identity, so background refetches
+ // cannot reset a draft in progress.
+ key={`${projectId}:${state.data.config ? "configured" : "new"}`}
+ state={state.data.config ?? undefined}
+ projectId={projectId}
+ writeMode={state.data.writeMode}
+ projectCreatedAt={project.createdAt}
+ />
+ )}
+ </Card>
+ </>
+ )}
+ {state.data?.config && (
+ <PostHogStatusSection config={state.data.config} />
+ )}
+ </ContainerPage>
+ );
+}
+
+const ConnectedPostHogIntegrationForm = ({
+ state,
+ projectId,
+ writeMode,
+ projectCreatedAt,
+}: {
+ state?: NonNullable<RouterOutput["posthogIntegration"]["get"]["config"]>;
+ projectId: string;
+ writeMode: V4WriteMode;
+ // Raw ISO string, not a Date: a Date built in the parent's JSX would be a new
+ // reference on every render and would defeat the memo below.
+ projectCreatedAt: string;
+}) => {
+ const capture = usePostHogClientCapture();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const integrationCreatedAt = state?.createdAt;
+ const exportSourceCtx: ExportSourceContext = useMemo(
+ () =>
+ buildExportSourceContext({
+ writeMode,
+ isCloud: isLangfuseCloud,
+ projectCreatedAt: new Date(projectCreatedAt),
+ integrationCreatedAt: integrationCreatedAt
+ ? new Date(integrationCreatedAt)
+ : null,
+ exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,
+ }),
+ [writeMode, isLangfuseCloud, projectCreatedAt, integrationCreatedAt],
+ );
+ const defaultExportSource = getExportSourceFormValue(
+ state?.exportSource,
+ exportSourceCtx,
+ );
+
+ const utils = api.useUtils();
+ const mut = api.posthogIntegration.update.useMutation({
+ onSuccess: () => {
+ utils.posthogIntegration.invalidate();
+ },
+ });
+ const mutDelete = api.posthogIntegration.delete.useMutation({
+ onSuccess: () => {
+ utils.posthogIntegration.invalidate();
+ },
+ });
+
+ function onSubmit(values: PostHogIntegrationFormValues) {
+ capture("integrations:posthog_form_submitted");
+ mut.mutate({
+ projectId,
+ ...values,
+ });
+ }
+
+ return (
+ <PostHogIntegrationForm
+ actionState={
+ mut.isPending ? "saving" : mutDelete.isPending ? "resetting" : "idle"
+ }
+ configurationState={state ? "configured" : "new"}
+ defaultValues={{
+ posthogHostname: state?.posthogHostName ?? "",
+ posthogProjectApiKey: "",
+ enabled: state?.enabled ?? false,
+ exportSource: defaultExportSource,
+ }}
+ exportSourceContext={exportSourceCtx}
+ projectApiKeyDisplay={state?.posthogApiKeyDisplay}
+ resetError={mutDelete.error?.message}
+ onSubmit={onSubmit}
+ onReset={() => mutDelete.mutateAsync({ projectId })}
+ />
+ );
+};
diff --git a/web/src/features/prompts/PromptsPage.tsx b/web/src/features/prompts/PromptsPage.tsx
new file mode 100644
index 0000000000..abb07bfd29
--- /dev/null
+++ b/web/src/features/prompts/PromptsPage.tsx
@@ -0,0 +1,196 @@
+/* eslint-disable no-nested-ternary */
+import { useRouter } from "next/router";
+import { ActionButton } from "@/src/components/ActionButton";
+import Page from "@/src/components/layouts/page";
+import { PromptTable } from "@/src/features/prompts/components/prompts-table";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { Download, UploadIcon, PlusIcon } from "lucide-react";
+import { api } from "@/src/utils/api";
+import { PromptsOnboarding } from "@/src/components/onboarding/PromptsOnboarding";
+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
+import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";
+import PromptMetrics from "@/src/features/prompts/PromptMetricsPage";
+import { useQueryParams, StringParam } from "use-query-params";
+import { useState } from "react";
+import { AutomationButton } from "@/src/features/automations/components/AutomationButton";
+import { ImportPromptsButtonDialogController } from "@/src/features/prompts/components/ImportPromptsButtonDialogController";
+import { Button } from "@/src/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { toast } from "sonner";
+
+export default function PromptsPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const routeSegments = router.query.folder;
+ const [queryParams] = useQueryParams({ folder: StringParam });
+ const folderQueryParam = queryParams.folder || "";
+
+ // Determine view type based on route segments
+ // NOTE: there is a bug here, that if the user directly accesses a prompt name which ends in `/metrics`,
+ // the prompt metrics page will be shown for a non-existing prompt name. Doesn't happen if the user clicks
+ // this in the UI (we URL encode here and don't strip metrics). We could resolve this with another API call
+ // to check the prompt name existence.
+ const segmentsArray = Array.isArray(routeSegments) ? routeSegments : [];
+ const isMetricsPage =
+ segmentsArray.length > 0 &&
+ segmentsArray[segmentsArray.length - 1] === "metrics";
+ const promptNameFromRoute =
+ segmentsArray.length > 0
+ ? isMetricsPage
+ ? segmentsArray.slice(0, -1).join("/")
+ : segmentsArray.join("/")
+ : "";
+
+ const hasCUDAccess = useHasProjectAccess({
+ projectId,
+ scope: "prompts:CUD",
+ });
+ const hasReadAccess = useHasProjectAccess({
+ projectId,
+ scope: "prompts:read",
+ });
+ const promptLimit = useEntitlementLimit("prompt-management-count-prompts");
+ const utils = api.useUtils();
+ const [isExporting, setIsExporting] = useState(false);
+ const capture = usePostHogClientCapture();
+
+ const handleExport = async (mode: "latest" | "all") => {
+ setIsExporting(true);
+ try {
+ const data = await utils.prompts.exportAll.fetch({
+ projectId,
+ includeAllVersions: mode === "all",
+ });
+ const json = JSON.stringify(data, null, 2);
+ const blob = new Blob([json], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `langfuse-prompts-${mode}-${new Date().toISOString().slice(0, 10)}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ capture("prompts:bulk_export", { mode });
+ } catch {
+ toast.error("Failed to export prompts. Please try again.");
+ } finally {
+ setIsExporting(false);
+ }
+ };
+
+ // Check if the project has any prompts
+ const { data: hasAnyPrompt, isLoading } = api.prompts.hasAny.useQuery(
+ { projectId },
+ {
+ enabled: !!projectId,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const { data: count } = api.prompts.count.useQuery(
+ { projectId },
+ {
+ enabled: !!projectId && !promptNameFromRoute, // Only count when on folder view
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const showOnboarding = !isLoading && !hasAnyPrompt;
+
+ // Decide what to render: metrics, detail, or folder view
+ if (promptNameFromRoute.length > 0) {
+ if (isMetricsPage) {
+ return <PromptMetrics promptName={promptNameFromRoute} />;
+ }
+ return <PromptDetail promptName={promptNameFromRoute} />;
+ }
+
+ return (
+ <Page
+ headerProps={{
+ title: "Prompts",
+ help: {
+ description:
+ "Manage and version your prompts in Langfuse. Edit and update them via the UI and SDK. Retrieve the production version via the SDKs. Learn more in the docs.",
+ href: "https://langfuse.com/docs/prompt-management/get-started",
+ },
+ actionButtonsRight: (
+ <>
+ {projectId && <AutomationButton projectId={projectId} />}
+ {hasReadAccess && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" disabled={isExporting}>
+ <UploadIcon className="mr-1 h-4 w-4" />
+ {isExporting ? "Exporting…" : "Export"}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => handleExport("latest")}>
+ Latest version per prompt
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => handleExport("all")}>
+ All versions
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {projectId && (
+ <ImportPromptsButtonDialogController projectId={projectId}>
+ {({ disabled, openDialog }) => (
+ <Button
+ variant="outline"
+ disabled={Boolean(disabled)}
+ title={disabled?.reason}
+ onClick={openDialog}
+ >
+ <Download className="mr-1 h-4 w-4" />
+ Import
+ </Button>
+ )}
+ </ImportPromptsButtonDialogController>
+ )}
+ <ActionButton
+ icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}
+ hasAccess={hasCUDAccess}
+ href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ""}`}
+ trackingEventName="prompts:new_form_open"
+ variant="default"
+ usageLimit={
+ typeof promptLimit === "number"
+ ? {
+ current: Number(count?.totalCount ?? 0),
+ max: promptLimit,
+ }
+ : undefined
+ }
+ >
+ New prompt
+ </ActionButton>
+ </>
+ ),
+ }}
+ scrollable={showOnboarding}
+ >
+ {/* Show onboarding screen if project has no prompts */}
+ {showOnboarding ? (
+ <PromptsOnboarding projectId={projectId} />
+ ) : (
+ <PromptTable key={folderQueryParam} />
+ )}
+ </Page>
+ );
+}
diff --git a/web/src/features/traces/TracesSetupPage.tsx b/web/src/features/traces/TracesSetupPage.tsx
new file mode 100644
index 0000000000..af25f7a661
--- /dev/null
+++ b/web/src/features/traces/TracesSetupPage.tsx
@@ -0,0 +1,149 @@
+import React, { useEffect, useState } from "react";
+import { useRouter } from "next/router";
+import { api, reportNonTrpcError } from "@/src/utils/api";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import ContainerPage from "@/src/components/layouts/container-page";
+import { ActionButton } from "@/src/components/ActionButton";
+import { SubHeader } from "@/src/components/layouts/header";
+import { Button } from "@/src/components/ui/button";
+import { ApiKeyDetailContent } from "@/src/features/public-api/components/ApiKeyDetailContent";
+import { useLangfuseBaseUrl } from "@/src/features/public-api/hooks/useLangfuseEnvCode";
+import { type RouterOutput } from "@/src/utils/types";
+import { useQueryProject } from "@/src/features/projects/hooks";
+
+export const TracingSetup = ({
+ projectId,
+ hasTracingConfigured,
+}: {
+ projectId: string;
+ hasTracingConfigured?: boolean;
+}) => {
+ const baseUrl = useLangfuseBaseUrl();
+ const [apiKeys, setApiKeys] = useState<
+ RouterOutput["projectApiKeys"]["create"] | null
+ >(null);
+ const utils = api.useUtils();
+ const mutCreateApiKey = api.projectApiKeys.create.useMutation({
+ onSuccess: (data) => {
+ utils.projectApiKeys.invalidate();
+ setApiKeys(data);
+ },
+ });
+
+ const createApiKey = async () => {
+ try {
+ await mutCreateApiKey.mutateAsync({ projectId });
+ } catch (error) {
+ reportNonTrpcError(error, "setup");
+ }
+ };
+
+ return (
+ <div className="space-y-8">
+ <div>
+ <SubHeader title="1. Get API keys" />
+ {apiKeys ? (
+ <ApiKeyDetailContent
+ scope="project"
+ secretKey={apiKeys.secretKey}
+ publicKey={apiKeys.publicKey}
+ baseUrl={baseUrl}
+ className="mt-4"
+ showMcpSection={false}
+ />
+ ) : (
+ <div className="flex flex-col gap-4">
+ <p className="text-muted-foreground text-sm">
+ You need to create an API key to start tracing your application.
+ You can create more keys later in the project settings.
+ </p>
+ <div className="flex gap-2">
+ <Button
+ onClick={createApiKey}
+ loading={mutCreateApiKey.isPending}
+ className="self-start"
+ >
+ Create new API key
+ </Button>
+ <ActionButton
+ href={`/project/${projectId}/settings/api-keys`}
+ variant="secondary"
+ >
+ Manage API keys
+ </ActionButton>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div>
+ <SubHeader
+ title="2. Add tracing to your application"
+ status={hasTracingConfigured ? "active" : "pending"}
+ />
+ <p className="text-muted-foreground mb-4 text-sm">
+ Langfuse relies on OpenTelemetry to instrument your application and
+ export LLM application/agent traces to Langfuse. You can use one of
+ our SDKs or 50+ framework integrations. Please follow the quickstart
+ in the documentation to add Langfuse to your application.
+ </p>
+ <ActionButton href="https://langfuse.com/docs/observability/get-started">
+ Quickstart guide
+ </ActionButton>
+ </div>
+ </div>
+ );
+};
+
+export default function TracesSetupPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const { project } = useQueryProject();
+
+ // Check if the user has tracing configured
+ // Skip polling entirely if the project flag is already set in the session
+ const { data: hasTracingConfigured } =
+ api.traces.hasTracingConfigured.useQuery(
+ { projectId },
+ {
+ enabled: !!projectId,
+ refetchInterval: project?.hasTraces ? false : 5000,
+ initialData: project?.hasTraces ? true : undefined,
+ staleTime: project?.hasTraces ? Infinity : 0,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const capture = usePostHogClientCapture();
+ useEffect(() => {
+ if (hasTracingConfigured !== undefined) {
+ capture("onboarding:tracing_check_active", {
+ active: hasTracingConfigured,
+ });
+ }
+ }, [hasTracingConfigured, capture]);
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "Tracing Setup",
+ help: {
+ description:
+ "Setup tracing to track and analyze your LLM calls. You can create API keys and integrate Langfuse with your application.",
+ href: "https://langfuse.com/docs/observability/overview",
+ },
+ }}
+ >
+ <div className="flex flex-col gap-4">
+ <TracingSetup
+ projectId={projectId}
+ hasTracingConfigured={hasTracingConfigured ?? false}
+ />
+ </div>
+ </ContainerPage>
+ );
+}
diff --git a/web/src/features/widgets/EditWidgetPage.tsx b/web/src/features/widgets/EditWidgetPage.tsx
new file mode 100644
index 0000000000..0e958ee482
--- /dev/null
+++ b/web/src/features/widgets/EditWidgetPage.tsx
@@ -0,0 +1,137 @@
+import { useRouter } from "next/router";
+import Page from "@/src/components/layouts/page";
+import { api } from "@/src/utils/api";
+import { WidgetForm } from "@/src/features/widgets/components/WidgetForm";
+import { type WidgetSavePayload } from "@/src/features/widgets/components/widgetFormSchema";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+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 EditWidgetPage() {
+ const router = useRouter();
+ const { projectId, widgetId, dashboardId } = router.query as {
+ projectId: string;
+ widgetId: string;
+ dashboardId?: string;
+ };
+
+ // 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(
+ {
+ projectId,
+ widgetId,
+ },
+ {
+ enabled: Boolean(projectId) && Boolean(widgetId),
+ },
+ );
+
+ // Update widget mutation
+ const updateWidgetMutation = api.dashboardWidgets.update.useMutation({
+ onSettled: () => {
+ utils.dashboardWidgets.invalidate();
+ },
+ onSuccess: (data, variables) => {
+ // Which measure/aggregation/chart shapes do users actually save?
+ capture("dashboard:widget_saved", {
+ isNew: false,
+ view: variables.view,
+ chartType: variables.chartType,
+ measures: variables.metrics.map((m) => `${m.agg}:${m.measure}`),
+ dimensionCount: variables.dimensions.length,
+ filterCount: variables.filters.length,
+ });
+ showSuccessToast({
+ title: "Widget updated successfully",
+ description: "Your widget has been updated.",
+ });
+ // Navigate back to dashboard if provided else widgets list
+ if (dashboardId) {
+ router.push(
+ `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${widgetId}`,
+ );
+ } else {
+ router.push(`/project/${projectId}/widgets`);
+ }
+ },
+ onError: (error) => {
+ showErrorToast("Failed to update widget", error.message);
+ },
+ });
+
+ // Handle update widget
+ const handleUpdateWidget = (widgetFormData: WidgetSavePayload) => {
+ if (!widgetId) return;
+
+ updateWidgetMutation.mutate({
+ projectId,
+ widgetId,
+ name: widgetFormData.name,
+ description: widgetFormData.description,
+ view: widgetFormData.view as z.infer<typeof views>,
+ dimensions: widgetFormData.dimensions,
+ metrics: widgetFormData.metrics.map((metric) => ({
+ measure: metric.measure,
+ agg: metric.agg as z.infer<typeof metricAggregations>,
+ })),
+ filters: widgetFormData.filters,
+ chartType: widgetFormData.chartType,
+ chartConfig: widgetFormData.chartConfig,
+ });
+ };
+
+ return (
+ <Page
+ withPadding
+ headerProps={{
+ title: "Edit Widget",
+ help: {
+ description: "Edit an existing widget",
+ },
+ }}
+ >
+ {!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.
+ key={widgetId}
+ projectId={projectId}
+ widgetId={widgetId}
+ onSave={handleUpdateWidget}
+ initialValues={{
+ name: widgetData.name,
+ description: widgetData.description,
+ view: widgetData.view as z.infer<typeof views>,
+ // Pass complete arrays for editing mode
+ metrics: widgetData.metrics,
+ dimensions: widgetData.dimensions,
+ // Keep single values for backward compatibility and fallbacks
+ dimension: widgetData.dimensions.slice().shift()?.field ?? "none",
+ measure: widgetData.metrics.slice().shift()?.measure ?? "count",
+ aggregation:
+ (widgetData.metrics.slice().shift()?.agg as z.infer<
+ typeof metricAggregations
+ >) ?? "count",
+ filters: widgetData.filters,
+ chartType: widgetData.chartType,
+ chartConfig: widgetData.chartConfig,
+ minVersion: widgetData.minVersion,
+ }}
+ />
+ ) : (
+ <div className="flex h-[300px] items-center justify-center">
+ <p className="text-muted-foreground">Loading...</p>
+ </div>
+ )}
+ </Page>
+ );
+}
diff --git a/web/src/features/widgets/NewWidgetPage.tsx b/web/src/features/widgets/NewWidgetPage.tsx
new file mode 100644
index 0000000000..7b834722cf
--- /dev/null
+++ b/web/src/features/widgets/NewWidgetPage.tsx
@@ -0,0 +1,172 @@
+import { useRouter } from "next/router";
+import Page from "@/src/components/layouts/page";
+import { api } from "@/src/utils/api";
+import { WidgetForm } from "@/src/features/widgets";
+import { type WidgetSavePayload } from "@/src/features/widgets/components/widgetFormSchema";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+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 { 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 NewWidgetPage() {
+ const router = useRouter();
+ const { projectId, dashboardId } = router.query as {
+ projectId: string;
+ dashboardId?: string;
+ };
+ const { isV4, isResolved } = useReadPath();
+ const capture = usePostHogClientCapture();
+
+ const dashboards = api.dashboard.allDashboards.useQuery(
+ {
+ projectId,
+ page: 1,
+ limit: 500,
+ orderBy: { column: "updatedAt", order: "DESC" },
+ },
+ { enabled: Boolean(projectId) },
+ );
+
+ const createWidgetMutation = api.dashboardWidgets.create.useMutation({
+ onSuccess: async (data, variables) => {
+ // Which measure/aggregation/chart shapes do users actually save?
+ capture("dashboard:widget_saved", {
+ isNew: true,
+ view: variables.view,
+ chartType: variables.chartType,
+ measures: variables.metrics.map((m) => `${m.agg}:${m.measure}`),
+ dimensionCount: variables.dimensions.length,
+ filterCount: variables.filters.length,
+ });
+ showSuccessToast({
+ title: "Widget created successfully",
+ description: "Your widget has been created.",
+ });
+
+ if (dashboardId) {
+ await router.push(
+ `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${data.widget.id}`,
+ );
+ return;
+ }
+
+ const dashboardData =
+ dashboards.data ?? (await dashboards.refetch()).data;
+
+ if (
+ dashboardData &&
+ !dashboardData.dashboards.some(
+ (dashboard) => dashboard.owner === "PROJECT",
+ )
+ ) {
+ await router.push(`/project/${projectId}/widgets`);
+ } else {
+ setPendingWidgetId(data.widget.id); // store for dialog
+ setDashboardDialogOpen(true);
+ }
+ },
+ onError: (error) => {
+ showErrorToast("Failed to save widget", error.message);
+ },
+ });
+
+ const handleSaveWidget = (widgetData: WidgetSavePayload) => {
+ if (!widgetData.name.trim()) {
+ showErrorToast("Error", "Widget name is required");
+ return;
+ }
+
+ // Prepare the widget data
+ createWidgetMutation.mutate({
+ projectId,
+ name: widgetData.name,
+ description: widgetData.description,
+ view: widgetData.view as z.infer<typeof views>,
+ dimensions: widgetData.dimensions,
+ metrics: widgetData.metrics.map((metric) => ({
+ measure: metric.measure,
+ agg: metric.agg as z.infer<typeof metricAggregations>,
+ })),
+ filters: widgetData.filters,
+ chartType: widgetData.chartType,
+ chartConfig: widgetData.chartConfig,
+ });
+ };
+
+ 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
+ headerProps={{
+ title: "New Widget",
+ help: {
+ description: "Create a new widget",
+ },
+ }}
+ >
+ <WidgetForm
+ // No `key` on the beta flag: WidgetForm derives viewVersion (and its
+ // 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;
+ // the initial mount still seeds the beta-aware default view below.
+ projectId={projectId}
+ onSave={handleSaveWidget}
+ initialValues={{
+ name: "",
+ description: "",
+ view: getDefaultView(isV4),
+ dimension: "none",
+ measure: "count",
+ aggregation: "count",
+ filters: [],
+ chartType: "LINE_TIME_SERIES",
+ chartConfig: { type: "LINE_TIME_SERIES" },
+ }}
+ widgetId={undefined}
+ />
+ {pendingWidgetId && (
+ <SelectDashboardDialog
+ open={dashboardDialogOpen}
+ onOpenChange={setDashboardDialogOpen}
+ projectId={projectId}
+ onSelectDashboard={(dashboardId) => {
+ router.push(
+ `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${pendingWidgetId}`,
+ );
+ }}
+ onSkip={() => {
+ router.push(`/project/${projectId}/widgets`);
+ }}
+ />
+ )}
+ </Page>
+ );
+}
diff --git a/web/src/pages/project/[projectId]/dashboards/new.tsx b/web/src/pages/project/[projectId]/dashboards/new.tsx
index 6ffe61b7d5..84ce6d8d4c 100644
--- a/web/src/pages/project/[projectId]/dashboards/new.tsx
+++ b/web/src/pages/project/[projectId]/dashboards/new.tsx
@@ -1,122 +1 @@
-import { useState } from "react";
-import { useRouter } from "next/router";
-import { api } from "@/src/utils/api";
-import Page from "@/src/components/layouts/page";
-import { Button } from "@/src/components/ui/button";
-import { Input } from "@/src/components/ui/input";
-import { Textarea } from "@/src/components/ui/textarea";
-import { Label } from "@/src/components/ui/label";
-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
-import { showErrorToast } from "@/src/features/notifications/showErrorToast";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-
-export default function NewDashboard() {
- const router = useRouter();
- const { projectId } = router.query as { projectId: string };
-
- // State for new dashboard
- const [dashboardName, setDashboardName] = useState("New Dashboard");
- const [dashboardDescription, setDashboardDescription] = useState("");
-
- // Check project access
- const hasCUDAccess = useHasProjectAccess({
- projectId,
- scope: "dashboards:CUD",
- });
-
- // Mutation for creating a new dashboard
- const createDashboard = api.dashboard.createDashboard.useMutation({
- onSuccess: (data) => {
- showSuccessToast({
- title: "Dashboard created",
- description: "Your new dashboard has been created successfully",
- });
- // Navigate to the newly created dashboard
- router.push(`/project/${projectId}/dashboards/${data.id}`);
- },
- onError: (error) => {
- showErrorToast("Error creating dashboard", error.message);
- },
- });
-
- // Handle form submission
- const handleCreateDashboard = () => {
- if (dashboardName.trim()) {
- createDashboard.mutate({
- projectId,
- name: dashboardName,
- description: dashboardDescription,
- });
- } else {
- showErrorToast("Validation error", "Dashboard name is required");
- }
- };
-
- return (
- <Page
- withPadding
- headerProps={{
- title: "Create Dashboard",
- help: {
- description: "Create a new dashboard for your project",
- },
- actionButtonsRight: (
- <>
- <Button
- variant="outline"
- onClick={() => router.push(`/project/${projectId}/dashboards`)}
- >
- Cancel
- </Button>
- <Button
- onClick={handleCreateDashboard}
- disabled={
- !dashboardName.trim() ||
- createDashboard.isPending ||
- !hasCUDAccess
- }
- loading={createDashboard.isPending}
- >
- Create
- </Button>
- </>
- ),
- }}
- >
- <div className="mx-auto my-8 max-w-xl space-y-6">
- <div className="space-y-2">
- <Label htmlFor="dashboard-name">Dashboard Name</Label>
- <Input
- id="dashboard-name"
- value={dashboardName}
- onChange={(e) => {
- setDashboardName(e.target.value);
- }}
- placeholder="Enter dashboard name"
- required
- />
- </div>
-
- <div className="space-y-2">
- <Label htmlFor="dashboard-description">Description</Label>
- <Textarea
- id="dashboard-description"
- value={dashboardDescription}
- onChange={(e) => {
- setDashboardDescription(e.target.value);
- }}
- placeholder="Describe the purpose of this dashboard. Optional, but very helpful."
- rows={4}
- />
- </div>
-
- <div className="text-muted-foreground text-sm">
- <p>
- After creating the dashboard, you can add widgets to visualize your
- data.
- </p>
- </div>
- </div>
- </Page>
- );
-}
+export { default } from "@/src/features/dashboard/NewDashboardPage";
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx
index 29f53c34f5..66d62c0677 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx
@@ -1,213 +1 @@
-import { DATASET_ITEM_TABS } from "@/src/features/navigation/utils/dataset-item-tabs";
-import { DatasetItemDetailPage } from "@/src/features/datasets/components/DatasetItemDetailPage";
-import { DatasetItemViewModeContent } from "@/src/features/datasets/components/DatasetItemViewModeContent";
-import { DatasetItemVersionedContent } from "@/src/features/datasets/components/DatasetItemVersionedContent";
-import { DatasetVersionHistoryPanel } from "@/src/features/datasets/components/DatasetVersionHistoryPanel";
-import { DatasetVersionWarningBanner } from "@/src/features/datasets/components/DatasetVersionWarningBanner";
-import { api } from "@/src/utils/api";
-import { useDatasetVersion } from "@/src/features/datasets/hooks/useDatasetVersion";
-import { toDatasetSchema } from "@/src/features/datasets/utils/datasetItemUtils";
-import { Switch } from "@/src/components/design-system/Switch/Switch";
-import { Label } from "@/src/components/ui/label";
-import { Button } from "@/src/components/ui/button";
-import useSessionStorage from "@/src/components/useSessionStorage";
-import { History, PanelRightOpen } from "lucide-react";
-import { useState } from "react";
-import {
- RouteParamsPendingFallback,
- useReadyRouteParams,
-} from "@/src/hooks/useReadyRouteParams";
-
-export default function DatasetItemPage() {
- const route = useReadyRouteParams(["projectId", "datasetId", "itemId"]);
- if (!route.ready) return <RouteParamsPendingFallback />;
- return (
- <DatasetItemContent
- projectId={route.params.projectId}
- datasetId={route.params.datasetId}
- itemId={route.params.itemId}
- />
- );
-}
-
-function DatasetItemContent({
- projectId,
- datasetId,
- itemId,
-}: {
- projectId: string;
- datasetId: string;
- itemId: string;
-}) {
- const { selectedVersion, resetToLatest } = useDatasetVersion();
- const isViewingOldVersion = selectedVersion !== null;
-
- const [showDiffMode, setShowDiffMode] = useSessionStorage(
- "datasetItem-showDiff",
- false,
- );
- const [isVersionPanelOpen, setIsVersionPanelOpen] =
- useState(!!selectedVersion);
-
- const routeReady =
- Boolean(projectId) && Boolean(datasetId) && Boolean(itemId);
-
- // Fetch current item
- const item = api.datasets.itemByIdAtVersion.useQuery(
- {
- datasetId,
- projectId,
- datasetItemId: itemId,
- },
- {
- enabled: routeReady,
- refetchOnWindowFocus: false,
- },
- );
-
- // Fetch item at selected version if viewing old version
- const itemAtVersion = api.datasets.itemByIdAtVersion.useQuery(
- {
- projectId,
- datasetId,
- datasetItemId: itemId,
- version: selectedVersion!,
- },
- {
- enabled: routeReady && selectedVersion !== null,
- },
- );
-
- // Fetch dataset
- const dataset = api.datasets.byId.useQuery(
- {
- datasetId,
- projectId,
- },
- { enabled: routeReady },
- );
-
- // Fetch item version history for sidebar indicators
- const itemVersionHistory = api.datasets.itemVersionHistory.useQuery(
- {
- projectId,
- datasetId,
- itemId,
- },
- { enabled: routeReady },
- );
-
- // Check if item was changed at selected version (enables diff toggle)
- // Use 1 second tolerance to account for potential timestamp precision issues
- const itemChangedAtVersion =
- selectedVersion &&
- itemVersionHistory.data?.some(
- (v) => Math.abs(v.getTime() - selectedVersion.getTime()) < 1000,
- );
-
- return (
- <DatasetItemDetailPage
- activeTab={DATASET_ITEM_TABS.ITEM}
- withPadding={false}
- >
- <div className="flex h-full">
- {/* Main content area */}
- <div className="relative flex flex-1 flex-col overflow-auto">
- {/* Sticky banner without padding */}
- {isViewingOldVersion && selectedVersion && (
- <div className="sticky top-0 z-10">
- <DatasetVersionWarningBanner
- selectedVersion={selectedVersion}
- resetToLatest={resetToLatest}
- />
- </div>
- )}
-
- {/* Version panel toggle button */}
- <div className="bg-background sticky top-0 z-10 flex justify-end border-b p-2">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setIsVersionPanelOpen(!isVersionPanelOpen)}
- title={
- isVersionPanelOpen
- ? "Hide version history"
- : "Show version history"
- }
- >
- {isVersionPanelOpen ? (
- <>
- <History className="mr-2 h-4 w-4" />
- Hide Version History
- </>
- ) : (
- <>
- <PanelRightOpen className="mr-2 h-4 w-4" />
- Show Version History
- </>
- )}
- </Button>
- </div>
-
- {/* Content with padding */}
- <div className="px-6 py-4">
- {/* Diff mode toggle */}
- {isViewingOldVersion && selectedVersion && itemChangedAtVersion && (
- <div className="mb-4 flex flex-col gap-2">
- <div className="flex items-center space-x-2">
- <Switch
- id="diff-mode"
- checked={showDiffMode}
- onCheckedChange={setShowDiffMode}
- />
- <Label htmlFor="diff-mode" className="cursor-pointer text-sm">
- Show diff with latest version
- </Label>
- </div>
- </div>
- )}
-
- {/* Item unchanged message */}
- {isViewingOldVersion &&
- selectedVersion &&
- !itemChangedAtVersion && (
- <div className="text-muted-foreground mb-4 text-sm">
- Item unchanged in this version
- </div>
- )}
-
- {/* Main content area */}
- {isViewingOldVersion ? (
- <DatasetItemVersionedContent
- itemAtVersion={itemAtVersion.data ?? null}
- latestItem={item.data ?? null}
- isLoadingVersioned={itemAtVersion.isLoading}
- isLoadingLatest={item.isLoading}
- showDiffMode={showDiffMode}
- itemChangedAtVersion={!!itemChangedAtVersion}
- dataset={toDatasetSchema(dataset.data ?? null)}
- />
- ) : (
- <DatasetItemViewModeContent
- item={item.data ?? null}
- isLoading={item.isLoading}
- dataset={toDatasetSchema(dataset.data ?? null)}
- />
- )}
- </div>
- </div>
-
- {/* Version history sidebar */}
- {isVersionPanelOpen && (
- <div className="w-1/4 shrink-0 border-l">
- <DatasetVersionHistoryPanel
- projectId={projectId}
- datasetId={datasetId}
- itemVersions={itemVersionHistory.data}
- />
- </div>
- )}
- </div>
- </DatasetItemDetailPage>
- );
-}
+export { default } from "@/src/features/datasets/DatasetItemPage";
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/items/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/items/index.tsx
index 21f9c89bdb..b348e620b5 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/items/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/items/index.tsx
@@ -1,188 +1 @@
-import { api } from "@/src/utils/api";
-import {
- getDatasetTabs,
- DATASET_TABS,
-} from "@/src/features/navigation/utils/dataset-tabs";
-import { DatasetItemsTable } from "@/src/features/datasets/components/DatasetItemsTable";
-import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
-import { NewDatasetItemButton } from "@/src/features/datasets/components/NewDatasetItemButton";
-import { UploadDatasetCsvButton } from "@/src/features/datasets/components/UploadDatasetCsvButton";
-import { Button } from "@/src/components/ui/button";
-import { History, MoreVertical } from "lucide-react";
-import Page from "@/src/components/layouts/page";
-import { DatasetItemsOnboarding } from "@/src/components/onboarding/DatasetItemsOnboarding";
-import { SidePanel, SidePanelContent } from "@/src/components/ui/side-panel";
-import { DatasetVersionHistoryPanel } from "@/src/features/datasets/components/DatasetVersionHistoryPanel";
-import { DatasetVersionWarningBanner } from "@/src/features/datasets/components/DatasetVersionWarningBanner";
-import { useState } from "react";
-import { useDatasetVersion } from "@/src/features/datasets/hooks/useDatasetVersion";
-import { getDatasetBreadcrumb } from "@/src/features/datasets/utils/getDatasetBreadcrumb";
-import {
- RouteParamsPendingFallback,
- useReadyRouteParams,
-} from "@/src/hooks/useReadyRouteParams";
-import { DatasetActionMenu } from "@/src/features/datasets/components/DatasetActionMenu";
-
-export default function DatasetItemsPage() {
- const route = useReadyRouteParams(["projectId", "datasetId"]);
- if (!route.ready) return <RouteParamsPendingFallback />;
- return (
- <DatasetItemsView
- projectId={route.params.projectId}
- datasetId={route.params.datasetId}
- />
- );
-}
-
-function DatasetItemsView({
- projectId,
- datasetId,
-}: {
- projectId: string;
- datasetId: string;
-}) {
- const { selectedVersion, resetToLatest } = useDatasetVersion();
- const isViewingOldVersion = selectedVersion !== null;
-
- const [isVersionPanelOpen, setIsVersionPanelOpen] = useState(false);
-
- const dataset = api.datasets.byId.useQuery(
- {
- datasetId,
- projectId,
- },
- { enabled: Boolean(projectId) && Boolean(datasetId) },
- );
-
- const totalDatasetItemCount = api.datasets.countItemsByDatasetId.useQuery(
- {
- projectId,
- datasetId,
- },
- { enabled: Boolean(projectId) && Boolean(datasetId) },
- );
-
- const showOnboarding =
- totalDatasetItemCount.isSuccess && totalDatasetItemCount.data === 0;
-
- // Fetch change counts since selected version
- const changeCounts = api.datasets.countChangesSinceVersion.useQuery(
- {
- projectId,
- datasetId,
- version: selectedVersion!,
- },
- {
- enabled: selectedVersion !== null,
- },
- );
-
- const handlePanelOpenChange = (open: boolean) => {
- setIsVersionPanelOpen(open);
- };
-
- const breadcrumb = getDatasetBreadcrumb(
- projectId,
- datasetId,
- dataset.data?.name,
- );
-
- return (
- <Page
- headerProps={{
- title: dataset.data?.name ?? "",
- itemType: "DATASET",
- breadcrumb,
- tabsProps: {
- tabs: getDatasetTabs(projectId, datasetId),
- activeTab: DATASET_TABS.ITEMS,
- },
- actionButtonsRight: (
- <>
- {!showOnboarding && (
- <>
- <NewDatasetItemButton
- projectId={projectId}
- datasetId={datasetId}
- />
- <UploadDatasetCsvButton
- projectId={projectId}
- datasetId={datasetId}
- />
- </>
- )}
- <DetailPageNav
- currentId={datasetId}
- path={(entry) =>
- `/project/${projectId}/datasets/${entry.id}/items/`
- }
- listKey="datasets"
- />
- <DatasetActionMenu
- projectId={projectId}
- datasetId={datasetId}
- datasetName={dataset.data?.name ?? ""}
- datasetDescription={dataset.data?.description ?? undefined}
- datasetMetadata={dataset.data?.metadata}
- datasetInputSchema={dataset.data?.inputSchema ?? undefined}
- datasetExpectedOutputSchema={
- dataset.data?.expectedOutputSchema ?? undefined
- }
- >
- {({ getTriggerProps }) => (
- <Button
- variant="outline"
- size="icon"
- aria-label="Dataset actions"
- {...getTriggerProps()}
- >
- <MoreVertical className="h-4 w-4" />
- </Button>
- )}
- </DatasetActionMenu>
- <Button
- variant="outline"
- size="icon"
- onClick={() => setIsVersionPanelOpen(!isVersionPanelOpen)}
- title="Version History"
- >
- <History className="h-4 w-4" />
- </Button>
- </>
- ),
- }}
- >
- {showOnboarding ? (
- <DatasetItemsOnboarding projectId={projectId} datasetId={datasetId} />
- ) : (
- <div className="grid flex-1 grid-cols-[1fr_auto] overflow-hidden">
- <div className="flex h-full flex-col overflow-hidden">
- {isViewingOldVersion && selectedVersion && (
- <DatasetVersionWarningBanner
- selectedVersion={selectedVersion}
- resetToLatest={resetToLatest}
- changeCounts={changeCounts.data}
- />
- )}
- <DatasetItemsTable projectId={projectId} datasetId={datasetId} />
- </div>
- <SidePanel
- id="version-history-panel"
- openState={{
- open: isVersionPanelOpen,
- onOpenChange: handlePanelOpenChange,
- }}
- mobileTitle="Version History"
- >
- <SidePanelContent className="h-full">
- <DatasetVersionHistoryPanel
- projectId={projectId}
- datasetId={datasetId}
- />
- </SidePanelContent>
- </SidePanel>
- </div>
- )}
- </Page>
- );
-}
+export { default } from "@/src/features/datasets/DatasetItemsPage";
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/runs/[runId].tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/runs/[runId].tsx
index 68d1ec6cf2..fd754af1fe 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/runs/[runId].tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/runs/[runId].tsx
@@ -1,200 +1 @@
-import { Button } from "@/src/components/ui/button";
-import { JSONView } from "@/src/components/ui/CodeJsonViewer";
-import { DatasetRunItemsByRunTable } from "@/src/features/datasets/components/DatasetRunItemsByRunTable";
-import { DeleteDatasetRunDialogController } from "@/src/features/datasets/components/DeleteDatasetRunDialogController";
-import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
-import { api } from "@/src/utils/api";
-import { Columns3, MoreVertical, Trash } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/router";
-import { useEffect } from "react";
-import Page from "@/src/components/layouts/page";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/src/components/ui/dropdown-menu";
-import {
- SidePanel,
- SidePanelContent,
- SidePanelHeader,
- SidePanelTitle,
-} from "@/src/components/ui/side-panel";
-import { Skeleton } from "@/src/components/ui/skeleton";
-import { getDatasetBreadcrumb } from "@/src/features/datasets/utils/getDatasetBreadcrumb";
-import { useExperimentAccess } from "@/src/features/experiments/hooks/useExperimentAccess";
-import { singleRunToExperimentsUrl } from "@/src/features/experiments/utils/experimentUrlTranslation";
-import { buildLocalIsoDatePresentation } from "@/src/utils/dates";
-
-function DatasetRunLegacy() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
- const datasetId = router.query.datasetId as string;
- const runId = router.query.runId as string;
-
- const dataset = api.datasets.byId.useQuery({
- datasetId,
- projectId,
- });
- const run = api.datasets.runById.useQuery({
- datasetId,
- projectId,
- runId,
- });
- const breadcrumb = getDatasetBreadcrumb(
- projectId,
- datasetId,
- dataset.data?.name,
- );
-
- const preparedDate = buildLocalIsoDatePresentation({
- date: run.data?.datasetVersion,
- });
-
- return (
- <Page
- headerProps={{
- title: run.data?.name ?? runId,
- itemType: "EXPERIMENT",
- breadcrumb: [
- ...breadcrumb,
- {
- name: "Experiments",
- href: `/project/${projectId}/datasets/${datasetId}/experiments`,
- },
- ],
- actionButtonsRight: (
- <>
- <Link
- href={{
- pathname: `/project/${projectId}/datasets/${datasetId}/compare`,
- query: { runs: [runId] },
- }}
- >
- <Button>
- <Columns3 className="mr-2 h-4 w-4" />
- <span>Compare</span>
- </Button>
- </Link>
- <DetailPageNav
- currentId={runId}
- path={(entry) =>
- `/project/${projectId}/datasets/${datasetId}/runs/${entry.id}`
- }
- listKey="datasetRuns"
- />
- <DeleteDatasetRunDialogController
- projectId={projectId}
- datasetRunId={runId}
- datasetId={datasetId}
- redirectUrl={`/project/${projectId}/datasets/${datasetId}/experiments`}
- >
- {({ disabled, openDialog }) => (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline" size="icon">
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem disabled={disabled} onSelect={openDialog}>
- <Trash className="h-4 w-4" />
- <span>Delete</span>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </DeleteDatasetRunDialogController>
- </>
- ),
- }}
- >
- <div className="grid flex-1 grid-cols-[1fr_auto] overflow-hidden">
- <div className="flex h-full flex-col overflow-hidden">
- <DatasetRunItemsByRunTable
- projectId={projectId}
- datasetId={datasetId}
- datasetRunId={runId}
- datasetVersion={run.data?.datasetVersion}
- />
- </div>
- <SidePanel
- mobileTitle="Experiment run details"
- id="experiment-run-details"
- >
- <SidePanelHeader>
- <SidePanelTitle>Experiment run details</SidePanelTitle>
- </SidePanelHeader>
- <SidePanelContent>
- {run.isPending ? (
- <Skeleton className="h-full w-full" />
- ) : (
- <>
- {run.data?.datasetVersion && preparedDate && (
- <div className="flex flex-col gap-2 p-1">
- <span className="text-sm font-bold">Dataset Version</span>
- <Link
- href={`/project/${projectId}/datasets/${datasetId}/items?version=${run.data.datasetVersion.toISOString()}`}
- className="text-link hover:text-link-hover text-sm"
- >
- <span title={preparedDate.title}>
- {preparedDate.display}
- </span>
- </Link>
- </div>
- )}
- {!!run.data?.description && (
- <JSONView
- json={run.data.description}
- title="Description"
- className="w-full overflow-y-auto"
- />
- )}
- {!!run.data?.metadata && (
- <JSONView
- json={run.data.metadata}
- title="Metadata"
- className="w-full overflow-y-auto"
- />
- )}
- {!run.data?.description && !run.data?.metadata && (
- <div className="text-muted-foreground mt-1 px-1 text-sm">
- No description or metadata for this run
- </div>
- )}
- </>
- )}
- </SidePanelContent>
- </SidePanel>
- </div>
- </Page>
- );
-}
-
-export default function DatasetRun() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
- const runId = router.query.runId as string;
- const { isExperimentsBetaActive, isInitializing } = useExperimentAccess();
-
- useEffect(() => {
- if (
- !router.isReady ||
- isInitializing ||
- !isExperimentsBetaActive ||
- !projectId ||
- !runId
- ) {
- return;
- }
-
- router.replace(singleRunToExperimentsUrl(projectId, runId));
- }, [isExperimentsBetaActive, isInitializing, projectId, router, runId]);
-
- if (!router.isReady || isInitializing || isExperimentsBetaActive) {
- return <Skeleton className="h-full w-full" />;
- }
-
- return <DatasetRunLegacy />;
-}
+export { default } from "@/src/features/datasets/DatasetRunPage";
diff --git a/web/src/pages/project/[projectId]/experiments/results.tsx b/web/src/pages/project/[projectId]/experiments/results.tsx
index 56dd3f036e..32c1c8a4a6 100644
--- a/web/src/pages/project/[projectId]/experiments/results.tsx
+++ b/web/src/pages/project/[projectId]/experiments/results.tsx
@@ -1,204 +1 @@
-import { useRouter } from "next/router";
-import Page from "@/src/components/layouts/page";
-import { api } from "@/src/utils/api";
-import { ExperimentItemsTable } from "@/src/features/experiments/components/table";
-import { ExperimentOverviewPanel } from "@/src/features/experiments/components/ExperimentOverviewPanel";
-import {
- OverviewPanelLayout,
- OverviewPanelToggle,
-} from "@/src/components/layouts/overview-panel";
-import useSessionStorage from "@/src/components/useSessionStorage";
-import { useCallback, useEffect } from "react";
-import { ExperimentDisplaySettings } from "@/src/features/experiments/components/ExperimentDisplaySettings";
-import { ExperimentFormatSetting } from "@/src/features/experiments/components/ExperimentFormatSetting";
-import { useExperimentAccess } from "@/src/features/experiments/hooks/useExperimentAccess";
-import { Spinner } from "@/src/components/design-system/Spinner/Spinner";
-import { ExperimentSelectionControls } from "@/src/features/experiments/components/ExperimentSelectionControls";
-import { useIoRenderModeLocalStorage } from "@/src/components/table/data-table-io-render-mode-switch";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import {
- diffModeChangedProps,
- layoutChangedProps,
-} from "@/src/features/experiments/lib/analytics";
-import {
- useExperimentResultsState,
- type ExperimentDiffMode,
- type ExperimentResultsLayout,
-} from "@/src/features/experiments/hooks/useExperimentResultsState";
-
-export default function ExperimentResults() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
-
- const {
- baselineId,
- hasBaseline,
- setBaseline,
- clearBaseline,
- comparisonIds,
- setComparisonIds,
- layout,
- setLayout,
- diffMode,
- setDiffMode,
- itemVisibility,
- setItemVisibility,
- allExperimentIds,
- colorExperimentIds,
- } = useExperimentResultsState();
- const [ioRenderMode, setIoRenderMode] = useIoRenderModeLocalStorage(
- "experiment-items",
- "json",
- );
-
- const [isOverviewOpen, setIsOverviewOpen] = useSessionStorage(
- "overview-panel-experiment-detail",
- false,
- );
-
- const capture = usePostHogClientCapture();
-
- // Is the new score-matrix layout adopted, and diff mode — Expected → Output
- // in particular — used at all? Captured on the menu pick rather than on the
- // URL state, which also changes on navigation, on a restored view, and (for
- // the layout) as a side effect of choosing Expected → Output.
- const handleLayoutChange = useCallback(
- (newLayout: ExperimentResultsLayout) => {
- if (newLayout !== layout) {
- capture(
- "experiment:layout_changed",
- layoutChangedProps({
- tableName: "experiment-items",
- layout: newLayout,
- comparisonCount: comparisonIds.length,
- }),
- );
- }
- setLayout(newLayout);
- },
- [capture, layout, comparisonIds.length, setLayout],
- );
-
- const handleDiffModeChange = useCallback(
- (newDiffMode: ExperimentDiffMode) => {
- if (newDiffMode !== diffMode) {
- capture(
- "experiment:diff_mode_changed",
- diffModeChangedProps({
- tableName: "experiment-items",
- mode: newDiffMode,
- comparisonCount: comparisonIds.length,
- }),
- );
- }
- setDiffMode(newDiffMode);
- },
- [capture, diffMode, comparisonIds.length, setDiffMode],
- );
-
- const { isExperimentsBetaActive, isInitializing } = useExperimentAccess();
-
- useEffect(() => {
- if (isInitializing || isExperimentsBetaActive || !projectId) return;
-
- router.replace(`/project/${projectId}/datasets`);
- }, [isExperimentsBetaActive, isInitializing, projectId, router]);
-
- // Fetch experiment to get dataset ID and other details
- const { data: experiment } = api.experiments.byId.useQuery(
- {
- projectId,
- experimentId: baselineId ?? "",
- },
- {
- enabled: Boolean(projectId && baselineId) && isExperimentsBetaActive,
- },
- );
-
- // Show spinner while session loads or while redirecting when beta is off
- if (!isExperimentsBetaActive) {
- return (
- <Page headerProps={{ title: "Experiments" }}>
- <div className="flex h-full items-center justify-center">
- <Spinner size="xl" variant="muted" />
- </div>
- </Page>
- );
- }
-
- return (
- <Page
- headerProps={{
- title: "",
- itemType: "EXPERIMENT",
- breadcrumb: [
- { name: "Experiments", href: `/project/${projectId}/experiments` },
- ],
- actionButtonsLeft: (
- <ExperimentSelectionControls
- projectId={projectId}
- baselineId={baselineId}
- baselineName={experiment?.name}
- comparisonIds={comparisonIds}
- colorExperimentIds={colorExperimentIds}
- selectedExperimentCount={allExperimentIds.length}
- onBaselineChange={setBaseline}
- onBaselineClear={clearBaseline}
- onComparisonIdsChange={setComparisonIds}
- />
- ),
- actionButtonsRight: (
- <>
- <ExperimentDisplaySettings
- layout={layout}
- onLayoutChange={handleLayoutChange}
- diffMode={diffMode}
- onDiffModeChange={handleDiffModeChange}
- itemVisibility={itemVisibility}
- onItemVisibilityChange={setItemVisibility}
- hasComparisons={comparisonIds.length > 0}
- hasBaseline={hasBaseline}
- />
-
- <OverviewPanelToggle
- open={isOverviewOpen}
- onOpenChange={setIsOverviewOpen}
- />
- </>
- ),
- }}
- >
- <OverviewPanelLayout
- open={isOverviewOpen}
- persistId={`experiment-detail-${baselineId ?? "none"}`}
- mainContent={
- <ExperimentItemsTable
- // The shared table body's memo comparator does not look at the
- // column definitions, so a format change alone never reaches the
- // cells. Remounting is what makes the switch take effect.
- key={ioRenderMode}
- projectId={projectId}
- ioRenderMode={ioRenderMode}
- toolbarSettings={
- <ExperimentFormatSetting
- ioRenderMode={ioRenderMode}
- onIoRenderModeChange={setIoRenderMode}
- />
- }
- />
- }
- overviewContent={
- <ExperimentOverviewPanel
- key={baselineId ?? "no-baseline"}
- projectId={projectId}
- experiment={experiment ?? undefined}
- />
- }
- defaultPrimarySize={75}
- defaultSecondarySize={25}
- minPrimarySize={50}
- maxSecondarySize={40}
- />
- </Page>
- );
-}
+export { default } from "@/src/features/experiments/ExperimentResultsPage";
diff --git a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
index fdfdb86e41..e5bfe8800b 100644
--- a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
+++ b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
@@ -1,196 +1 @@
-/* eslint-disable no-nested-ternary */
-import { useRouter } from "next/router";
-import { ActionButton } from "@/src/components/ActionButton";
-import Page from "@/src/components/layouts/page";
-import { PromptTable } from "@/src/features/prompts/components/prompts-table";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { Download, UploadIcon, PlusIcon } from "lucide-react";
-import { api } from "@/src/utils/api";
-import { PromptsOnboarding } from "@/src/components/onboarding/PromptsOnboarding";
-import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
-import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";
-import PromptMetrics from "@/src/features/prompts/PromptMetricsPage";
-import { useQueryParams, StringParam } from "use-query-params";
-import { useState } from "react";
-import { AutomationButton } from "@/src/features/automations/components/AutomationButton";
-import { ImportPromptsButtonDialogController } from "@/src/features/prompts/components/ImportPromptsButtonDialogController";
-import { Button } from "@/src/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/src/components/ui/dropdown-menu";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { toast } from "sonner";
-
-export default function PromptsWithFolder() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
- const routeSegments = router.query.folder;
- const [queryParams] = useQueryParams({ folder: StringParam });
- const folderQueryParam = queryParams.folder || "";
-
- // Determine view type based on route segments
- // NOTE: there is a bug here, that if the user directly accesses a prompt name which ends in `/metrics`,
- // the prompt metrics page will be shown for a non-existing prompt name. Doesn't happen if the user clicks
- // this in the UI (we URL encode here and don't strip metrics). We could resolve this with another API call
- // to check the prompt name existence.
- const segmentsArray = Array.isArray(routeSegments) ? routeSegments : [];
- const isMetricsPage =
- segmentsArray.length > 0 &&
- segmentsArray[segmentsArray.length - 1] === "metrics";
- const promptNameFromRoute =
- segmentsArray.length > 0
- ? isMetricsPage
- ? segmentsArray.slice(0, -1).join("/")
- : segmentsArray.join("/")
- : "";
-
- const hasCUDAccess = useHasProjectAccess({
- projectId,
- scope: "prompts:CUD",
- });
- const hasReadAccess = useHasProjectAccess({
- projectId,
- scope: "prompts:read",
- });
- const promptLimit = useEntitlementLimit("prompt-management-count-prompts");
- const utils = api.useUtils();
- const [isExporting, setIsExporting] = useState(false);
- const capture = usePostHogClientCapture();
-
- const handleExport = async (mode: "latest" | "all") => {
- setIsExporting(true);
- try {
- const data = await utils.prompts.exportAll.fetch({
- projectId,
- includeAllVersions: mode === "all",
- });
- const json = JSON.stringify(data, null, 2);
- const blob = new Blob([json], { type: "application/json" });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `langfuse-prompts-${mode}-${new Date().toISOString().slice(0, 10)}.json`;
- a.click();
- URL.revokeObjectURL(url);
- capture("prompts:bulk_export", { mode });
- } catch {
- toast.error("Failed to export prompts. Please try again.");
- } finally {
- setIsExporting(false);
- }
- };
-
- // Check if the project has any prompts
- const { data: hasAnyPrompt, isLoading } = api.prompts.hasAny.useQuery(
- { projectId },
- {
- enabled: !!projectId,
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- },
- );
-
- const { data: count } = api.prompts.count.useQuery(
- { projectId },
- {
- enabled: !!projectId && !promptNameFromRoute, // Only count when on folder view
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- },
- );
-
- const showOnboarding = !isLoading && !hasAnyPrompt;
-
- // Decide what to render: metrics, detail, or folder view
- if (promptNameFromRoute.length > 0) {
- if (isMetricsPage) {
- return <PromptMetrics promptName={promptNameFromRoute} />;
- }
- return <PromptDetail promptName={promptNameFromRoute} />;
- }
-
- return (
- <Page
- headerProps={{
- title: "Prompts",
- help: {
- description:
- "Manage and version your prompts in Langfuse. Edit and update them via the UI and SDK. Retrieve the production version via the SDKs. Learn more in the docs.",
- href: "https://langfuse.com/docs/prompt-management/get-started",
- },
- actionButtonsRight: (
- <>
- {projectId && <AutomationButton projectId={projectId} />}
- {hasReadAccess && (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline" disabled={isExporting}>
- <UploadIcon className="mr-1 h-4 w-4" />
- {isExporting ? "Exporting…" : "Export"}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => handleExport("latest")}>
- Latest version per prompt
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => handleExport("all")}>
- All versions
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- {projectId && (
- <ImportPromptsButtonDialogController projectId={projectId}>
- {({ disabled, openDialog }) => (
- <Button
- variant="outline"
- disabled={Boolean(disabled)}
- title={disabled?.reason}
- onClick={openDialog}
- >
- <Download className="mr-1 h-4 w-4" />
- Import
- </Button>
- )}
- </ImportPromptsButtonDialogController>
- )}
- <ActionButton
- icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}
- hasAccess={hasCUDAccess}
- href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ""}`}
- trackingEventName="prompts:new_form_open"
- variant="default"
- usageLimit={
- typeof promptLimit === "number"
- ? {
- current: Number(count?.totalCount ?? 0),
- max: promptLimit,
- }
- : undefined
- }
- >
- New prompt
- </ActionButton>
- </>
- ),
- }}
- scrollable={showOnboarding}
- >
- {/* Show onboarding screen if project has no prompts */}
- {showOnboarding ? (
- <PromptsOnboarding projectId={projectId} />
- ) : (
- <PromptTable key={folderQueryParam} />
- )}
- </Page>
- );
-}
+export { default } from "@/src/features/prompts/PromptsPage";
diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
index 378be414ff..dbd6578f23 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
@@ -1,131 +1 @@
-/* eslint-disable no-nested-ternary */
-import Header from "@/src/components/layouts/header";
-import ContainerPage from "@/src/components/layouts/container-page";
-import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
-import { Button } from "@/src/components/ui/button";
-import { Card } from "@/src/components/ui/card";
-import { IntegrationSettingsSkeleton } from "@/src/features/analytics-integrations/components/IntegrationSettingsSkeleton";
-import Link from "next/link";
-import { useRouter } from "next/router";
-import { useHasEntitlement } from "@/src/features/entitlements/hooks";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { api, type RouterOutputs } from "@/src/utils/api";
-import { deriveSyncStatus } from "@/src/features/blobstorage-integration/deriveSyncStatus";
-import { type BlobStorageSyncStatus } from "@/src/features/blobstorage-integration/types";
-import { BlobStorageIntegrationContainer } from "@/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer";
-import { BlobStorageStatusSection } from "@/src/features/blobstorage-integration/components/BlobStorageStatusSection";
-
-const syncStatusToBadge: Record<BlobStorageSyncStatus, string> = {
- up_to_date: "active",
- running: "running",
- queued: "queued",
- idle: "pending",
- disabled: "disabled",
- error: "error",
-};
-
-const syncStatusFromConfig = (
- config: NonNullable<RouterOutputs["blobStorageIntegration"]["get"]["config"]>,
-): BlobStorageSyncStatus =>
- deriveSyncStatus({
- enabled: config.enabled,
- lastError: config.lastError,
- lastSyncAt: config.lastSyncAt ? new Date(config.lastSyncAt) : null,
- nextSyncAt: config.nextSyncAt ? new Date(config.nextSyncAt) : null,
- runStartedAt: config.runStartedAt ? new Date(config.runStartedAt) : null,
- });
-
-export default function BlobStorageIntegrationSettings() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
- const hasAccess = useHasProjectAccess({
- projectId,
- scope: "integrations:CRUD",
- });
- const hasEntitlement = useHasEntitlement("scheduled-blob-exports");
- const canLoadConfig = hasAccess && hasEntitlement;
- const state = api.blobStorageIntegration.get.useQuery(
- { projectId },
- {
- enabled: canLoadConfig,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: 50 * 60 * 1000, // 50 minutes
- refetchInterval: (query) => {
- const cfg = query.state.data?.config;
- if (!cfg) return false;
- const status = syncStatusFromConfig(cfg);
- return status === "running" || status === "queued" ? 5_000 : false;
- },
- },
- );
-
- const syncStatus =
- state.isLoading || !canLoadConfig || !state.data?.config
- ? undefined
- : syncStatusFromConfig(state.data.config);
-
- return (
- <ContainerPage
- headerProps={{
- title: "Blob Storage Integration",
- breadcrumb: [
- { name: "Settings", href: `/project/${projectId}/settings` },
- ],
- actionButtonsLeft: (
- <>
- {syncStatus && <StatusBadge type={syncStatusToBadge[syncStatus]} />}
- </>
- ),
- actionButtonsRight: (
- <Button asChild variant="secondary">
- <Link
- href="https://langfuse.com/docs/api-and-data-platform/features/export-to-blob-storage"
- target="_blank"
- >
- Integration Docs ↗
- </Link>
- </Button>
- ),
- }}
- >
- <p className="text-primary mb-4 text-sm">
- Configure scheduled exports of your trace data to AWS S3, S3-compatible
- storages, or Azure Blob Storage. Set up a hourly, daily, or weekly
- export to your own storage for data analysis or backup purposes. Use the
- &quot;Validate&quot; button to test your configuration by uploading a
- small test file, and the &quot;Run Now&quot; button to trigger an
- immediate export.
- </p>
- {!hasEntitlement ? (
- <p className="text-sm">
- This feature is not available in your current plan.
- </p>
- ) : !hasAccess ? (
- <p className="text-sm">
- Your current role does not grant you access to these settings, please
- reach out to your project admin or owner.
- </p>
- ) : (
- <>
- {state.data?.config && (
- <BlobStorageStatusSection config={state.data.config} />
- )}
- <Header title="Configuration" className="mt-8" />
- <Card className="p-3">
- {!state.data ? (
- <IntegrationSettingsSkeleton />
- ) : (
- <BlobStorageIntegrationContainer
- config={state.data.config ?? null}
- projectId={projectId}
- writeMode={state.data.writeMode}
- />
- )}
- </Card>
- </>
- )}
- </ContainerPage>
- );
-}
+export { default } from "@/src/features/blobstorage-integration/BlobStorageIntegrationPage";
diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
index ca75694bf6..c31baeeccd 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
@@ -1,197 +1 @@
-/* eslint-disable no-nested-ternary */
-import { PostHogLogo } from "@/src/components/PosthogLogo";
-import Header from "@/src/components/layouts/header";
-import ContainerPage from "@/src/components/layouts/container-page";
-import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
-import { Button } from "@/src/components/design-system/Button/Button";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { PostHogStatusSection } from "@/src/features/posthog-integration/components/PostHogStatusSection";
-import {
- PostHogIntegrationForm,
- type PostHogIntegrationFormValues,
-} from "@/src/features/posthog-integration/components/PostHogIntegrationForm";
-import {
- LEGACY_ANALYTICS_EXPORTER_CUTOFF,
- type V4WriteMode,
- type ExportSourceContext,
-} from "@langfuse/shared";
-// Shared export-source UI adapters; policy in export-source-policy.ts.
-import {
- buildExportSourceContext,
- getExportSourceFormValue,
-} from "@/src/features/analytics-integrations/exportSource";
-import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
-import { useQueryProject } from "@/src/features/projects/hooks";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { api } from "@/src/utils/api";
-import { type RouterOutput } from "@/src/utils/types";
-import { Card } from "@/src/components/ui/card";
-import { IntegrationSettingsSkeleton } from "@/src/features/analytics-integrations/components/IntegrationSettingsSkeleton";
-import Link from "next/link";
-import { useRouter } from "next/router";
-import { useMemo } from "react";
-
-export default function PosthogIntegrationSettings() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
-
- const hasAccess = useHasProjectAccess({
- projectId,
- scope: "integrations:CRUD",
- });
- const state = api.posthogIntegration.get.useQuery(
- { projectId },
- {
- enabled: hasAccess,
- },
- );
-
- const { project } = useQueryProject();
-
- // A persisted fault outranks active/inactive: it is the state the admin has
- // to act on, and it is cleared by the next successful sync.
- const status =
- state.isLoading || !hasAccess
- ? undefined
- : state.data?.config?.lastError
- ? "error"
- : state.data?.config?.enabled
- ? "active"
- : "inactive";
-
- return (
- <ContainerPage
- headerProps={{
- title: "PostHog Integration",
- breadcrumb: [
- { name: "Settings", href: `/project/${projectId}/settings` },
- ],
- actionButtonsLeft: <>{status && <StatusBadge type={status} />}</>,
- actionButtonsRight: (
- <Button
- href="https://langfuse.com/integrations/analytics/posthog"
- text="Integration Docs"
- variant="secondary"
- />
- ),
- }}
- >
- <p className="text-primary mb-4 text-sm">
- We have teamed up with{" "}
- <Link href="https://posthog.com" className="underline">
- PostHog
- </Link>{" "}
- (OSS product analytics) to make Langfuse events/metrics available in
- your PostHog dashboards. Upon activation, all historical data from your
- project will be synced. After the initial sync, new data is
- automatically synced every hour to keep your PostHog dashboards up to
- date.
- </p>
- {!hasAccess && (
- <p className="text-sm">
- You current role does not grant you access to these settings, please
- reach out to your project admin or owner.
- </p>
- )}
- {hasAccess && (
- <>
- <Header title="Configuration" />
- <Card className="p-3">
- <PostHogLogo className="text-foreground mb-4 w-36" />
- {!state.data || !project ? (
- <IntegrationSettingsSkeleton />
- ) : (
- <ConnectedPostHogIntegrationForm
- // Draft lifetime = entity identity, so background refetches
- // cannot reset a draft in progress.
- key={`${projectId}:${state.data.config ? "configured" : "new"}`}
- state={state.data.config ?? undefined}
- projectId={projectId}
- writeMode={state.data.writeMode}
- projectCreatedAt={project.createdAt}
- />
- )}
- </Card>
- </>
- )}
- {state.data?.config && (
- <PostHogStatusSection config={state.data.config} />
- )}
- </ContainerPage>
- );
-}
-
-const ConnectedPostHogIntegrationForm = ({
- state,
- projectId,
- writeMode,
- projectCreatedAt,
-}: {
- state?: NonNullable<RouterOutput["posthogIntegration"]["get"]["config"]>;
- projectId: string;
- writeMode: V4WriteMode;
- // Raw ISO string, not a Date: a Date built in the parent's JSX would be a new
- // reference on every render and would defeat the memo below.
- projectCreatedAt: string;
-}) => {
- const capture = usePostHogClientCapture();
- const { isLangfuseCloud } = useLangfuseCloudRegion();
- const integrationCreatedAt = state?.createdAt;
- const exportSourceCtx: ExportSourceContext = useMemo(
- () =>
- buildExportSourceContext({
- writeMode,
- isCloud: isLangfuseCloud,
- projectCreatedAt: new Date(projectCreatedAt),
- integrationCreatedAt: integrationCreatedAt
- ? new Date(integrationCreatedAt)
- : null,
- exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,
- }),
- [writeMode, isLangfuseCloud, projectCreatedAt, integrationCreatedAt],
- );
- const defaultExportSource = getExportSourceFormValue(
- state?.exportSource,
- exportSourceCtx,
- );
-
- const utils = api.useUtils();
- const mut = api.posthogIntegration.update.useMutation({
- onSuccess: () => {
- utils.posthogIntegration.invalidate();
- },
- });
- const mutDelete = api.posthogIntegration.delete.useMutation({
- onSuccess: () => {
- utils.posthogIntegration.invalidate();
- },
- });
-
- function onSubmit(values: PostHogIntegrationFormValues) {
- capture("integrations:posthog_form_submitted");
- mut.mutate({
- projectId,
- ...values,
- });
- }
-
- return (
- <PostHogIntegrationForm
- actionState={
- mut.isPending ? "saving" : mutDelete.isPending ? "resetting" : "idle"
- }
- configurationState={state ? "configured" : "new"}
- defaultValues={{
- posthogHostname: state?.posthogHostName ?? "",
- posthogProjectApiKey: "",
- enabled: state?.enabled ?? false,
- exportSource: defaultExportSource,
- }}
- exportSourceContext={exportSourceCtx}
- projectApiKeyDisplay={state?.posthogApiKeyDisplay}
- resetError={mutDelete.error?.message}
- onSubmit={onSubmit}
- onReset={() => mutDelete.mutateAsync({ projectId })}
- />
- );
-};
+export { default } from "@/src/features/posthog-integration/PostHogIntegrationPage";
diff --git a/web/src/pages/project/[projectId]/traces/setup.tsx b/web/src/pages/project/[projectId]/traces/setup.tsx
index af25f7a661..ed168d8a13 100644
--- a/web/src/pages/project/[projectId]/traces/setup.tsx
+++ b/web/src/pages/project/[projectId]/traces/setup.tsx
@@ -1,149 +1 @@
-import React, { useEffect, useState } from "react";
-import { useRouter } from "next/router";
-import { api, reportNonTrpcError } from "@/src/utils/api";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import ContainerPage from "@/src/components/layouts/container-page";
-import { ActionButton } from "@/src/components/ActionButton";
-import { SubHeader } from "@/src/components/layouts/header";
-import { Button } from "@/src/components/ui/button";
-import { ApiKeyDetailContent } from "@/src/features/public-api/components/ApiKeyDetailContent";
-import { useLangfuseBaseUrl } from "@/src/features/public-api/hooks/useLangfuseEnvCode";
-import { type RouterOutput } from "@/src/utils/types";
-import { useQueryProject } from "@/src/features/projects/hooks";
-
-export const TracingSetup = ({
- projectId,
- hasTracingConfigured,
-}: {
- projectId: string;
- hasTracingConfigured?: boolean;
-}) => {
- const baseUrl = useLangfuseBaseUrl();
- const [apiKeys, setApiKeys] = useState<
- RouterOutput["projectApiKeys"]["create"] | null
- >(null);
- const utils = api.useUtils();
- const mutCreateApiKey = api.projectApiKeys.create.useMutation({
- onSuccess: (data) => {
- utils.projectApiKeys.invalidate();
- setApiKeys(data);
- },
- });
-
- const createApiKey = async () => {
- try {
- await mutCreateApiKey.mutateAsync({ projectId });
- } catch (error) {
- reportNonTrpcError(error, "setup");
- }
- };
-
- return (
- <div className="space-y-8">
- <div>
- <SubHeader title="1. Get API keys" />
- {apiKeys ? (
- <ApiKeyDetailContent
- scope="project"
- secretKey={apiKeys.secretKey}
- publicKey={apiKeys.publicKey}
- baseUrl={baseUrl}
- className="mt-4"
- showMcpSection={false}
- />
- ) : (
- <div className="flex flex-col gap-4">
- <p className="text-muted-foreground text-sm">
- You need to create an API key to start tracing your application.
- You can create more keys later in the project settings.
- </p>
- <div className="flex gap-2">
- <Button
- onClick={createApiKey}
- loading={mutCreateApiKey.isPending}
- className="self-start"
- >
- Create new API key
- </Button>
- <ActionButton
- href={`/project/${projectId}/settings/api-keys`}
- variant="secondary"
- >
- Manage API keys
- </ActionButton>
- </div>
- </div>
- )}
- </div>
-
- <div>
- <SubHeader
- title="2. Add tracing to your application"
- status={hasTracingConfigured ? "active" : "pending"}
- />
- <p className="text-muted-foreground mb-4 text-sm">
- Langfuse relies on OpenTelemetry to instrument your application and
- export LLM application/agent traces to Langfuse. You can use one of
- our SDKs or 50+ framework integrations. Please follow the quickstart
- in the documentation to add Langfuse to your application.
- </p>
- <ActionButton href="https://langfuse.com/docs/observability/get-started">
- Quickstart guide
- </ActionButton>
- </div>
- </div>
- );
-};
-
-export default function TracesSetupPage() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
- const { project } = useQueryProject();
-
- // Check if the user has tracing configured
- // Skip polling entirely if the project flag is already set in the session
- const { data: hasTracingConfigured } =
- api.traces.hasTracingConfigured.useQuery(
- { projectId },
- {
- enabled: !!projectId,
- refetchInterval: project?.hasTraces ? false : 5000,
- initialData: project?.hasTraces ? true : undefined,
- staleTime: project?.hasTraces ? Infinity : 0,
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- },
- );
-
- const capture = usePostHogClientCapture();
- useEffect(() => {
- if (hasTracingConfigured !== undefined) {
- capture("onboarding:tracing_check_active", {
- active: hasTracingConfigured,
- });
- }
- }, [hasTracingConfigured, capture]);
-
- return (
- <ContainerPage
- headerProps={{
- title: "Tracing Setup",
- help: {
- description:
- "Setup tracing to track and analyze your LLM calls. You can create API keys and integrate Langfuse with your application.",
- href: "https://langfuse.com/docs/observability/overview",
- },
- }}
- >
- <div className="flex flex-col gap-4">
- <TracingSetup
- projectId={projectId}
- hasTracingConfigured={hasTracingConfigured ?? false}
- />
- </div>
- </ContainerPage>
- );
-}
+export { default, TracingSetup } from "@/src/features/traces/TracesSetupPage";
diff --git a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
index 2682a944c8..0a68136969 100644
--- a/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/widgets/[widgetId]/index.tsx
@@ -1,137 +1 @@
-import { useRouter } from "next/router";
-import Page from "@/src/components/layouts/page";
-import { api } from "@/src/utils/api";
-import { WidgetForm } from "@/src/features/widgets/components/WidgetForm";
-import { type WidgetSavePayload } from "@/src/features/widgets/components/widgetFormSchema";
-import { showErrorToast } from "@/src/features/notifications/showErrorToast";
-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();
- const { projectId, widgetId, dashboardId } = router.query as {
- projectId: string;
- widgetId: string;
- dashboardId?: string;
- };
-
- // 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(
- {
- projectId,
- widgetId,
- },
- {
- enabled: Boolean(projectId) && Boolean(widgetId),
- },
- );
-
- // Update widget mutation
- const updateWidgetMutation = api.dashboardWidgets.update.useMutation({
- onSettled: () => {
- utils.dashboardWidgets.invalidate();
- },
- onSuccess: (data, variables) => {
- // Which measure/aggregation/chart shapes do users actually save?
- capture("dashboard:widget_saved", {
- isNew: false,
- view: variables.view,
- chartType: variables.chartType,
- measures: variables.metrics.map((m) => `${m.agg}:${m.measure}`),
- dimensionCount: variables.dimensions.length,
- filterCount: variables.filters.length,
- });
- showSuccessToast({
- title: "Widget updated successfully",
- description: "Your widget has been updated.",
- });
- // Navigate back to dashboard if provided else widgets list
- if (dashboardId) {
- router.push(
- `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${widgetId}`,
- );
- } else {
- router.push(`/project/${projectId}/widgets`);
- }
- },
- onError: (error) => {
- showErrorToast("Failed to update widget", error.message);
- },
- });
-
- // Handle update widget
- const handleUpdateWidget = (widgetFormData: WidgetSavePayload) => {
- if (!widgetId) return;
-
- updateWidgetMutation.mutate({
- projectId,
- widgetId,
- name: widgetFormData.name,
- description: widgetFormData.description,
- view: widgetFormData.view as z.infer<typeof views>,
- dimensions: widgetFormData.dimensions,
- metrics: widgetFormData.metrics.map((metric) => ({
- measure: metric.measure,
- agg: metric.agg as z.infer<typeof metricAggregations>,
- })),
- filters: widgetFormData.filters,
- chartType: widgetFormData.chartType,
- chartConfig: widgetFormData.chartConfig,
- });
- };
-
- return (
- <Page
- withPadding
- headerProps={{
- title: "Edit Widget",
- help: {
- description: "Edit an existing widget",
- },
- }}
- >
- {!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.
- key={widgetId}
- projectId={projectId}
- widgetId={widgetId}
- onSave={handleUpdateWidget}
- initialValues={{
- name: widgetData.name,
- description: widgetData.description,
- view: widgetData.view as z.infer<typeof views>,
- // Pass complete arrays for editing mode
- metrics: widgetData.metrics,
- dimensions: widgetData.dimensions,
- // Keep single values for backward compatibility and fallbacks
- dimension: widgetData.dimensions.slice().shift()?.field ?? "none",
- measure: widgetData.metrics.slice().shift()?.measure ?? "count",
- aggregation:
- (widgetData.metrics.slice().shift()?.agg as z.infer<
- typeof metricAggregations
- >) ?? "count",
- filters: widgetData.filters,
- chartType: widgetData.chartType,
- chartConfig: widgetData.chartConfig,
- minVersion: widgetData.minVersion,
- }}
- />
- ) : (
- <div className="flex h-[300px] items-center justify-center">
- <p className="text-muted-foreground">Loading...</p>
- </div>
- )}
- </Page>
- );
-}
+export { default } from "@/src/features/widgets/EditWidgetPage";
diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsx
index e1204fdd76..f37410d269 100644
--- a/web/src/pages/project/[projectId]/widgets/new.tsx
+++ b/web/src/pages/project/[projectId]/widgets/new.tsx
@@ -1,172 +1 @@
-import { useRouter } from "next/router";
-import Page from "@/src/components/layouts/page";
-import { api } from "@/src/utils/api";
-import { WidgetForm } from "@/src/features/widgets";
-import { type WidgetSavePayload } from "@/src/features/widgets/components/widgetFormSchema";
-import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
-import { showErrorToast } from "@/src/features/notifications/showErrorToast";
-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 { 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() {
- const router = useRouter();
- const { projectId, dashboardId } = router.query as {
- projectId: string;
- dashboardId?: string;
- };
- const { isV4, isResolved } = useReadPath();
- const capture = usePostHogClientCapture();
-
- const dashboards = api.dashboard.allDashboards.useQuery(
- {
- projectId,
- page: 1,
- limit: 500,
- orderBy: { column: "updatedAt", order: "DESC" },
- },
- { enabled: Boolean(projectId) },
- );
-
- const createWidgetMutation = api.dashboardWidgets.create.useMutation({
- onSuccess: async (data, variables) => {
- // Which measure/aggregation/chart shapes do users actually save?
- capture("dashboard:widget_saved", {
- isNew: true,
- view: variables.view,
- chartType: variables.chartType,
- measures: variables.metrics.map((m) => `${m.agg}:${m.measure}`),
- dimensionCount: variables.dimensions.length,
- filterCount: variables.filters.length,
- });
- showSuccessToast({
- title: "Widget created successfully",
- description: "Your widget has been created.",
- });
-
- if (dashboardId) {
- await router.push(
- `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${data.widget.id}`,
- );
- return;
- }
-
- const dashboardData =
- dashboards.data ?? (await dashboards.refetch()).data;
-
- if (
- dashboardData &&
- !dashboardData.dashboards.some(
- (dashboard) => dashboard.owner === "PROJECT",
- )
- ) {
- await router.push(`/project/${projectId}/widgets`);
- } else {
- setPendingWidgetId(data.widget.id); // store for dialog
- setDashboardDialogOpen(true);
- }
- },
- onError: (error) => {
- showErrorToast("Failed to save widget", error.message);
- },
- });
-
- const handleSaveWidget = (widgetData: WidgetSavePayload) => {
- if (!widgetData.name.trim()) {
- showErrorToast("Error", "Widget name is required");
- return;
- }
-
- // Prepare the widget data
- createWidgetMutation.mutate({
- projectId,
- name: widgetData.name,
- description: widgetData.description,
- view: widgetData.view as z.infer<typeof views>,
- dimensions: widgetData.dimensions,
- metrics: widgetData.metrics.map((metric) => ({
- measure: metric.measure,
- agg: metric.agg as z.infer<typeof metricAggregations>,
- })),
- filters: widgetData.filters,
- chartType: widgetData.chartType,
- chartConfig: widgetData.chartConfig,
- });
- };
-
- 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
- headerProps={{
- title: "New Widget",
- help: {
- description: "Create a new widget",
- },
- }}
- >
- <WidgetForm
- // No `key` on the beta flag: WidgetForm derives viewVersion (and its
- // 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;
- // the initial mount still seeds the beta-aware default view below.
- projectId={projectId}
- onSave={handleSaveWidget}
- initialValues={{
- name: "",
- description: "",
- view: getDefaultView(isV4),
- dimension: "none",
- measure: "count",
- aggregation: "count",
- filters: [],
- chartType: "LINE_TIME_SERIES",
- chartConfig: { type: "LINE_TIME_SERIES" },
- }}
- widgetId={undefined}
- />
- {pendingWidgetId && (
- <SelectDashboardDialog
- open={dashboardDialogOpen}
- onOpenChange={setDashboardDialogOpen}
- projectId={projectId}
- onSelectDashboard={(dashboardId) => {
- router.push(
- `/project/${projectId}/dashboards/${dashboardId}?addWidgetId=${pendingWidgetId}`,
- );
- }}
- onSkip={() => {
- router.push(`/project/${projectId}/widgets`);
- }}
- />
- )}
- </Page>
- );
-}
+export { default } from "@/src/features/widgets/NewWidgetPage";