🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: add new widget creator page (#6322)
Steffen Schmitz5c2ac78eca1e
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex 6eca268503..843794714a 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -33,4 +33,5 @@ export type TableName =| "scores"| "prompts"| "dashboard"+ | "widgets"| "users";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 96adc8727b..bbb151bb45 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -58,7 +58,7 @@ importers:version: 14.2.25(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: ^4.24.11- version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])zod:specifier: ^3.23.8version: 3.23.8@@ -232,7 +232,7 @@ importers:version: 4.0.2next-auth:specifier: ^4.24.11- version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])nodemailer:specifier: ^6.9.15version: 6.9.15@@ -632,7 +632,7 @@ importers:version: 14.2.25(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: ^4.24.11- version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])next-query-params:specifier: ^5.0.1version: 5.0.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]))([email protected]))@@ -687,6 +687,9 @@ importers:react18-json-view:specifier: ^0.2.8-canary.6version: 0.2.8-canary.6([email protected])+ recharts:+ specifier: ^2.15.2remark-gfm:specifier: ^4.0.0version: 4.0.0@@ -10389,11 +10392,11 @@ packages:peerDependencies:react: '>=16.8.0'- resolution: {integrity: sha512-2NMXOBY1uVUQx1jBeENGA497HK20y6CPGYL1ZnJLeoQ8rrc3UfmOM82sRxtzpcoCkUMy4CS0RGylfuVhuFjBgg==}+ resolution: {integrity: sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==}peerDependencies:- react: ^16.8.0 || ^17.0.0 || ^18.0.0- react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0resolution: {integrity: sha512-ZWj0fHEMyWkHzKYUr2Bs/4zU6XLmq9HsgBURm7g5pAVfyn49DgUiNgY2d4lXRlYSiCif9YBGpQleewkcqddc7g==}@@ -10459,12 +10462,12 @@ packages:resolution: {integrity: sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==}- resolution: {integrity: sha512-hlLJMhPQfv4/3NBSAyq3gzGg4h2v69RJh6KU7b3pXYNNAELs9kEoXOjbkxdXpALqKBoVmVptGfLpxdaVYqjmXQ==}+ resolution: {integrity: sha512-xv9lVztv3ingk7V3Jf05wfAZbM9Q2umJzu5t/cfnAK7LUslNrGT7LPBr74G+ok8kSCeFMaePmWMg0rcYOnczTw==}engines: {node: '>=14'}peerDependencies:- react: ^16.0.0 || ^17.0.0 || ^18.0.0- react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0+ react: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0resolution: {integrity: sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==}@@ -14628,7 +14631,7 @@ snapshots:'@aws-sdk/client-bedrock-agent-runtime': 3.668.0'@aws-sdk/client-bedrock-runtime': 3.668.0'@aws-sdk/client-kendra': 3.668.0- '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])'@langchain/core': 0.3.18([email protected]([email protected]))zod: 3.23.8zod-to-json-schema: 3.23.5([email protected])@@ -15000,7 +15003,7 @@ snapshots:'@next-auth/[email protected](@prisma/[email protected]([email protected]([email protected]))([email protected]))([email protected](patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]))':dependencies:- next-auth: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ next-auth: 4.24.11(patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@next/[email protected]': {}@@ -17391,7 +17394,7 @@ snapshots:react-day-picker: 8.10.1([email protected])([email protected])react-dom: 18.2.0([email protected])tailwind-merge: 1.14.0transitivePeerDependencies:- tailwindcss@@ -18035,7 +18038,7 @@ snapshots:'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/parser': 7.12.0([email protected])([email protected])eslint-config-prettier: 9.1.0([email protected])- eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))+ eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])eslint-plugin-eslint-comments: 3.2.0([email protected])eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])@@ -20040,7 +20043,7 @@ snapshots:eslint: 8.57.0eslint-plugin-turbo: 1.13.4([email protected])- [email protected]([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])):+ [email protected]([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])):dependencies:eslint-plugin-import: 2.29.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])@@ -20131,7 +20134,7 @@ snapshots:doctrine: 2.1.0eslint: 8.57.0eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])hasown: 2.0.2is-core-module: 2.15.1is-glob: 4.0.3@@ -20158,7 +20161,7 @@ snapshots:doctrine: 2.1.0eslint: 8.57.0eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.8.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected])hasown: 2.0.2is-core-module: 2.15.1is-glob: 4.0.3@@ -23023,7 +23026,7 @@ snapshots:dependencies:type-fest: 2.19.0- [email protected](patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]):+ [email protected](patch_hash=cczsf6i6qe2m2htirvgxjtoclu)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]):dependencies:'@babel/runtime': 7.26.0'@panva/hkdf': 1.1.1@@ -24047,7 +24050,7 @@ snapshots:react: 18.2.0shallow-equal: 3.1.0dependencies:fast-equals: 5.0.1prop-types: 15.8.1@@ -24140,15 +24143,15 @@ snapshots:dependencies:decimal.js-light: 2.5.1dependencies:clsx: 2.1.1eventemitter3: 4.0.7lodash: 4.17.21react: 18.2.0react-dom: 18.2.0([email protected])- react-is: 16.13.1+ react-is: 18.3.1recharts-scale: 0.4.5tiny-invariant: 1.3.3victory-vendor: 36.9.2diff --git a/web/package.json b/web/package.jsonindex 0e056443e4..b65441fdc2 100644--- a/web/package.json+++ b/web/package.json@@ -142,6 +142,7 @@"react-responsive": "^10.0.0","react-syntax-highlighter": "^15.5.0","react18-json-view": "^0.2.8-canary.6",+ "recharts": "^2.15.2","remark-gfm": "^4.0.0","remark-math": "^6.0.0","remark-parse": "^11.0.0",diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.tsindex c48dfecb66..401fb533e5 100644--- a/web/src/__tests__/queryBuilder.servertest.ts+++ b/web/src/__tests__/queryBuilder.servertest.ts@@ -515,12 +515,12 @@ describe("queryBuilder", () => {const manyObsTrace = result.data.find((row: any) => row.name === "trace-with-many-obs",);- expect(manyObsTrace.sum_observations_count).toBe("5");+ expect(manyObsTrace.sum_observationsCount).toBe("5");const fewObsTrace = result.data.find((row: any) => row.name === "trace-with-few-obs",);- expect(fewObsTrace.sum_observations_count).toBe("2");+ expect(fewObsTrace.sum_observationsCount).toBe("2");});it("should use tags as dimension", async () => {@@ -877,14 +877,14 @@ describe("queryBuilder", () => {(row: any) => row.environment === "production",);expect(prodEnv.count_count).toBe("2"); // 2 traces- expect(prodEnv.sum_observations_count).toBe("7"); // 3+4 observations+ expect(prodEnv.sum_observationsCount).toBe("7"); // 3+4 observations// Verify development environment dataconst devEnv = result.data.find((row: any) => row.environment === "development",);expect(devEnv.count_count).toBe("2"); // 2 traces- expect(devEnv.sum_observations_count).toBe("3"); // 2+1 observations+ expect(devEnv.sum_observationsCount).toBe("3"); // 2+1 observations});it("should handle multiple dimensions (name and environment) correctly", async () => {@@ -1015,10 +1015,10 @@ describe("queryBuilder", () => {const row = result.data[0];expect(row.name).toBe("multi-metric-test");expect(row.count_count).toBe("2"); // 2 traces- expect(row.sum_observations_count).toBe("30"); // 10+20 observations- expect(row.avg_observations_count).toBe(15); // (10+20)/2 average- expect(row.max_observations_count).toBe("20"); // max is 20- expect(row.min_observations_count).toBe("10"); // min is 10+ expect(row.sum_observationsCount).toBe("30"); // 10+20 observations+ expect(row.avg_observationsCount).toBe(15); // (10+20)/2 average+ expect(row.max_observationsCount).toBe("20"); // max is 20+ expect(row.min_observationsCount).toBe("10"); // min is 10});it("should order by a dimension field correctly", async () => {@@ -1096,7 +1096,7 @@ describe("queryBuilder", () => {toTimestamp: new Date(new Date().setDate(new Date().getDate() + 1),).toISOString(),- orderBy: [{ field: "sum_observations_count", direction: "desc" }],+ orderBy: [{ field: "sum_observationsCount", direction: "desc" }],};// Execute query@@ -1107,7 +1107,7 @@ describe("queryBuilder", () => {);// Verify ORDER BY clause is present in the query- expect(compiledQuery).toContain("ORDER BY sum_observations_count desc");+ expect(compiledQuery).toContain("ORDER BY sum_observationsCount desc");const result = await (await clickhouseClient().query({@@ -1150,7 +1150,7 @@ describe("queryBuilder", () => {).toISOString(),orderBy: [{ field: "environment", direction: "asc" },- { field: "sum_observations_count", direction: "desc" },+ { field: "sum_observationsCount", direction: "desc" },],};@@ -1163,7 +1163,7 @@ describe("queryBuilder", () => {// Verify ORDER BY clause is present in the query with both fieldsexpect(compiledQuery).toContain(- "ORDER BY environment asc, sum_observations_count desc",+ "ORDER BY environment asc, sum_observationsCount desc",);const result = await (@@ -1298,7 +1298,7 @@ describe("queryBuilder", () => {);// Verify ORDER BY clause includes default metric ordering (descending)- expect(compiledQuery).toContain("ORDER BY sum_observations_count desc");+ expect(compiledQuery).toContain("ORDER BY sum_observationsCount desc");const result = await (await clickhouseClient().query({@@ -2226,8 +2226,8 @@ describe("queryBuilder", () => {// Check qa trace with gpt-4const qaTraceRow = result.data.find((row: any) =>- row.trace_name === "qa-trace" &&- row.observation_model_name === "gpt-4",+ row.traceName === "qa-trace" &&+ row.observationModelName === "gpt-4",);expect(qaTraceRow.count_count).toBe("2"); // 2 scores (accuracy + relevance)expect(parseFloat(qaTraceRow.avg_value)).toBeCloseTo(0.875, 2); // (0.90 + 0.85) / 2@@ -2235,8 +2235,8 @@ describe("queryBuilder", () => {// Check summarization trace with claude-3const summaryTraceRow = result.data.find((row: any) =>- row.trace_name === "summarization-trace" &&- row.observation_model_name === "claude-3",+ row.traceName === "summarization-trace" &&+ row.observationModelName === "claude-3",);expect(summaryTraceRow.count_count).toBe("1"); // 1 score (accuracy)expect(parseFloat(summaryTraceRow.avg_value)).toBeCloseTo(0.95, 2);@@ -2501,25 +2501,24 @@ describe("queryBuilder", () => {// Check each combinationconst evaluationExcellent = result.data.find((row: any) =>- row.name === "evaluation" && row.string_value === "excellent",+ row.name === "evaluation" && row.stringValue === "excellent",);expect(evaluationExcellent.count_count).toBe("1");const evaluationGood = result.data.find(- (row: any) =>- row.name === "evaluation" && row.string_value === "good",+ (row: any) => row.name === "evaluation" && row.stringValue === "good",);expect(evaluationGood.count_count).toBe("2");const categoryQuestion = result.data.find((row: any) =>- row.name === "category" && row.string_value === "question",+ row.name === "category" && row.stringValue === "question",);expect(categoryQuestion.count_count).toBe("1");const categoryFactual = result.data.find((row: any) =>- row.name === "category" && row.string_value === "factual",+ row.name === "category" && row.stringValue === "factual",);expect(categoryFactual.count_count).toBe("1");});@@ -2619,7 +2618,7 @@ describe("queryBuilder", () => {// Check specific valuesconst stringValues = result.data- .map((row: any) => row.string_value)+ .map((row: any) => row.stringValue).sort();expect(stringValues).toEqual(["command", "statement"]);});@@ -2778,39 +2777,39 @@ describe("queryBuilder", () => {// Get results for each traceconst gpt4Result = result.data.find(- (row: any) => row.trace_name === "gpt-4-completion",+ (row: any) => row.traceName === "gpt-4-completion",);const gpt35Result = result.data.find(- (row: any) => row.trace_name === "gpt-3.5-completion",+ (row: any) => row.traceName === "gpt-3.5-completion",);const claudeResult = result.data.find(- (row: any) => row.trace_name === "claude-completion",+ (row: any) => row.traceName === "claude-completion",);// The p95 should be close to the 95th percentile value we generated// For GPT-4: the 95th percentile of values from 500-1400 would be around 1350msexpect(- parseInt(gpt4Result.p95_time_to_first_token),+ parseInt(gpt4Result.p95_timeToFirstToken),).toBeGreaterThanOrEqual(1300);- expect(- parseInt(gpt4Result.p95_time_to_first_token),- ).toBeLessThanOrEqual(1400);+ expect(parseInt(gpt4Result.p95_timeToFirstToken)).toBeLessThanOrEqual(+ 1400,+ );// For GPT-3.5: the 95th percentile of values from 200-650 would be around 625msexpect(- parseInt(gpt35Result.p95_time_to_first_token),+ parseInt(gpt35Result.p95_timeToFirstToken),).toBeGreaterThanOrEqual(600);- expect(- parseInt(gpt35Result.p95_time_to_first_token),- ).toBeLessThanOrEqual(650);+ expect(parseInt(gpt35Result.p95_timeToFirstToken)).toBeLessThanOrEqual(+ 650,+ );// For Claude: the 95th percentile of values from 300-1200 would be around 1150msexpect(- parseInt(claudeResult.p95_time_to_first_token),+ parseInt(claudeResult.p95_timeToFirstToken),).toBeGreaterThanOrEqual(1100);- expect(- parseInt(claudeResult.p95_time_to_first_token),- ).toBeLessThanOrEqual(1200);+ expect(parseInt(claudeResult.p95_timeToFirstToken)).toBeLessThanOrEqual(+ 1200,+ );});});});diff --git a/web/src/__tests__/queryBuilderDashboards.servertest.ts b/web/src/__tests__/queryBuilderDashboards.servertest.tsindex b2e6736004..e439250f20 100644--- a/web/src/__tests__/queryBuilderDashboards.servertest.ts+++ b/web/src/__tests__/queryBuilderDashboards.servertest.ts@@ -450,12 +450,12 @@ describe("selfServeDashboards", () => {// Verify each model is present with cost and token metricsexpectedModels.forEach((modelName) => {const modelRow = queryBuilderResult.find(- (row: any) => row.provided_model_name === modelName,+ (row: any) => row.providedModelName === modelName,);expect(modelRow).toBeDefined();- expect(modelRow.sum_total_cost).toBeDefined();- expect(modelRow.sum_total_tokens).toBeDefined();+ expect(modelRow.sum_totalCost).toBeDefined();+ expect(modelRow.sum_totalTokens).toBeDefined();// We could add more specific assertions about the expected costs and tokens// if we had that information calculated from our sample data@@ -495,9 +495,9 @@ describe("selfServeDashboards", () => {expect(queryBuilderResult.length).toBe(2);const modelRow = queryBuilderResult[0];- expect(modelRow.provided_model_name).toBe("gpt-4-turbo");- expect(modelRow.sum_total_cost).toBe(900);- expect(modelRow.sum_total_tokens).toBe("20736");+ expect(modelRow.providedModelName).toBe("gpt-4-turbo");+ expect(modelRow.sum_totalCost).toBe(900);+ expect(modelRow.sum_totalTokens).toBe("20736");});it("should filter observations by environment", async () => {@@ -540,12 +540,12 @@ describe("selfServeDashboards", () => {// Verify each production model is presentproductionModels.forEach((modelName) => {const modelRow = queryBuilderResult.find(- (row: any) => row.provided_model_name === modelName,+ (row: any) => row.providedModelName === modelName,);expect(modelRow).toBeDefined();- expect(modelRow.sum_total_cost).toBeGreaterThan(500);- expect(Number(modelRow.sum_total_tokens)).toBeGreaterThan(10000);+ expect(modelRow.sum_totalCost).toBeGreaterThan(500);+ expect(Number(modelRow.sum_totalTokens)).toBeGreaterThan(10000);});});});@@ -637,9 +637,9 @@ describe("selfServeDashboards", () => {// Each row should have these propertiesqueryBuilderResult.forEach((row: any) => {expect(row.time_dimension).toBeDefined();- expect(row.provided_model_name).toBeDefined();- expect(row.sum_total_cost).toBeDefined();- expect(row.sum_total_tokens).toBeDefined();+ expect(row.providedModelName).toBeDefined();+ expect(row.sum_totalCost).toBeDefined();+ expect(row.sum_totalTokens).toBeDefined();});// Verify that the hours where we created observations have non-zero costs/tokens@@ -655,7 +655,7 @@ describe("selfServeDashboards", () => {(row: any) =>new Date(row.time_dimension).getTime() >= oneHourAgo.getTime() &&new Date(row.time_dimension).getTime() <= now.getTime() &&- expectedModels.includes(row.provided_model_name),+ expectedModels.includes(row.providedModelName),);// We should have at least one recent observation@@ -664,7 +664,7 @@ describe("selfServeDashboards", () => {// At least one of the recent observations should have non-zero cost/tokensconst hasNonZeroValues = recentObservations.some((row: any) =>- Number(row.sum_total_cost) > 0 && Number(row.sum_total_tokens) > 0,+ Number(row.sum_totalCost) > 0 && Number(row.sum_totalTokens) > 0,);expect(hasNonZeroValues).toBe(true);});@@ -700,19 +700,19 @@ describe("selfServeDashboards", () => {// Check that we have results for the expected usersexpectedUsers.forEach((userId) => {const userRow = queryBuilderResult.find(- (row: any) => row.user_id === userId,+ (row: any) => row.userId === userId,);// We might not have observations for all users, so we'll just check// that the structure is correct for the ones we do haveif (userRow) {- expect(userRow.sum_total_cost).toBeDefined();+ expect(userRow.sum_totalCost).toBeDefined();}});// At least one user should have a non-zero costconst hasNonZeroCost = queryBuilderResult.some(- (row: any) => Number(row.sum_total_cost) > 0,+ (row: any) => Number(row.sum_totalCost) > 0,);expect(hasNonZeroCost).toBe(true);});@@ -754,7 +754,7 @@ describe("selfServeDashboards", () => {// Check that we have results for all expected usersexpectedUsers.forEach((userId) => {const userRow = queryBuilderResult.find(- (row: any) => row.user_id === userId,+ (row: any) => row.userId === userId,);expect(userRow).toBeDefined();@@ -949,7 +949,7 @@ describe("selfServeDashboards", () => {// Each row should have these propertiesqueryBuilderResult.forEach((row: any) => {expect(row.time_dimension).toBeDefined();- expect(row.provided_model_name).toBeDefined();+ expect(row.providedModelName).toBeDefined();expect(row.p50_latency).toBeDefined();expect(row.p75_latency).toBeDefined();expect(row.p90_latency).toBeDefined();@@ -970,7 +970,7 @@ describe("selfServeDashboards", () => {(row: any) =>new Date(row.time_dimension).getTime() >= oneHourAgo.getTime() &&new Date(row.time_dimension).getTime() <= now.getTime() &&- expectedModels.includes(row.provided_model_name),+ expectedModels.includes(row.providedModelName),);// We should have at least one recent observation with latency datadiff --git a/web/src/components/ui/card.tsx b/web/src/components/ui/card.tsxindex 7feddaabff..97d9d19d08 100644--- a/web/src/components/ui/card.tsx+++ b/web/src/components/ui/card.tsx@@ -45,10 +45,10 @@ const CardTitle = React.forwardRef<CardTitle.displayName = "CardTitle";const CardDescription = React.forwardRef<- HTMLParagraphElement,- React.HTMLAttributes<HTMLParagraphElement>+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (- <p+ <divref={ref}className={cn("text-sm text-muted-foreground", className)}{...props}diff --git a/web/src/components/ui/chart.tsx b/web/src/components/ui/chart.tsxnew file mode 100644index 0000000000..6a916ed3fe--- /dev/null+++ b/web/src/components/ui/chart.tsx@@ -0,0 +1,365 @@+"use client"++import * as React from "react"+import * as RechartsPrimitive from "recharts"++import { cn } from "@/src/utils/tailwind"++// Format: { THEME_NAME: CSS_SELECTOR }+const THEMES = { light: "", dark: ".dark" } as const++export type ChartConfig = {+ [k in string]: {+ label?: React.ReactNode+ icon?: React.ComponentType+ } & (+ | { color?: string; theme?: never }+ | { color?: never; theme: Record<keyof typeof THEMES, string> }+ )+}++type ChartContextProps = {+ config: ChartConfig+}++const ChartContext = React.createContext<ChartContextProps | null>(null)++function useChart() {+ const context = React.useContext(ChartContext)++ if (!context) {+ throw new Error("useChart must be used within a <ChartContainer />")+ }++ return context+}++const ChartContainer = React.forwardRef<+ HTMLDivElement,+ React.ComponentProps<"div"> & {+ config: ChartConfig+ children: React.ComponentProps<+ typeof RechartsPrimitive.ResponsiveContainer+ >["children"]+ }+>(({ id, className, children, config, ...props }, ref) => {+ const uniqueId = React.useId()+ const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`++ return (+ <ChartContext.Provider value={{ config }}>+ <div+ data-chart={chartId}+ ref={ref}+ className={cn(+ "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",+ className+ )}+ {...props}+ >+ <ChartStyle id={chartId} config={config} />+ <RechartsPrimitive.ResponsiveContainer>+ {children}+ </RechartsPrimitive.ResponsiveContainer>+ </div>+ </ChartContext.Provider>+ )+})+ChartContainer.displayName = "Chart"++const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {+ const colorConfig = Object.entries(config).filter(+ ([, config]) => config.theme || config.color+ )++ if (!colorConfig.length) {+ return null+ }++ return (+ <style+ dangerouslySetInnerHTML={{+ __html: Object.entries(THEMES)+ .map(+ ([theme, prefix]) => `+${prefix} [data-chart=${id}] {+${colorConfig+ .map(([key, itemConfig]) => {+ const color =+ itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||+ itemConfig.color+ return color ? ` --color-${key}: ${color};` : null+ })+ .join("\n")}+}+`+ )+ .join("\n"),+ }}+ />+ )+}++const ChartTooltip = RechartsPrimitive.Tooltip++const ChartTooltipContent = React.forwardRef<+ HTMLDivElement,+ React.ComponentProps<typeof RechartsPrimitive.Tooltip> &+ React.ComponentProps<"div"> & {+ hideLabel?: boolean+ hideIndicator?: boolean+ indicator?: "line" | "dot" | "dashed"+ nameKey?: string+ labelKey?: string+ }+>(+ (+ {+ active,+ payload,+ className,+ indicator = "dot",+ hideLabel = false,+ hideIndicator = false,+ label,+ labelFormatter,+ labelClassName,+ formatter,+ color,+ nameKey,+ labelKey,+ },+ ref+ ) => {+ const { config } = useChart()++ const tooltipLabel = React.useMemo(() => {+ if (hideLabel || !payload?.length) {+ return null+ }++ const [item] = payload+ const key = `${labelKey || item?.dataKey || item?.name || "value"}`+ const itemConfig = getPayloadConfigFromPayload(config, item, key)+ const value =+ !labelKey && typeof label === "string"+ ? config[label as keyof typeof config]?.label || label+ : itemConfig?.label++ if (labelFormatter) {+ return (+ <div className={cn("font-medium", labelClassName)}>+ {labelFormatter(value, payload)}+ </div>+ )+ }++ if (!value) {+ return null+ }++ return <div className={cn("font-medium", labelClassName)}>{value}</div>+ }, [+ label,+ labelFormatter,+ payload,+ hideLabel,+ labelClassName,+ config,+ labelKey,+ ])++ if (!active || !payload?.length) {+ return null+ }++ const nestLabel = payload.length === 1 && indicator !== "dot"++ return (+ <div+ ref={ref}+ className={cn(+ "grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",+ className+ )}+ >+ {!nestLabel ? tooltipLabel : null}+ <div className="grid gap-1.5">+ {payload.map((item, index) => {+ const key = `${nameKey || item.name || item.dataKey || "value"}`+ const itemConfig = getPayloadConfigFromPayload(config, item, key)+ const indicatorColor = color || item.payload.fill || item.color++ return (+ <div+ key={item.dataKey}+ className={cn(+ "flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",+ indicator === "dot" && "items-center"+ )}+ >+ {formatter && item?.value !== undefined && item.name ? (+ formatter(item.value, item.name, item, index, item.payload)+ ) : (+ <>+ {itemConfig?.icon ? (+ <itemConfig.icon />+ ) : (+ !hideIndicator && (+ <div+ className={cn(+ "shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",+ {+ "h-2.5 w-2.5": indicator === "dot",+ "w-1": indicator === "line",+ "w-0 border-[1.5px] border-dashed bg-transparent":+ indicator === "dashed",+ "my-0.5": nestLabel && indicator === "dashed",+ }+ )}+ style={+ {+ "--color-bg": indicatorColor,+ "--color-border": indicatorColor,+ } as React.CSSProperties+ }+ />+ )+ )}+ <div+ className={cn(+ "flex flex-1 justify-between leading-none",+ nestLabel ? "items-end" : "items-center"+ )}+ >+ <div className="grid gap-1.5">+ {nestLabel ? tooltipLabel : null}+ <span className="text-muted-foreground">+ {itemConfig?.label || item.name}+ </span>+ </div>+ {item.value && (+ <span className="font-mono font-medium tabular-nums text-foreground">+ {item.value.toLocaleString()}+ </span>+ )}+ </div>+ </>+ )}+ </div>+ )+ })}+ </div>+ </div>+ )+ }+)+ChartTooltipContent.displayName = "ChartTooltip"++const ChartLegend = RechartsPrimitive.Legend++const ChartLegendContent = React.forwardRef<+ HTMLDivElement,+ React.ComponentProps<"div"> &+ Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {+ hideIcon?: boolean+ nameKey?: string+ }+>(+ (+ { className, hideIcon = false, payload, verticalAlign = "bottom", nameKey },+ ref+ ) => {+ const { config } = useChart()++ if (!payload?.length) {+ return null+ }++ return (+ <div+ ref={ref}+ className={cn(+ "flex items-center justify-center gap-4",+ verticalAlign === "top" ? "pb-3" : "pt-3",+ className+ )}+ >+ {payload.map((item) => {+ const key = `${nameKey || item.dataKey || "value"}`+ const itemConfig = getPayloadConfigFromPayload(config, item, key)++ return (+ <div+ key={item.value}+ className={cn(+ "flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"+ )}+ >+ {itemConfig?.icon && !hideIcon ? (+ <itemConfig.icon />+ ) : (+ <div+ className="h-2 w-2 shrink-0 rounded-[2px]"+ style={{+ backgroundColor: item.color,+ }}+ />+ )}+ {itemConfig?.label}+ </div>+ )+ })}+ </div>+ )+ }+)+ChartLegendContent.displayName = "ChartLegend"++// Helper to extract item config from a payload.+function getPayloadConfigFromPayload(+ config: ChartConfig,+ payload: unknown,+ key: string+) {+ if (typeof payload !== "object" || payload === null) {+ return undefined+ }++ const payloadPayload =+ "payload" in payload &&+ typeof payload.payload === "object" &&+ payload.payload !== null+ ? payload.payload+ : undefined++ let configLabelKey: string = key++ if (+ key in payload &&+ typeof payload[key as keyof typeof payload] === "string"+ ) {+ configLabelKey = payload[key as keyof typeof payload] as string+ } else if (+ payloadPayload &&+ key in payloadPayload &&+ typeof payloadPayload[key as keyof typeof payloadPayload] === "string"+ ) {+ configLabelKey = payloadPayload[+ key as keyof typeof payloadPayload+ ] as string+ }++ return configLabelKey in config+ ? config[configLabelKey]+ : config[key as keyof typeof config]+}++export {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ ChartLegend,+ ChartLegendContent,+ ChartStyle,+}diff --git a/web/src/ee/features/evals/components/inner-evaluator-form.tsx b/web/src/ee/features/evals/components/inner-evaluator-form.tsxindex c93a7fa1e8..27b2706f2b 100644--- a/web/src/ee/features/evals/components/inner-evaluator-form.tsx+++ b/web/src/ee/features/evals/components/inner-evaluator-form.tsx@@ -454,7 +454,7 @@ export const InnerEvaluatorForm = (props: {evalTraceTableCols,)}filterState={field.value ?? []}- onChange={(value) => field.onChange(value)}+ onChange={field.onChange}disabled={props.disabled}columnsWithCustomSelect={["tags"]}/>@@ -477,7 +477,7 @@ export const InnerEvaluatorForm = (props: {evalDatasetFormFilterCols,)}filterState={field.value ?? []}- onChange={(value) => field.onChange(value)}+ onChange={field.onChange}disabled={props.disabled}/></FormControl>diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsxindex cd023fc614..7d425edb31 100644--- a/web/src/features/filters/components/filter-builder.tsx+++ b/web/src/features/filters/components/filter-builder.tsx@@ -198,7 +198,9 @@ export function InlineFilterBuilder({}: {columns: ColumnDefinition[];filterState: FilterState;- onChange: Dispatch<SetStateAction<FilterState>>;+ onChange:+ | Dispatch<SetStateAction<FilterState>>+ | ((newState: FilterState) => void);disabled?: boolean;columnsWithCustomSelect?: string[];}) {diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.tsindex 7f166549c8..c738d9853a 100644--- a/web/src/features/filters/hooks/useFilterState.ts+++ b/web/src/features/filters/hooks/useFilterState.ts@@ -133,6 +133,15 @@ const tableCols = {scores: scoresTableCols,prompts: promptsTableCols,users: usersTableCols,+ widgets: [+ { id: "environment", name: "Environment" },+ { id: "traceName", name: "Trace Name" },+ { id: "tags", name: "Tags" },+ { id: "release", name: "Release" },+ { id: "user", name: "User" },+ { id: "session", name: "Session" },+ { id: "version", name: "Version" },+ ],dashboard: [{ id: "traceName", name: "Trace Name" },{ id: "tags", name: "Tags" },diff --git a/web/src/features/query/dashboardUiTableToViewMapping.ts b/web/src/features/query/dashboardUiTableToViewMapping.tsindex 54fe955ff1..24efa8ad84 100644--- a/web/src/features/query/dashboardUiTableToViewMapping.ts+++ b/web/src/features/query/dashboardUiTableToViewMapping.ts@@ -18,6 +18,10 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {uiTableName: "User",viewName: "userId",},+ {+ uiTableName: "Session",+ viewName: "sessionId",+ },{uiTableName: "Release",viewName: "release",@@ -26,6 +30,10 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {uiTableName: "Version",viewName: "version",},+ {+ uiTableName: "Environment",+ viewName: "environment",+ },],observations: [{@@ -44,6 +52,10 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {uiTableName: "Model",viewName: "providedModelName",},+ {+ uiTableName: "Environment",+ viewName: "environment",+ },],"scores-numeric": [{@@ -62,6 +74,10 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {uiTableName: "Tags",viewName: "tags",},+ {+ uiTableName: "Environment",+ viewName: "environment",+ },],"scores-categorical": [{@@ -80,6 +96,10 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {uiTableName: "Tags",viewName: "tags",},+ {+ uiTableName: "Environment",+ viewName: "environment",+ },],};diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.tsindex 91f6bdd0c4..dd6218ae1f 100644--- a/web/src/features/query/dataModel.ts+++ b/web/src/features/query/dataModel.ts@@ -25,10 +25,12 @@ export const traceView: ViewDeclarationType = {},userId: {sql: "user_id",+ alias: "userId",type: "string",},sessionId: {sql: "session_id",+ alias: "sessionId",type: "string",},release: {@@ -52,13 +54,13 @@ export const traceView: ViewDeclarationType = {},observationsCount: {sql: "uniq(observations.id)",- alias: "observations_count",+ alias: "observationsCount",type: "count",relationTable: "observations",},scoresCount: {sql: "uniq(scores.id)",- alias: "scores_count",+ alias: "scoresCount",type: "count",relationTable: "scores",},@@ -97,11 +99,12 @@ export const observationsView: ViewDeclarationType = {},traceId: {sql: "trace_id",+ alias: "traceId",type: "string",},traceName: {sql: "name",- alias: "trace_name",+ alias: "traceName",type: "string",relationTable: "traces",},@@ -111,6 +114,7 @@ export const observationsView: ViewDeclarationType = {},parentObservationId: {sql: "parent_observation_id",+ alias: "parentObservationId",type: "string",},type: {@@ -136,23 +140,28 @@ export const observationsView: ViewDeclarationType = {},providedModelName: {sql: "provided_model_name",+ alias: "providedModelName",type: "string",},promptName: {sql: "prompt_name",+ alias: "promptName",type: "string",},promptVersion: {sql: "prompt_version",+ alias: "promptVersion",type: "string",},userId: {sql: "user_id",+ alias: "userId",type: "string",relationTable: "traces",},sessionId: {sql: "session_id",+ alias: "sessionId",type: "string",relationTable: "traces",},@@ -170,22 +179,22 @@ export const observationsView: ViewDeclarationType = {},totalTokens: {sql: "sumMap(usage_details)['total']",- alias: "total_tokens",+ alias: "totalTokens",type: "sum",},totalCost: {sql: "sum(total_cost)",- alias: "total_cost",+ alias: "totalCost",type: "sum",},timeToFirstToken: {sql: "date_diff('millisecond', any(observations.start_time), any(observations.completion_start_time))",- alias: "time_to_first_token",+ alias: "timeToFirstToken",type: "number",},countScores: {sql: "uniq(scores.id)",- alias: "count_scores",+ alias: "countScores",type: "count",relationTable: "scores",},@@ -228,15 +237,17 @@ const scoreBaseDimensions: DimensionsDeclarationType = {},dataType: {sql: "data_type",+ alias: "dataType",type: "string",},traceId: {sql: "trace_id",+ alias: "traceId",type: "string",},traceName: {sql: "name",- alias: "trace_name",+ alias: "traceName",type: "string",relationTable: "traces",},@@ -247,46 +258,48 @@ const scoreBaseDimensions: DimensionsDeclarationType = {},userId: {sql: "user_id",- alias: "user_id",+ alias: "userId",type: "string",relationTable: "traces",},sessionId: {sql: "session_id",- alias: "session_id",+ alias: "sessionId",type: "string",relationTable: "traces",},observationId: {sql: "observation_id",+ alias: "observationId",type: "string",},observationName: {sql: "name",- alias: "observation_name",+ alias: "observationName",type: "string",relationTable: "observations",},observationModelName: {sql: "provided_model_name",- alias: "observation_model_name",+ alias: "observationModelName",type: "string",relationTable: "observations",},observationPromptName: {sql: "prompt_name",- alias: "observation_prompt_name",+ alias: "observationPromptName",type: "string",relationTable: "observations",},observationPromptVersion: {sql: "prompt_version",- alias: "observation_prompt_version",+ alias: "observationPromptVersion",type: "string",relationTable: "observations",},configId: {sql: "config_id",+ alias: "configId",type: "string",},};@@ -341,6 +354,7 @@ export const scoresCategoricalView: ViewDeclarationType = {...scoreBaseDimensions,stringValue: {sql: "string_value",+ alias: "stringValue",type: "string",},},diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxnew file mode 100644index 0000000000..98161c421f--- /dev/null+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -0,0 +1,39 @@+import React from "react";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { CardContent } from "@/src/components/ui/card";+import LineChartTimeSeries from "@/src/features/widgets/chart-library/LineChartTimeSeries";+import VerticalBarChartTimeSeries from "@/src/features/widgets/chart-library/VerticalBarChartTimeSeries";+import HorizontalBarChart from "@/src/features/widgets/chart-library/HorizontalBarChart";+import VerticalBarChart from "@/src/features/widgets/chart-library/VerticalBarChart";+import PieChart from "@/src/features/widgets/chart-library/PieChart";++export const Chart = ({+ chartType,+ data,+ rowLimit,+}: {+ chartType: string;+ data: DataPoint[];+ rowLimit: number;+}) => {+ return (+ <CardContent>+ {(() => {+ switch (chartType) {+ case "line-time-series":+ return <LineChartTimeSeries data={data} />;+ case "bar-time-series":+ return <VerticalBarChartTimeSeries data={data} />;+ case "bar-horizontal":+ return <HorizontalBarChart data={data.slice(0, rowLimit)} />;+ case "bar-vertical":+ return <VerticalBarChart data={data.slice(0, rowLimit)} />;+ case "pie":+ return <PieChart data={data.slice(0, rowLimit)} />;+ default:+ return <HorizontalBarChart data={data.slice(0, rowLimit)} />;+ }+ })()}+ </CardContent>+ );+};diff --git a/web/src/features/widgets/chart-library/HorizontalBarChart.tsx b/web/src/features/widgets/chart-library/HorizontalBarChart.tsxnew file mode 100644index 0000000000..3271809f60--- /dev/null+++ b/web/src/features/widgets/chart-library/HorizontalBarChart.tsx@@ -0,0 +1,61 @@+import React from "react";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@/src/components/ui/chart";+import { Bar, BarChart, XAxis, YAxis } from "recharts";+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";++/**+ * HorizontalBarChart component+ * @param data - Data to be displayed. Expects an array of objects with dimension and metric properties.+ * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.+ * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.+ */+export const HorizontalBarChart: React.FC<ChartProps> = ({+ data,+ config = {+ metric: {+ theme: {+ light: "hsl(var(--chart-1))",+ dark: "hsl(var(--chart-1))",+ },+ },+ },+ accessibilityLayer = true,+}) => {+ return (+ <ChartContainer config={config}>+ <BarChart+ accessibilityLayer={accessibilityLayer}+ data={data}+ layout="vertical"+ >+ <XAxis+ type="number"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <YAxis+ type="category"+ dataKey="dimension"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <Bar+ dataKey="metric"+ radius={[0, 4, 4, 0]}+ className="fill-[--color-metric]"+ />+ <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ </BarChart>+ </ChartContainer>+ );+};++export default HorizontalBarChart;diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsxnew file mode 100644index 0000000000..8b3a3d16ae--- /dev/null+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx@@ -0,0 +1,69 @@+import React, { useMemo } from "react";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@/src/components/ui/chart";+import { Line, LineChart, XAxis, YAxis } from "recharts";+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";+import {+ getUniqueDimensions,+ groupDataByTimeDimension,+} from "@/src/features/widgets/chart-library/utils";++/**+ * LineChartTimeSeries component+ * @param data - Data to be displayed. Expects an array of objects with time_dimension, dimension, and metric properties.+ * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.+ * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.+ */+export const LineChartTimeSeries: React.FC<ChartProps> = ({+ data,+ config = {+ metric: {+ theme: {+ light: "hsl(var(--chart-1))",+ dark: "hsl(var(--chart-1))",+ },+ },+ },+ accessibilityLayer = true,+}) => {+ const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);+ const dimensions = useMemo(() => getUniqueDimensions(data), [data]);++ return (+ <ChartContainer config={config}>+ <LineChart accessibilityLayer={accessibilityLayer} data={groupedData}>+ <XAxis+ dataKey="time_dimension"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <YAxis+ type="number"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ {dimensions.map((dimension, index) => (+ <Line+ key={dimension}+ type="monotone"+ dataKey={dimension}+ strokeWidth={2}+ dot={true}+ activeDot={{ r: 6, strokeWidth: 0 }}+ stroke={`hsl(var(--chart-${(index % 4) + 1}))`}+ />+ ))}+ <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ </LineChart>+ </ChartContainer>+ );+};++export default LineChartTimeSeries;diff --git a/web/src/features/widgets/chart-library/PieChart.tsx b/web/src/features/widgets/chart-library/PieChart.tsxnew file mode 100644index 0000000000..26c68c80c1--- /dev/null+++ b/web/src/features/widgets/chart-library/PieChart.tsx@@ -0,0 +1,99 @@+import React, { useMemo } from "react";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@/src/components/ui/chart";+import { Label, Pie, PieChart as PieChartComponent } from "recharts";+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";++/**+ * PieChart component+ * @param data - Data to be displayed. Expects an array of objects with dimension and metric properties.+ * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.+ * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.+ */+export const PieChart: React.FC<ChartProps> = ({+ data,+ config = {+ metric: {+ theme: {+ light: "hsl(var(--chart-1))",+ dark: "hsl(var(--chart-1))",+ },+ },+ },+ accessibilityLayer = true,+}) => {+ // Calculate total metric value for center label+ const totalValue = useMemo(() => {+ return data.reduce((acc, curr) => acc + curr.metric, 0);+ }, [data]);++ // Transform data for PieChart+ const chartData = useMemo(() => {+ return data.map((item, index) => ({+ name: item.dimension || "Unknown",+ value: item.metric,+ fill: `hsl(var(--chart-${(index % 4) + 1}))`,+ }));+ }, [data]);++ return (+ <ChartContainer config={config}>+ <PieChartComponent accessibilityLayer={accessibilityLayer}>+ <ChartTooltip+ cursor={false}+ content={<ChartTooltipContent hideLabel />}+ />+ <Pie+ data={chartData}+ dataKey="value"+ nameKey="name"+ cx="50%"+ cy="50%"+ innerRadius={80}+ outerRadius={120}+ paddingAngle={2}+ strokeWidth={5}+ >+ {/* Label in the center of the donut */}+ {data.length > 0 && (+ <Label+ content={({ viewBox }) => {+ if (viewBox && "cx" in viewBox && "cy" in viewBox) {+ return (+ <text+ x={viewBox.cx}+ y={viewBox.cy}+ textAnchor="middle"+ dominantBaseline="middle"+ >+ <tspan+ x={viewBox.cx}+ y={viewBox.cy}+ className="fill-foreground text-3xl font-bold"+ >+ {totalValue.toLocaleString()}+ </tspan>+ <tspan+ x={viewBox.cx}+ y={(viewBox.cy || 0) + 24}+ className="fill-muted-foreground"+ >+ Total+ </tspan>+ </text>+ );+ }+ return null;+ }}+ />+ )}+ </Pie>+ </PieChartComponent>+ </ChartContainer>+ );+};++export default PieChart;diff --git a/web/src/features/widgets/chart-library/VerticalBarChart.tsx b/web/src/features/widgets/chart-library/VerticalBarChart.tsxnew file mode 100644index 0000000000..1203805519--- /dev/null+++ b/web/src/features/widgets/chart-library/VerticalBarChart.tsx@@ -0,0 +1,57 @@+import React from "react";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@/src/components/ui/chart";+import { Bar, BarChart, XAxis, YAxis } from "recharts";+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";++/**+ * VerticalBarChart component+ * @param data - Data to be displayed. Expects an array of objects with dimension and metric properties.+ * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.+ * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.+ */+export const VerticalBarChart: React.FC<ChartProps> = ({+ data,+ config = {+ metric: {+ theme: {+ light: "hsl(var(--chart-1))",+ dark: "hsl(var(--chart-1))",+ },+ },+ },+ accessibilityLayer = true,+}) => {+ return (+ <ChartContainer config={config}>+ <BarChart accessibilityLayer={accessibilityLayer} data={data}>+ <XAxis+ type="category"+ dataKey="dimension"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <YAxis+ type="number"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <Bar+ dataKey="metric"+ radius={[4, 4, 0, 0]}+ className="fill-[--color-metric]"+ />+ <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ </BarChart>+ </ChartContainer>+ );+};++export default VerticalBarChart;diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsxnew file mode 100644index 0000000000..239138b7b9--- /dev/null+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx@@ -0,0 +1,68 @@+import React, { useMemo } from "react";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@/src/components/ui/chart";+import { Bar, BarChart, XAxis, YAxis } from "recharts";+import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";+import {+ getUniqueDimensions,+ groupDataByTimeDimension,+} from "@/src/features/widgets/chart-library/utils";++/**+ * VerticalBarChartTimeSeries component+ * @param data - Data to be displayed. Expects an array of objects with time_dimension, dimension, and metric properties.+ * @param config - Configuration object for the chart. Can include theme settings for light and dark modes.+ * @param accessibilityLayer - Boolean to enable or disable the accessibility layer. Default is true.+ */+export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({+ data,+ config = {+ metric: {+ theme: {+ light: "hsl(var(--chart-1))",+ dark: "hsl(var(--chart-1))",+ },+ },+ },+ accessibilityLayer = true,+}) => {+ const groupedData = useMemo(() => groupDataByTimeDimension(data), [data]);+ const dimensions = useMemo(() => getUniqueDimensions(data), [data]);++ return (+ <ChartContainer config={config}>+ <BarChart accessibilityLayer={accessibilityLayer} data={groupedData}>+ <XAxis+ dataKey="time_dimension"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ <YAxis+ type="number"+ stroke="hsl(var(--chart-grid))"+ fontSize={12}+ tickLine={false}+ axisLine={false}+ />+ {dimensions.map((dimension, index) => (+ <Bar+ key={dimension}+ dataKey={dimension}+ stroke={`hsl(var(--chart-${(index % 4) + 1}))`}+ fill={`hsl(var(--chart-${(index % 4) + 1}))`}+ // Stack bars if there are multiple dimensions+ stackId={dimensions.length > 1 ? "stack" : undefined}+ />+ ))}+ <ChartTooltip content={<ChartTooltipContent hideLabel />} />+ </BarChart>+ </ChartContainer>+ );+};++export default VerticalBarChartTimeSeries;diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.tsnew file mode 100644index 0000000000..b8dbabb5b6--- /dev/null+++ b/web/src/features/widgets/chart-library/chart-props.ts@@ -0,0 +1,13 @@+import { type ChartConfig } from "@/src/components/ui/chart";++export interface DataPoint {+ time_dimension: string | undefined;+ dimension: string | undefined;+ metric: number;+}++export interface ChartProps {+ data: DataPoint[];+ config?: ChartConfig;+ accessibilityLayer?: boolean;+}diff --git a/web/src/features/widgets/chart-library/utils.ts b/web/src/features/widgets/chart-library/utils.tsnew file mode 100644index 0000000000..6818b92dd5--- /dev/null+++ b/web/src/features/widgets/chart-library/utils.ts@@ -0,0 +1,39 @@+import { type DataPoint } from "./chart-props";++/**+ * Groups data by dimension to prepare it for time series breakdowns+ * @param data+ */+export const groupDataByTimeDimension = (data: DataPoint[]) => {+ // First, group by time_dimension+ const timeGroups = data.reduce(+ (acc: Record<string, Record<string, number>>, item: DataPoint) => {+ const time = item.time_dimension || "Unknown";+ if (!acc[time]) {+ acc[time] = {};+ }++ const dimension = item.dimension || "Unknown";+ acc[time][dimension] = item.metric;++ return acc;+ },+ {},+ );++ // Convert to array format for Recharts+ return Object.entries(timeGroups).map(([time, dimensions]) => ({+ time_dimension: time,+ ...dimensions,+ }));+};++export const getUniqueDimensions = (data: DataPoint[]) => {+ const uniqueDimensions = new Set<string>();+ data.forEach((item: DataPoint) => {+ if (item.dimension) {+ uniqueDimensions.add(item.dimension);+ }+ });+ return Array.from(uniqueDimensions);+};diff --git a/web/src/pages/project/[projectId]/queryPlayground.tsx b/web/src/pages/project/[projectId]/queryPlayground.tsxindex e111fbfdf4..8e2de8d1eb 100644--- a/web/src/pages/project/[projectId]/queryPlayground.tsx+++ b/web/src/pages/project/[projectId]/queryPlayground.tsx@@ -27,8 +27,7 @@ export default function QueryPlayground() {},"fromTimestamp": "${new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()}","toTimestamp": "${new Date().toISOString()}",- "page": 0,- "limit": 50+ "orderBy": null}`);const [error, setError] = useState<string | null>(null);diff --git a/web/src/pages/project/[projectId]/widgets/new.tsx b/web/src/pages/project/[projectId]/widgets/new.tsxnew file mode 100644index 0000000000..abc7f0e25f--- /dev/null+++ b/web/src/pages/project/[projectId]/widgets/new.tsx@@ -0,0 +1,552 @@+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";+import Page from "@/src/components/layouts/page";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import { api } from "@/src/utils/api";+import {+ metricAggregations,+ type QueryType,+ mapLegacyUiTableFilterToView,+} from "@/src/features/query";+import { useState, useMemo, useEffect } from "react";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Label } from "@/src/components/ui/label";+import { viewDeclarations } from "@/src/features/query/dataModel";+import { type z } from "zod";+import { views } from "@/src/features/query/types";+import { Input } from "@/src/components/ui/input";+import { startCase } from "lodash";+import { DatePickerWithRange } from "@/src/components/date-picker";+import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";+import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";+import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";+import { type ColumnDefinition } from "@langfuse/shared";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";++export default function NewWidget() {+ const session = useSession();+ const isAdmin = session.data?.user?.admin === true;++ const router = useRouter();+ const { projectId } = router.query as { projectId: string };++ // State for form fields+ const [widgetName, setWidgetName] = useState<string>("Traces");+ const [widgetDescription, setWidgetDescription] = useState<string>(+ "Traces grouped by name for the last 30 days.",+ );+ const [selectedView, setSelectedView] =+ useState<z.infer<typeof views>>("traces");+ const [selectedMetric, setSelectedMetric] = useState<string>("count");+ const [selectedAggregation, setSelectedAggregation] =+ useState<z.infer<typeof metricAggregations>>("count");+ const [selectedDimension, setSelectedDimension] = useState<string>("none");++ // Filter state+ const { selectedOption, dateRange, setDateRangeAndOption } =+ useDashboardDateRange();+ const [userFilterState, setUserFilterState] = useQueryFilterState(+ [],+ "widgets",+ projectId,+ );++ const traceFilterOptions = api.traces.filterOptions.useQuery(+ {+ projectId,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );++ const environmentFilterOptions =+ api.projects.environmentFilterOptions.useQuery(+ { projectId },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );+ const environmentOptions =+ environmentFilterOptions.data?.map((value) => ({+ value: value.environment,+ })) || [];+ const nameOptions = traceFilterOptions.data?.name || [];+ const tagsOptions = traceFilterOptions.data?.tags || [];++ // Filter columns for PopoverFilterBuilder+ const filterColumns: ColumnDefinition[] = [+ {+ name: "Environment",+ id: "environment",+ type: "stringOptions",+ options: environmentOptions,+ internal: "internalValue",+ },+ {+ name: "Trace Name",+ id: "traceName",+ type: "stringOptions",+ options: nameOptions,+ internal: "internalValue",+ },+ {+ name: "Tags",+ id: "tags",+ type: "arrayOptions",+ options: tagsOptions,+ internal: "internalValue",+ },+ {+ name: "User",+ id: "user",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Session",+ id: "session",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Release",+ id: "release",+ type: "string",+ internal: "internalValue",+ },+ {+ name: "Version",+ id: "version",+ type: "string",+ internal: "internalValue",+ },+ ];++ // Chart type options+ type ChartType = {+ group: "time-series" | "total-value";+ name: string;+ value: string;+ };++ const chartTypes: ChartType[] = useMemo(+ () => [+ { group: "time-series", name: "Line Chart", value: "line-time-series" },+ {+ group: "time-series",+ name: "Vertical Bar Chart",+ value: "bar-time-series",+ },+ {+ group: "total-value",+ name: "Horizontal Bar Chart",+ value: "bar-horizontal",+ },+ {+ group: "total-value",+ name: "Vertical Bar Chart",+ value: "bar-vertical",+ },+ { group: "total-value", name: "Pie Chart", value: "pie" },+ ],+ [],+ );++ const [selectedChartType, setSelectedChartType] =+ useState<string>("line-time-series");+ const [rowLimit, setRowLimit] = useState<number>(100);++ // Reset form fields when view changes+ useEffect(() => {+ if (selectedView) {+ setSelectedMetric("count");+ setSelectedAggregation("count");+ setSelectedDimension("none");+ }+ }, [selectedView]);++ // Set aggregation to "count" when metric is "count"+ useEffect(() => {+ if (selectedMetric === "count") {+ setSelectedAggregation("count");+ }+ }, [selectedMetric]);++ // Get available metrics for the selected view+ const availableMetrics = useMemo(() => {+ const viewDeclaration = viewDeclarations[selectedView];+ return Object.entries(viewDeclaration.measures).map(([key]) => ({+ value: key,+ label: startCase(key),+ }));+ }, [selectedView]);++ // Get available dimensions for the selected view+ const availableDimensions = useMemo(() => {+ const viewDeclaration = viewDeclarations[selectedView];+ return Object.entries(viewDeclaration.dimensions).map(([key]) => ({+ value: key,+ label: startCase(key),+ }));+ }, [selectedView]);++ // Check if the selected chart type is a time series chart+ const isTimeSeriesChart = useMemo(() => {+ return (+ chartTypes.find((chart) => chart.value === selectedChartType)?.group ===+ "time-series"+ );+ }, [selectedChartType, chartTypes]);++ // Create a dynamic query based on the selected view+ const query = useMemo<QueryType>(() => {+ // Calculate fromTimestamp and toTimestamp from dateRange+ const fromTimestamp = dateRange+ ? dateRange.from+ : new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000); // Default to last 7 days+ const toTimestamp = dateRange ? dateRange.to : new Date();++ return {+ view: selectedView,+ dimensions:+ selectedDimension !== "none" ? [{ field: selectedDimension }] : [],+ metrics: [{ measure: selectedMetric, aggregation: selectedAggregation }],+ filters: [...mapLegacyUiTableFilterToView(selectedView, userFilterState)],+ timeDimension: isTimeSeriesChart ? { granularity: "auto" } : null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };+ }, [+ selectedView,+ selectedDimension,+ selectedAggregation,+ selectedMetric,+ userFilterState,+ dateRange,+ isTimeSeriesChart,+ ]);++ const queryResult = api.dashboard.executeQuery.useQuery(+ {+ projectId,+ query,+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ enabled: isAdmin, // Only run query if isAdmin is true+ },+ );++ // Transform the query results to a consistent format for charts+ const transformedData: DataPoint[] = useMemo(+ () =>+ queryResult.data?.map((item: any) => {+ // Get the dimension field (first dimension in the query)+ const dimensionField = selectedDimension;+ // Get the metric field (first metric in the query with its aggregation)+ const metricField = `${selectedAggregation}_${selectedMetric}`;++ return {+ dimension: item[dimensionField]+ ? (item[dimensionField] as string)+ : "n/a",+ metric: Number(item[metricField] || 0),+ time_dimension: item["time_dimension"],+ };+ }) ?? [],+ [queryResult.data, selectedAggregation, selectedDimension, selectedMetric],+ );++ if (!isAdmin) {+ return null; // Blank page for non-admins+ }++ return (+ <Page+ withPadding+ headerProps={{+ title: "New Widget",+ help: {+ description: "Create a new widget",+ },+ }}+ >+ <div className="flex h-full gap-4">+ {/* Left column - Form */}+ <div className="h-full w-1/3">+ <Card className="flex h-full flex-col">+ <CardHeader>+ <CardTitle>Widget Configuration</CardTitle>+ <CardDescription>+ Configure your widget by selecting data and visualization+ options+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4 overflow-y-auto">+ {/* Widget Name */}+ <div className="space-y-2">+ <Label htmlFor="widget-name">Name</Label>+ <Input+ id="widget-name"+ value={widgetName}+ onChange={(e) => setWidgetName(e.target.value)}+ placeholder="Enter widget name"+ />+ </div>++ {/* Widget Description */}+ <div className="space-y-2">+ <Label htmlFor="widget-description">Description</Label>+ <Input+ id="widget-description"+ value={widgetDescription}+ onChange={(e) => setWidgetDescription(e.target.value)}+ placeholder="Enter widget description"+ />+ </div>++ {/* Data Selection Section */}+ <div className="mt-6 space-y-4">+ <h3 className="text-lg font-bold">Data Selection</h3>++ {/* View Selection */}+ <div className="space-y-2">+ <Label htmlFor="view-select">View</Label>+ <Select+ value={selectedView}+ onValueChange={(value) =>+ setSelectedView(value as z.infer<typeof views>)+ }+ >+ <SelectTrigger id="view-select">+ <SelectValue placeholder="Select a view" />+ </SelectTrigger>+ <SelectContent>+ {views.options.map((view) => (+ <SelectItem key={view} value={view}>+ {startCase(view)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ {/* Metrics Selection */}+ <div className="space-y-2">+ <Label htmlFor="metrics-select">Metric</Label>+ <Select+ value={selectedMetric}+ onValueChange={(value) => setSelectedMetric(value)}+ >+ <SelectTrigger id="metrics-select">+ <SelectValue placeholder="Select metrics" />+ </SelectTrigger>+ <SelectContent>+ {availableMetrics.map((metric) => (+ <SelectItem key={metric.value} value={metric.value}>+ {metric.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {selectedMetric !== "count" && (+ <Select+ value={selectedAggregation}+ onValueChange={(value) =>+ setSelectedAggregation(+ value as z.infer<typeof metricAggregations>,+ )+ }+ >+ <SelectTrigger id="aggregation-select">+ <SelectValue placeholder="Select Aggregation" />+ </SelectTrigger>+ <SelectContent>+ {metricAggregations.options.map((aggregation) => (+ <SelectItem key={aggregation} value={aggregation}>+ {startCase(aggregation)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </div>++ {/* Filters Section */}+ <div className="space-y-2">+ <Label>Filters</Label>+ <div className="space-y-2">+ <InlineFilterBuilder+ columns={filterColumns}+ filterState={userFilterState}+ onChange={setUserFilterState}+ />+ </div>+ </div>++ {/* Dimension Selection (Breakdown) */}+ <div className="space-y-2">+ <Label htmlFor="dimension-select">+ Breakdown Dimension (Optional)+ </Label>+ <Select+ value={selectedDimension}+ onValueChange={setSelectedDimension}+ >+ <SelectTrigger id="dimension-select">+ <SelectValue placeholder="Select a dimension" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">None</SelectItem>+ {availableDimensions.map((dimension) => (+ <SelectItem+ key={dimension.value}+ value={dimension.value}+ >+ {dimension.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>++ {/* Visualization Section */}+ <div className="mt-6 space-y-4">+ <h3 className="text-lg font-bold">Visualization</h3>++ {/* Chart Type Selection */}+ <div className="space-y-2">+ <Label htmlFor="chart-type-select">Chart Type</Label>+ <Select+ value={selectedChartType}+ onValueChange={setSelectedChartType}+ >+ <SelectTrigger id="chart-type-select">+ <SelectValue placeholder="Select a chart type" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Time Series</SelectLabel>+ {chartTypes+ .filter((item) => item.group === "time-series")+ .map((chart) => (+ <SelectItem key={chart.value} value={chart.value}>+ {chart.name}+ </SelectItem>+ ))}+ </SelectGroup>+ <SelectGroup>+ <SelectLabel>Total Value</SelectLabel>+ {chartTypes+ .filter((item) => item.group === "total-value")+ .map((chart) => (+ <SelectItem key={chart.value} value={chart.value}>+ {chart.name}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-2">+ <Label htmlFor="date-select">Date Range</Label>+ <DatePickerWithRange+ dateRange={dateRange}+ setDateRangeAndOption={setDateRangeAndOption}+ selectedOption={selectedOption}+ className="w-full"+ />+ </div>++ {/* Row Limit Selection - Only shown for non-time series charts */}+ {!isTimeSeriesChart && (+ <div className="space-y-2">+ <Label htmlFor="row-limit">Row Limit (1-1000)</Label>+ <Input+ id="row-limit"+ type="number"+ min={1}+ max={1000}+ value={rowLimit}+ onChange={(e) => {+ const value = parseInt(e.target.value);+ if (!isNaN(value) && value >= 1 && value <= 1000) {+ setRowLimit(value);+ }+ }}+ placeholder="Enter row limit (1-1000)"+ />+ </div>+ )}+ </div>+ </CardContent>+ </Card>+ </div>++ {/* Right column - Chart */}+ <div className="w-2/3">+ <Card>+ <CardHeader>+ <CardTitle>{widgetName}</CardTitle>+ <CardDescription>{widgetDescription}</CardDescription>+ </CardHeader>+ {queryResult.data ? (+ <Chart+ chartType={selectedChartType}+ data={transformedData}+ rowLimit={rowLimit}+ />+ ) : (+ <CardContent>+ <div className="flex h-[300px] items-center justify-center">+ <p className="text-muted-foreground">+ Waiting for Input / Loading...+ </p>+ </div>+ </CardContent>+ )}+ </Card>+ </div>+ </div>+ </Page>+ );+}diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex 095178c291..c745d75518 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -73,6 +73,12 @@--sidebar-accent-foreground: 240 5.9% 10%;--sidebar-border: 220 13% 91%;--sidebar-ring: 217.2 91.2% 59.8%;++ --chart-1: var(--dark-green);+ --chart-2: var(--dark-yellow);+ --chart-3: var(--dark-blue);+ --chart-4: var(--dark-red);+ --chart-grid: var(--muted-gray);}.dark {@@ -147,6 +153,12 @@--sidebar-accent-foreground: 210 40% 86%;--sidebar-border: 217.2 32.6% 26.5%;--sidebar-ring: 224.3 76.3% 46%;++ --chart-1: var(--dark-green);+ --chart-2: var(--dark-yellow);+ --chart-3: var(--dark-blue);+ --chart-4: var(--dark-red);+ --chart-grid: var(--muted-gray);}}