Skip to content

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

feat(ui, api): Add Ordering functionality to traces (#750)

Felix Wu11167835870f
diff --git a/jest.config.mjs b/jest.config.mjs
index 34287d3b5a..ecc80917e5 100644
--- a/jest.config.mjs
+++ b/jest.config.mjs
@@ -18,6 +18,8 @@ const serverTestConfig = {
testEnvironment: "jest-environment-node",
};
+// To avoid the "Cannot use import statement outside a module" errors while transforming ESM.
+const esModules = ["superjson"];
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
@@ -26,7 +28,10 @@ const config = {
verbose: true,
projects: [
await createJestConfig(clientTestConfig)(),
- await createJestConfig(serverTestConfig)(),
+ {
+ ...(await createJestConfig(serverTestConfig)()),
+ transformIgnorePatterns: [`/node_modules/(?!(${esModules.join("|")})/)`],
+ },
],
};
diff --git a/package-lock.json b/package-lock.json
index 5ebfa37745..8e7f7338e4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -94,9 +94,11 @@
"zod": "^3.22.4"
},
"devDependencies": {
+ "@jedmao/location": "^3.0.0",
"@playwright/test": "^1.40.1",
"@release-it/bumper": "^6.0.1",
"@testing-library/jest-dom": "^6.1.5",
+ "@testing-library/react": "^14.1.2",
"@types/bcryptjs": "^2.4.6",
"@types/cors": "^2.8.17",
"@types/eslint": "^8.56.0",
@@ -2196,6 +2198,12 @@
"node": ">=8"
}
},
+ "node_modules/@jedmao/location": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@jedmao/location/-/location-3.0.0.tgz",
+ "integrity": "sha512-p7mzNlgJbCioUYLUEKds3cQG4CHONVFJNYqMe6ocEtENCL/jYmMo1Q3ApwsMmU+L0ZkaDJEyv4HokaByLoPwlQ==",
+ "dev": true
+ },
"node_modules/@jest/console": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz",
@@ -5603,6 +5611,82 @@
"url": "https://github.com/sponsors/tannerlinsley"
}
},
+ "node_modules/@testing-library/dom": {
+ "version": "9.3.3",
+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-9.3.3.tgz",
+ "integrity": "sha512-fB0R+fa3AUqbLHWyxXa2kGVtf1Fe1ZZFr0Zp6AIbIAzXb2mKbEXl+PCQNUOaq5lbTab5tfctfXRNsWXxa2f7Aw==",
+ "dev": true,
+ "dependencies": {
+ "@babel/code-frame": "^7.10.4",
+ "@babel/runtime": "^7.12.5",
+ "@types/aria-query": "^5.0.1",
+ "aria-query": "5.1.3",
+ "chalk": "^4.1.0",
+ "dom-accessibility-api": "^0.5.9",
+ "lz-string": "^1.5.0",
+ "pretty-format": "^27.0.2"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/aria-query": {
+ "version": "5.1.3",
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz",
+ "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==",
+ "dev": true,
+ "dependencies": {
+ "deep-equal": "^2.0.5"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "dev": true,
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/pretty-format": {
+ "version": "27.5.1",
+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
+ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
+ "dev": true,
+ "dependencies": {
+ "ansi-regex": "^5.0.1",
+ "ansi-styles": "^5.0.0",
+ "react-is": "^17.0.1"
+ },
+ "engines": {
+ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/pretty-format/node_modules/ansi-styles": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
+ "dev": true,
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
+ "dev": true
+ },
"node_modules/@testing-library/jest-dom": {
"version": "6.1.5",
"resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.1.5.tgz",
@@ -5644,6 +5728,24 @@
}
}
},
+ "node_modules/@testing-library/react": {
+ "version": "14.1.2",
+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-14.1.2.tgz",
+ "integrity": "sha512-z4p7DVBTPjKM5qDZ0t5ZjzkpSNb+fZy1u6bzO7kk8oeGagpPCAtgh4cx1syrfp7a+QWkM021jGqjJaxJJnXAZg==",
+ "dev": true,
+ "dependencies": {
+ "@babel/runtime": "^7.12.5",
+ "@testing-library/dom": "^9.0.0",
+ "@types/react-dom": "^18.0.0"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0"
+ }
+ },
"node_modules/@tootallnate/once": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
@@ -5768,6 +5870,12 @@
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
"devOptional": true
},
+ "node_modules/@types/aria-query": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
+ "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
+ "dev": true
+ },
"node_modules/@types/babel__core": {
"version": "7.20.4",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.4.tgz",
@@ -8352,6 +8460,38 @@
}
}
},
+ "node_modules/deep-equal": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz",
+ "integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==",
+ "dev": true,
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.0",
+ "call-bind": "^1.0.5",
+ "es-get-iterator": "^1.1.3",
+ "get-intrinsic": "^1.2.2",
+ "is-arguments": "^1.1.1",
+ "is-array-buffer": "^3.0.2",
+ "is-date-object": "^1.0.5",
+ "is-regex": "^1.1.4",
+ "is-shared-array-buffer": "^1.0.2",
+ "isarray": "^2.0.5",
+ "object-is": "^1.1.5",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.4",
+ "regexp.prototype.flags": "^1.5.1",
+ "side-channel": "^1.0.4",
+ "which-boxed-primitive": "^1.0.2",
+ "which-collection": "^1.0.1",
+ "which-typed-array": "^1.1.13"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/deep-extend": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
@@ -13015,6 +13155,15 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0"
}
},
+ "node_modules/lz-string": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
+ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
+ "dev": true,
+ "bin": {
+ "lz-string": "bin/bin.js"
+ }
+ },
"node_modules/macos-release": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/macos-release/-/macos-release-3.2.0.tgz",
@@ -13584,6 +13733,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/object-is": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz",
+ "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==",
+ "dev": true,
+ "dependencies": {
+ "call-bind": "^1.0.2",
+ "define-properties": "^1.1.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
diff --git a/package.json b/package.json
index 1d7df9eac2..904585003d 100644
--- a/package.json
+++ b/package.json
@@ -109,9 +109,11 @@
"zod": "^3.22.4"
},
"devDependencies": {
+ "@jedmao/location": "^3.0.0",
"@playwright/test": "^1.40.1",
"@release-it/bumper": "^6.0.1",
"@testing-library/jest-dom": "^6.1.5",
+ "@testing-library/react": "^14.1.2",
"@types/bcryptjs": "^2.4.6",
"@types/cors": "^2.8.17",
"@types/eslint": "^8.56.0",
diff --git a/src/__tests__/features/orderBy/hooks/useOrderByState.clienttest.tsx b/src/__tests__/features/orderBy/hooks/useOrderByState.clienttest.tsx
new file mode 100644
index 0000000000..67279c3391
--- /dev/null
+++ b/src/__tests__/features/orderBy/hooks/useOrderByState.clienttest.tsx
@@ -0,0 +1,110 @@
+/* eslint-disable @typescript-eslint/no-unsafe-assignment */
+/* eslint-disable @typescript-eslint/no-unsafe-call */
+import { cleanup, render } from "@testing-library/react";
+
+import { TestRouter } from "@/src/__tests__/fixtures/TestRouter";
+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
+import { LocationMock } from "@jedmao/location";
+import NextAdapterPages from "next-query-params/pages";
+import { useRouter } from "next/router";
+import { QueryParamProvider } from "use-query-params";
+
+afterEach(cleanup);
+
+jest.mock("next/router", () => ({
+ useRouter: jest.fn(),
+}));
+
+const { location: savedLocation } = window;
+
+// The test for the useOrderByState hook
+describe("useOrderByState hook", () => {
+ let testRouter: TestRouter;
+ let locationMock: LocationMock;
+
+ beforeAll(() => {
+ // @ts-expect-error - TS only allows to delete optional params; but here we want to delete it
+ // as it will be set in beforeEach
+ delete window.location;
+ });
+
+ beforeEach(() => {
+ jest.resetAllMocks();
+ locationMock = new LocationMock("https://langfuse.com");
+ testRouter = new TestRouter(locationMock);
+ window.location = locationMock;
+
+ (useRouter as jest.Mock).mockReturnValue(testRouter);
+ });
+
+ afterAll(() => {
+ window.location = savedLocation;
+ });
+
+ test("orderBy takes the default value if no url param is given", () => {
+ const result = render(
+ <QueryParamProvider adapter={NextAdapterPages}>
+ <UseOrderByStateExample />
+ </QueryParamProvider>,
+ );
+
+ expect(result.queryByText(/column Column 1, order DESC/)).toBeTruthy();
+ });
+
+ test("setOrderBy updates orderBy query param", () => {
+ const result = render(
+ <QueryParamProvider adapter={NextAdapterPages}>
+ <UseOrderByStateExample />
+ </QueryParamProvider>,
+ );
+
+ result.queryByText(/Set Order/)!.click();
+ result.rerender(
+ <QueryParamProvider adapter={NextAdapterPages}>
+ <UseOrderByStateExample />
+ </QueryParamProvider>,
+ );
+
+ expect(result.queryByText(/column Column 2, order ASC/)).toBeTruthy();
+ expect(locationMock.searchParams.get("orderBy")).toBe(
+ "column-Column 2_order-ASC",
+ );
+ });
+
+ test("orderBy reads the given param from the url", () => {
+ locationMock.replace(
+ "https://langfuse.com?orderBy=column-Column 3_order-DESC",
+ );
+
+ const result = render(
+ <QueryParamProvider adapter={NextAdapterPages}>
+ <UseOrderByStateExample />
+ </QueryParamProvider>,
+ );
+
+ expect(result.queryByText(/column Column 3, order DESC/)).toBeTruthy();
+ });
+});
+
+const UseOrderByStateExample = () => {
+ const [orderBy, setOrderBy] = useOrderByState({
+ column: "Column 1",
+ order: "DESC",
+ });
+
+ return (
+ <>
+ <h1>{`column ${orderBy?.column}, order ${orderBy?.order}`}</h1>
+ <button
+ onClick={() => {
+ setOrderBy({
+ column: "Column 2",
+ order: "ASC",
+ });
+ }}
+ >
+ Set Order
+ </button>
+ </>
+ );
+};
diff --git a/src/__tests__/features/orderBy/server/orderByToPrisma.clienttest.ts b/src/__tests__/features/orderBy/server/orderByToPrisma.clienttest.ts
new file mode 100644
index 0000000000..e04b2dcece
--- /dev/null
+++ b/src/__tests__/features/orderBy/server/orderByToPrisma.clienttest.ts
@@ -0,0 +1,36 @@
+import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";
+import { tracesTableCols } from "@/src/server/api/definitions/tracesTable";
+import { Prisma } from "@prisma/client";
+
+// The test for the orderByToPrisma function
+describe("orderByToPrisma (Convert orderBy to Prisma.sql)", () => {
+ test("orderByToPrisma returns default sql when orderBy=null", () => {
+ expect(orderByToPrismaSql(null, tracesTableCols)).toStrictEqual(
+ Prisma.sql`ORDER BY t.timestamp DESC`,
+ );
+ });
+
+ test("orderByToPrisma returns correct clause for orderBy column included in column defs", () => {
+ expect(
+ orderByToPrismaSql(
+ {
+ column: "latency",
+ order: "ASC",
+ },
+ tracesTableCols,
+ ),
+ ).toStrictEqual(Prisma.sql`ORDER BY tl.latency ASC`);
+ });
+
+ test("orderByToPrisma throws error for orderBy column not included in column defs", () => {
+ expect(() =>
+ orderByToPrismaSql(
+ {
+ column: "InvalidCol",
+ order: "ASC",
+ },
+ tracesTableCols,
+ ),
+ ).toThrow(/Invalid filter column: InvalidCol/);
+ });
+});
diff --git a/src/__tests__/fixtures/TestRouter.ts b/src/__tests__/fixtures/TestRouter.ts
new file mode 100644
index 0000000000..f02863765e
--- /dev/null
+++ b/src/__tests__/fixtures/TestRouter.ts
@@ -0,0 +1,56 @@
+/* eslint-disable @typescript-eslint/no-unsafe-member-access */
+/* eslint-disable @typescript-eslint/no-unsafe-call */
+import { type Router } from "next/router";
+import type { UrlObject } from "url";
+import { type LocationMock } from "@jedmao/location";
+
+type PartialRouter = Partial<Router>;
+
+export const BASE_URL = "https://langfuse.com";
+
+/**
+ * A Router to be used for testing which provides the bare minimum needed
+ * for the useQueryParam(s) hook and NextAdapter to work.
+ */
+export class TestRouter implements PartialRouter {
+ isReady = true;
+ pathname = "/";
+ private currentUrl = "";
+ private history: string[] = [];
+
+ constructor(private locationMock: LocationMock) {}
+
+ replace = (url: string | UrlObject) => {
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string, @typescript-eslint/restrict-template-expressions
+ this.locationMock.assign(`${BASE_URL}${url}`);
+ this.currentUrl = TestRouter.getURLString(url);
+ this.locationMock.assign(`${BASE_URL}${this.currentUrl}`);
+ return Promise.resolve(true);
+ };
+
+ push = (url: string | UrlObject) => {
+ this.history.push(this.currentUrl);
+ this.currentUrl = TestRouter.getURLString(url);
+ this.locationMock.assign(`${BASE_URL}${this.currentUrl}`);
+ return Promise.resolve(true);
+ };
+
+ setIsReady = (isReady: boolean) => {
+ this.isReady = isReady;
+ };
+
+ get asPath() {
+ return this.pathname;
+ }
+
+ static getURLString(url: string | UrlObject): string {
+ if (typeof url === "string") {
+ return url;
+ }
+ return `${url.pathname}${url.search}`;
+ }
+
+ getParams(): URLSearchParams {
+ return new URL(`${BASE_URL}${this.currentUrl}`).searchParams;
+ }
+}
diff --git a/src/__tests__/server/api/routers/traces.servertest.ts b/src/__tests__/server/api/routers/traces.servertest.ts
new file mode 100644
index 0000000000..6ec28d1691
--- /dev/null
+++ b/src/__tests__/server/api/routers/traces.servertest.ts
@@ -0,0 +1,107 @@
+/** @jest-environment node */
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { prisma } from "@/src/server/db";
+import type { Session } from "next-auth";
+
+describe("Traces TRPC Router", () => {
+ beforeEach(async () => await pruneDatabase());
+ afterEach(async () => await pruneDatabase());
+
+ const session: Session = {
+ expires: "1",
+ user: {
+ id: "clgb17vnp000008jjere5g15i",
+ name: "John Doe",
+ projects: [
+ {
+ id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ role: "ADMIN",
+ name: "test",
+ },
+ ],
+ featureFlags: {
+ templateFlag: true,
+ },
+ admin: true,
+ },
+ };
+
+ const ctx = createInnerTRPCContext({ session });
+ const caller = appRouter.createCaller({ ...ctx, prisma });
+
+ test("traces.all RPC returns an array of traces", async () => {
+ const trace = {
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ };
+ await prisma.trace.create({
+ data: { ...trace, projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ });
+
+ const traces = await caller.traces.all({
+ page: 0,
+ limit: 10,
+ // projectId from `seed.ts`
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: null,
+ searchQuery: "",
+ orderBy: null,
+ });
+ expect(traces).toBeDefined();
+ expect(traces).toMatchObject([trace]);
+ });
+
+ test("traces.all RPC orders traces by userId", async () => {
+ const traceTmpl = {
+ name: "trace-name",
+ userId: "user-1",
+ metadata: { key: "value" },
+ release: "1.0.0",
+ version: "2.0.0",
+ };
+ const trace1 = traceTmpl;
+ const trace2 = { ...traceTmpl, userId: "user-2" };
+ await prisma.trace.create({
+ data: { ...traceTmpl, projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ });
+ await prisma.trace.create({
+ data: {
+ ...trace2,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ const tracesASC = await caller.traces.all({
+ page: 0,
+ limit: 10,
+ // projectId from `seed.ts`
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: null,
+ searchQuery: "",
+ orderBy: {
+ column: "userId",
+ order: "ASC",
+ },
+ });
+ expect(tracesASC).toMatchObject([trace1, trace2]);
+
+ const tracesDESC = await caller.traces.all({
+ page: 0,
+ limit: 10,
+ // projectId from `seed.ts`
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: null,
+ searchQuery: "",
+ orderBy: {
+ column: "userId",
+ order: "DESC",
+ },
+ });
+ expect(tracesDESC).toMatchObject([trace2, trace1]);
+ });
+});
diff --git a/src/components/table/data-table.tsx b/src/components/table/data-table.tsx
index db2b39ca6a..421e072525 100644
--- a/src/components/table/data-table.tsx
+++ b/src/components/table/data-table.tsx
@@ -1,28 +1,30 @@
"use client";
+import DocPopup from "@/src/components/layouts/doc-popup";
+import { DataTablePagination } from "@/src/components/table/data-table-pagination";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import { type OrderByState } from "@/src/features/orderBy/types";
+import { cn } from "@/src/utils/tailwind";
import {
flexRender,
getCoreRowModel,
+ getFilteredRowModel,
useReactTable,
type ColumnFiltersState,
- getFilteredRowModel,
type OnChangeFn,
type PaginationState,
type RowSelectionState,
type VisibilityState,
} from "@tanstack/react-table";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/src/components/ui/table";
import { useState } from "react";
-import { DataTablePagination } from "@/src/components/table/data-table-pagination";
-import { type LangfuseColumnDef } from "@/src/components/table/types";
-import DocPopup from "@/src/components/layouts/doc-popup";
interface DataTableProps<TData, TValue> {
columns: LangfuseColumnDef<TData, TValue>[];
@@ -36,6 +38,8 @@ interface DataTableProps<TData, TValue> {
setRowSelection?: OnChangeFn<RowSelectionState>;
columnVisibility?: VisibilityState;
onColumnVisibilityChange?: OnChangeFn<VisibilityState>;
+ orderBy?: OrderByState;
+ setOrderBy?: (s: OrderByState) => void;
help?: { description: string; href: string };
}
@@ -55,8 +59,11 @@ export function DataTable<TData extends object, TValue>({
columnVisibility,
onColumnVisibilityChange,
help,
+ orderBy,
+ setOrderBy,
}: DataTableProps<TData, TValue>) {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
+
const table = useReactTable({
data: data.data ?? [],
columns,
@@ -93,17 +100,54 @@ export function DataTable<TData extends object, TValue>({
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
+ const sortingEnabled =
+ header.column.columnDef.enableSorting;
return header.column.getIsVisible() ? (
<TableHead
key={header.id}
- className="whitespace-nowrap p-2"
+ className={cn(
+ sortingEnabled ? "cursor-pointer" : null,
+ "whitespace-nowrap p-2",
+ )}
+ title={sortingEnabled ? "Sort by this column" : ""}
+ onClick={(event) => {
+ event.preventDefault(); // Add this line
+
+ if (
+ !setOrderBy ||
+ !header.column.columnDef.id ||
+ !sortingEnabled
+ ) {
+ return;
+ }
+
+ if (orderBy?.column === header.column.columnDef.id) {
+ setOrderBy({
+ column: header.column.columnDef.id,
+ order: orderBy.order === "ASC" ? "DESC" : "ASC",
+ });
+ } else {
+ setOrderBy({
+ column: header.column.columnDef.id,
+ order: "DESC",
+ });
+ }
+ }}
>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
+ {header.isPlaceholder ? null : (
+ <>
+ <div className="select-none">
+ {flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+
+ {orderBy?.column === header.column.columnDef.id
+ ? renderOrderingIndicator(orderBy)
+ : null}
+ </div>
+ </>
+ )}
</TableHead>
) : null;
})}
@@ -163,3 +207,9 @@ export function DataTable<TData extends object, TValue>({
</>
);
}
+
+function renderOrderingIndicator(orderBy?: OrderByState) {
+ if (!orderBy) return;
+ if (orderBy.order === "ASC") return <span className="ml-1">▲</span>;
+ else return <span className="ml-1">▼</span>;
+}
diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsx
index 3ded3c86c5..121a0ea320 100644
--- a/src/components/table/use-cases/traces.tsx
+++ b/src/components/table/use-cases/traces.tsx
@@ -1,20 +1,25 @@
import { DeleteTrace } from "@/src/components/delete-trace";
-import { TraceTableMultiSelectAction } from "@/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action";
import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";
+import { StarTraceToggle } from "@/src/components/star-toggle";
import { DataTable } from "@/src/components/table/data-table";
+import { TraceTableMultiSelectAction } from "@/src/components/table/data-table-multi-select-actions/trace-table-multi-select-action";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import TableLink from "@/src/components/table/table-link";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
import { TokenUsageBadge } from "@/src/components/token-usage-badge";
import { Checkbox } from "@/src/components/ui/checkbox";
+import { JSONView } from "@/src/components/ui/code";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { type FilterState } from "@/src/features/filters/types";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { tracesTableColsWithOptions } from "@/src/server/api/definitions/tracesTable";
import { api } from "@/src/utils/api";
import { formatInterval, utcDateOffsetByDays } from "@/src/utils/dates";
import { type RouterInput, type RouterOutput } from "@/src/utils/types";
import { type Score } from "@prisma/client";
+import { type RowSelectionState } from "@tanstack/react-table";
import { useEffect, useState } from "react";
import {
NumberParam,
@@ -23,10 +28,6 @@ import {
useQueryParams,
withDefault,
} from "use-query-params";
-import { StarTraceToggle } from "@/src/components/star-toggle";
-import { JSONView } from "@/src/components/ui/code";
-import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { type RowSelectionState } from "@tanstack/react-table";
export type TracesTableRow = {
bookmarked: boolean;
@@ -76,6 +77,10 @@ export default function TracesTable({
value: utcDateOffsetByDays(-14),
},
]);
+ const [orderByState, setOrderByState] = useOrderByState({
+ column: "timestamp",
+ order: "DESC",
+ });
const userIdFilter: FilterState = userId
? [
@@ -100,6 +105,7 @@ export default function TracesTable({
projectId,
filter: filterState,
searchQuery,
+ orderBy: orderByState,
});
const totalCount = traces.data?.slice(1)[0]?.totalCount ?? 0;
useEffect(() => {
@@ -173,6 +179,7 @@ export default function TracesTable({
{
accessorKey: "bookmarked",
header: undefined,
+ id: "bookmarked",
cell: ({ row }) => {
const bookmarked = row.getValue("bookmarked");
const traceId = row.getValue("id");
@@ -191,6 +198,7 @@ export default function TracesTable({
{
accessorKey: "id",
header: "ID",
+ id: "id",
cell: ({ row }) => {
const value = row.getValue("id");
return value && typeof value === "string" ? (
@@ -200,21 +208,26 @@ export default function TracesTable({
/>
) : undefined;
},
+ enableSorting: true,
},
{
accessorKey: "timestamp",
header: "Timestamp",
+ id: "timestamp",
enableHiding: true,
+ enableSorting: true,
},
{
accessorKey: "name",
header: "Name",
+ id: "name",
enableHiding: true,
},
{
accessorKey: "userId",
enableColumnFilter: !omittedFilter.find((f) => f === "userId"),
header: "User ID",
+ id: "userId",
cell: ({ row }) => {
const value = row.getValue("userId");
return value && typeof value === "string" ? (
@@ -226,6 +239,7 @@ export default function TracesTable({
) : undefined;
},
enableHiding: true,
+ enableSorting: true,
},
{
accessorKey: "sessionId",
@@ -245,6 +259,7 @@ export default function TracesTable({
},
{
accessorKey: "latency",
+ id: "latency",
header: "Latency",
// add seconds to the end of the latency
cell: ({ row }) => {
@@ -252,8 +267,10 @@ export default function TracesTable({
return value !== undefined ? formatInterval(value) : undefined;
},
enableHiding: true,
+ enableSorting: true,
},
{
+ // TODO: Enable Ordering By Usage (not covered by API yet)
accessorKey: "usage",
header: "Usage",
cell: ({ row }) => {
@@ -275,6 +292,7 @@ export default function TracesTable({
},
{
accessorKey: "scores",
+ id: "scores",
header: "Scores",
enableColumnFilter: !omittedFilter.find((f) => f === "scores"),
cell: ({ row }) => {
@@ -314,13 +332,17 @@ export default function TracesTable({
},
{
accessorKey: "version",
+ id: "version",
header: "Version",
enableHiding: true,
+ enableSorting: true,
},
{
accessorKey: "release",
+ id: "release",
header: "Release",
enableHiding: true,
+ enableSorting: true,
},
{
accessorKey: "action",
@@ -392,6 +414,8 @@ export default function TracesTable({
onChange: setPaginationState,
state: paginationState,
}}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
rowSelection={selectedRows}
setRowSelection={setSelectedRows}
columnVisibility={columnVisibility}
diff --git a/src/features/filters/server/filterToPrisma.ts b/src/features/filters/server/filterToPrisma.ts
index 33b520294c..ff87099885 100644
--- a/src/features/filters/server/filterToPrisma.ts
+++ b/src/features/filters/server/filterToPrisma.ts
@@ -18,7 +18,11 @@ export function filterToPrismaSql(
): Prisma.Sql {
const statements = filters.map((filter) => {
// Get column definition to map column to internal name, e.g. "t.id"
- const col = tableColumns.find((c) => c.name === filter.column);
+ const col = tableColumns.find(
+ (c) =>
+ // TODO: Only use id instead of name
+ c.name === filter.column || c.id === filter.column,
+ );
if (!col) {
console.error("Invalid filter column", filter.column);
throw new Error("Invalid filter column: " + filter.column);
diff --git a/src/features/orderBy/hooks/useOrderByState.ts b/src/features/orderBy/hooks/useOrderByState.ts
new file mode 100644
index 0000000000..4566fd1650
--- /dev/null
+++ b/src/features/orderBy/hooks/useOrderByState.ts
@@ -0,0 +1,24 @@
+import { type OrderByState } from "@/src/features/orderBy/types";
+import { ObjectParam, useQueryParam, withDefault } from "use-query-params";
+
+type OrderByQueryParamState =
+ | OrderByState
+ | { [key: string]: string | undefined };
+
+/**
+ * useOrderByState is a custom hook to manage the ordering settings (for a table).
+ * It does so via query params.
+ * @param initialState default ordering
+ * @returns [orderByState, setOrderByState]
+ */
+export const useOrderByState = (initialState: OrderByState = null) => {
+ const [orderByState, setOrderByState] = useQueryParam<OrderByQueryParamState>(
+ "orderBy",
+ withDefault(ObjectParam, initialState),
+ );
+
+ return [orderByState, setOrderByState] as [
+ OrderByState,
+ (orderByState: OrderByState) => void,
+ ];
+};
diff --git a/src/features/orderBy/server/orderByToPrisma.ts b/src/features/orderBy/server/orderByToPrisma.ts
new file mode 100644
index 0000000000..4cbb93e915
--- /dev/null
+++ b/src/features/orderBy/server/orderByToPrisma.ts
@@ -0,0 +1,30 @@
+import { type OrderByState } from "@/src/features/orderBy/types";
+import { type ColumnDefinition } from "@/src/server/api/interfaces/tableDefinition";
+import { Prisma } from "@prisma/client";
+
+/**
+ * Convert orderBy to SQL ORDER BY clause
+ * @param orderBy orderBy state
+ * @param tableColumns column definitions, used to map orderBy column to internal name
+ * @returns Prisma.sql
+ */
+export function orderByToPrismaSql(
+ orderBy: OrderByState,
+ tableColumns: ColumnDefinition[],
+): Prisma.Sql {
+ if (!orderBy) {
+ return Prisma.sql([`ORDER BY t.timestamp DESC`]);
+ }
+ // Get column definition to map column to internal name, e.g. "t.id"
+ const col = tableColumns.find(
+ // TODO: Only use id instead of name.
+ // It's less error-prone & decouples data fetching from the human-readable UI labels
+ (c) => c.name === orderBy.column || c.id === orderBy.column,
+ );
+ if (!col) {
+ console.log("Invalid filter column", orderBy.column);
+ throw new Error("Invalid filter column: " + orderBy.column);
+ }
+
+ return Prisma.sql([`ORDER BY ${col.internal} ${orderBy.order}`]);
+}
diff --git a/src/features/orderBy/types.ts b/src/features/orderBy/types.ts
new file mode 100644
index 0000000000..85cea12cc5
--- /dev/null
+++ b/src/features/orderBy/types.ts
@@ -0,0 +1,5 @@
+import { type orderBy } from "@/src/server/api/interfaces/orderBy";
+import { type z } from "zod";
+
+// to be sent to the server
+export type OrderByState = z.infer<typeof orderBy>;
diff --git a/src/server/api/definitions/tracesTable.ts b/src/server/api/definitions/tracesTable.ts
index fdc798bf85..eb20854a6a 100644
--- a/src/server/api/definitions/tracesTable.ts
+++ b/src/server/api/definitions/tracesTable.ts
@@ -4,42 +4,49 @@ import {
} from "@/src/server/api/interfaces/tableDefinition";
export const tracesTableCols: ColumnDefinition[] = [
- { name: "⭐️", type: "boolean", internal: "t.bookmarked" },
- { name: "id", type: "string", internal: "t.id" },
+ { name: "⭐️", id: "bookmarked", type: "boolean", internal: "t.bookmarked" },
+ { name: "id", id: "id", type: "string", internal: "t.id" },
{
name: "name",
+ id: "name",
type: "stringOptions",
internal: 't."name"',
options: [], // to be filled in at runtime
},
{
name: "timestamp",
+ id: "timestamp",
type: "datetime",
internal: 't."timestamp"',
},
- { name: "userId", type: "string", internal: 't."user_id"' },
+ { name: "userId", id: "userId", type: "string", internal: 't."user_id"' },
{
name: "metadata",
+ id: "metadata",
type: "stringObject",
internal: 't."metadata"',
},
{
name: "scores_avg",
+ id: "scores_avg",
type: "numberObject",
internal: "scores_avg",
},
{
name: "Latency (s)",
+ id: "latency",
type: "number",
internal: "tl.latency",
},
{
name: "version",
+ id: "version",
type: "string",
internal: 't."version"',
},
{
name: "release",
+ id: "release",
type: "string",
internal: 't."release"',
},
diff --git a/src/server/api/interfaces/orderBy.ts b/src/server/api/interfaces/orderBy.ts
new file mode 100644
index 0000000000..9080c0f58d
--- /dev/null
+++ b/src/server/api/interfaces/orderBy.ts
@@ -0,0 +1,8 @@
+import { z } from "zod";
+
+export const orderBy = z
+ .object({
+ column: z.string(),
+ order: z.enum(["ASC", "DESC"]),
+ })
+ .nullable();
diff --git a/src/server/api/interfaces/tableDefinition.ts b/src/server/api/interfaces/tableDefinition.ts
index f071d566a3..a3d0a8f162 100644
--- a/src/server/api/interfaces/tableDefinition.ts
+++ b/src/server/api/interfaces/tableDefinition.ts
@@ -6,17 +6,20 @@ export type OptionsDefinition = {
export type ColumnDefinition =
| {
name: string;
+ id?: string; // TODO: Adopt for all tables
type: "number" | "string" | "datetime" | "boolean";
internal: string;
}
| {
name: string;
+ id?: string; // TODO: Adopt for all tables
type: "stringOptions";
options: Array<OptionsDefinition>;
internal: string;
}
| {
name: string;
+ id?: string; // TODO: Adopt for all tables
type: "stringObject" | "numberObject";
internal: string;
keyOptions?: Array<string>;
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index fe057ff690..234a7e7f01 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -25,11 +25,14 @@ import {
} from "@/src/features/filters/server/filterToPrisma";
import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
import { TRPCError } from "@trpc/server";
+import { orderBy } from "@/src/server/api/interfaces/orderBy";
+import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
searchQuery: z.string().nullable(),
filter: z.array(singleFilter).nullable(),
+ orderBy: orderBy,
...paginationZod,
});
@@ -45,6 +48,10 @@ export const traceRouter = createTRPCRouter({
input.filter ?? [],
tracesTableCols,
);
+ const orderByCondition = orderByToPrismaSql(
+ input.orderBy,
+ tracesTableCols,
+ );
// to improve query performance, add timeseries filter to observation queries as well
const timeseriesFilter = input.filter?.find(
@@ -174,8 +181,7 @@ export const traceRouter = createTRPCRouter({
t."project_id" = ${input.projectId}
${searchCondition}
${filterCondition}
- ORDER BY
- t."timestamp" DESC
+ ${orderByCondition}
LIMIT ${input.limit}
OFFSET ${input.page * input.limit}
`);
diff --git a/src/server/api/trpc.ts b/src/server/api/trpc.ts
index 8e46a73fd5..cb52900f64 100644
--- a/src/server/api/trpc.ts
+++ b/src/server/api/trpc.ts
@@ -36,7 +36,7 @@ type CreateContextOptions = {
*
* @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts
*/
-const createInnerTRPCContext = (opts: CreateContextOptions) => {
+export const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
prisma,