Skip to content

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

feat(dataset-compare): manually review in compare view (#9536)

marliessophiec49442ae27d0
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index d17d4d9bf7..ffcf4b4f9d 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -48,11 +48,12 @@ export type ScoreTargetSession = z.infer<typeof ScoreTargetSession>;
export type ScoreTarget = z.infer<typeof ScoreTarget>;
const CreateAnnotationScoreBase = z.object({
+ id: z.string().optional(),
name: StringNoHTMLNonEmpty,
projectId: z.string(),
environment: z.string().default("default"),
scoreTarget: ScoreTarget,
- configId: z.string().optional(),
+ configId: z.string(),
comment: StringNoHTML.nullish(),
queueId: z.string().nullish(),
});
@@ -71,6 +72,10 @@ export const CreateAnnotationScoreData = z.discriminatedUnion("dataType", [
CreateAnnotationScoreBase.merge(BooleanData),
]);
+export type CreateAnnotationScoreData = z.infer<
+ typeof CreateAnnotationScoreData
+>;
+
/**
* UpdateAnnotationScoreData is only used for annotation scores updated via the UI
* For langfuse score types please refer to `web/src/features/public-api/types/scores.ts`
@@ -81,6 +86,10 @@ export const UpdateAnnotationScoreData = z.discriminatedUnion("dataType", [
UpdateAnnotationScoreBase.merge(BooleanData),
]);
+export type UpdateAnnotationScoreData = z.infer<
+ typeof UpdateAnnotationScoreData
+>;
+
// annotation queues
export const CreateQueueData = z.object({
diff --git a/web/src/__tests__/mergeScoresWithCache.clienttest.ts b/web/src/__tests__/mergeScoresWithCache.clienttest.ts
new file mode 100644
index 0000000000..4e46a1f4b9
--- /dev/null
+++ b/web/src/__tests__/mergeScoresWithCache.clienttest.ts
@@ -0,0 +1,643 @@
+import {
+ mergeScoresWithCache,
+ mergeAggregatesWithCache,
+ mergeAnnotationScoresWithCache,
+} from "@/src/features/scores/lib/mergeScoresWithCache";
+import { type APIScoreV2, type ScoreAggregate } from "@langfuse/shared";
+import { type CachedScore } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { type AnnotationScore } from "@/src/features/scores/types";
+
+describe("mergeScoresWithCache", () => {
+ it("should return server scores when cache is empty", () => {
+ const serverScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-1",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const result = mergeScoresWithCache(serverScores, [], new Set());
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.id).toBe("score-1");
+ });
+
+ it("should filter out deleted server scores", () => {
+ const serverScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-1",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ {
+ id: "score-2",
+ name: "sentiment",
+ source: "ANNOTATION",
+ dataType: "CATEGORICAL",
+ value: 1,
+ stringValue: "positive",
+ configId: "config-2",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const deletedIds = new Set(["score-1"]);
+
+ const result = mergeScoresWithCache(serverScores, [], deletedIds);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.id).toBe("score-2");
+ });
+
+ it("should overlay cached scores onto server scores", () => {
+ const serverScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 5,
+ stringValue: null,
+ configId: "config-1",
+ comment: "Old value",
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: "Updated value",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeScoresWithCache(serverScores, cachedScores, new Set());
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.value).toBe(8);
+ expect(result[0]?.comment).toBe("Updated value");
+ });
+
+ it("should add cache-only scores", () => {
+ const serverScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-1",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ source: "ANNOTATION",
+ configId: "config-2",
+ value: null,
+ stringValue: "positive",
+ comment: null,
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeScoresWithCache(serverScores, cachedScores, new Set());
+
+ expect(result).toHaveLength(2);
+ const ids = result.map((s) => s.id);
+ expect(ids).toContain("score-1");
+ expect(ids).toContain("score-2");
+ });
+
+ it("should handle both delete and cache overlay", () => {
+ const serverScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-1",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ {
+ id: "score-2",
+ name: "sentiment",
+ source: "ANNOTATION",
+ dataType: "CATEGORICAL",
+ value: 1,
+ stringValue: "positive",
+ configId: "config-2",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-3",
+ name: "accuracy",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-3",
+ value: 0.95,
+ stringValue: null,
+ comment: "New score",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const deletedIds = new Set(["score-1"]);
+
+ const result = mergeScoresWithCache(serverScores, cachedScores, deletedIds);
+
+ expect(result).toHaveLength(2);
+ const ids = result.map((s) => s.id);
+ expect(ids).not.toContain("score-1"); // Deleted
+ expect(ids).toContain("score-2"); // Server
+ expect(ids).toContain("score-3"); // Cache only
+ });
+});
+
+describe("mergeAggregatesWithCache", () => {
+ it("should return server aggregates when cache is empty", () => {
+ const serverAggregates: ScoreAggregate = {
+ "quality-ANNOTATION-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [8],
+ average: 8,
+ comment: null,
+ },
+ };
+
+ const result = mergeAggregatesWithCache(serverAggregates, [], new Set());
+
+ expect(Object.keys(result)).toHaveLength(1);
+ expect(result["quality-ANNOTATION-NUMERIC"]?.values).toEqual([8]);
+ });
+
+ it("should remove deleted aggregates", () => {
+ const serverAggregates: ScoreAggregate = {
+ "quality-ANNOTATION-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [8],
+ average: 8,
+ comment: null,
+ },
+ "sentiment-ANNOTATION-CATEGORICAL": {
+ id: "score-2",
+ type: "CATEGORICAL",
+ values: ["positive"],
+ valueCounts: [{ value: "positive", count: 1 }],
+ comment: null,
+ },
+ };
+
+ const deletedIds = new Set(["score-1"]);
+
+ const result = mergeAggregatesWithCache(serverAggregates, [], deletedIds);
+
+ expect(Object.keys(result)).toHaveLength(1);
+ expect(result["quality-ANNOTATION-NUMERIC"]).toBeUndefined();
+ expect(result["sentiment-ANNOTATION-CATEGORICAL"]).toBeDefined();
+ });
+
+ it("should overlay cached numeric score", () => {
+ const serverAggregates: ScoreAggregate = {
+ "quality-ANNOTATION-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [5],
+ average: 5,
+ comment: "Old",
+ },
+ };
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 9,
+ stringValue: null,
+ comment: "Updated",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeAggregatesWithCache(
+ serverAggregates,
+ cachedScores,
+ new Set(),
+ );
+
+ const aggregate = result["quality-ANNOTATION-NUMERIC"];
+ expect(aggregate).toBeDefined();
+ expect(aggregate?.type).toBe("NUMERIC");
+ if (aggregate?.type === "NUMERIC") {
+ expect(aggregate.average).toBe(9);
+ expect(aggregate.comment).toBe("Updated");
+ expect(aggregate.id).toBe("score-1");
+ }
+ });
+
+ it("should overlay cached categorical score", () => {
+ const serverAggregates: ScoreAggregate = {
+ "sentiment-ANNOTATION-CATEGORICAL": {
+ id: "score-2",
+ type: "CATEGORICAL",
+ values: ["negative"],
+ valueCounts: [{ value: "negative", count: 1 }],
+ comment: null,
+ },
+ };
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ source: "ANNOTATION",
+ configId: "config-2",
+ value: null,
+ stringValue: "positive",
+ comment: "Changed",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeAggregatesWithCache(
+ serverAggregates,
+ cachedScores,
+ new Set(),
+ );
+
+ const aggregate = result["sentiment-ANNOTATION-CATEGORICAL"];
+ expect(aggregate).toBeDefined();
+ expect(aggregate?.type).toBe("CATEGORICAL");
+ if (aggregate?.type === "CATEGORICAL") {
+ expect(aggregate.values).toEqual(["positive"]);
+ expect(aggregate.comment).toBe("Changed");
+ expect(aggregate.id).toBe("score-2");
+ }
+ });
+
+ it("should add cache-only aggregates", () => {
+ const serverAggregates: ScoreAggregate = {
+ "quality-ANNOTATION-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [8],
+ average: 8,
+ comment: null,
+ },
+ };
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-3",
+ name: "accuracy",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-3",
+ value: 0.95,
+ stringValue: null,
+ comment: "New",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ {
+ id: "score-3",
+ name: "accuracy",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-3",
+ value: 0.95,
+ stringValue: null,
+ comment: "New",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeAggregatesWithCache(
+ serverAggregates,
+ cachedScores,
+ new Set(),
+ );
+
+ expect(Object.keys(result)).toHaveLength(2);
+ expect(result["accuracy-ANNOTATION-NUMERIC"]).toBeDefined();
+ });
+});
+
+describe("mergeAnnotationScoresWithCache", () => {
+ it("should return server annotation scores when cache is empty", () => {
+ const serverAnnotationScores: AnnotationScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ },
+ ];
+
+ const result = mergeAnnotationScoresWithCache(
+ serverAnnotationScores,
+ [],
+ new Set(),
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.id).toBe("score-1");
+ });
+
+ it("should filter out deleted annotation scores", () => {
+ const serverAnnotationScores: AnnotationScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ },
+ {
+ id: "score-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ source: "ANNOTATION",
+ configId: "config-2",
+ value: null,
+ stringValue: "positive",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ },
+ ];
+
+ const deletedIds = new Set(["score-1"]);
+
+ const result = mergeAnnotationScoresWithCache(
+ serverAnnotationScores,
+ [],
+ deletedIds,
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.id).toBe("score-2");
+ });
+
+ it("should overlay cached annotation scores", () => {
+ const serverAnnotationScores: AnnotationScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 5,
+ stringValue: null,
+ comment: "Old",
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ },
+ ];
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 9,
+ stringValue: null,
+ comment: "Updated",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeAnnotationScoresWithCache(
+ serverAnnotationScores,
+ cachedScores,
+ new Set(),
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.value).toBe(9);
+ expect(result[0]?.comment).toBe("Updated");
+ });
+
+ it("should add cache-only annotation scores", () => {
+ const serverAnnotationScores: AnnotationScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ },
+ ];
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ source: "ANNOTATION",
+ configId: "config-2",
+ value: null,
+ stringValue: "positive",
+ comment: "New",
+ traceId: "trace-1",
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeAnnotationScoresWithCache(
+ serverAnnotationScores,
+ cachedScores,
+ new Set(),
+ );
+
+ expect(result).toHaveLength(2);
+ const ids = result.map((s) => s.id);
+ expect(ids).toContain("score-1");
+ expect(ids).toContain("score-2");
+ });
+
+ it("should convert CachedScore fields correctly", () => {
+ const serverAnnotationScores: AnnotationScore[] = [];
+
+ const cachedScores: CachedScore[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: "Test",
+ traceId: "trace-1",
+ observationId: "obs-1",
+ sessionId: undefined,
+ projectId: "project-1",
+ environment: "production",
+ },
+ ];
+
+ const result = mergeAnnotationScoresWithCache(
+ serverAnnotationScores,
+ cachedScores,
+ new Set(),
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: "Test",
+ traceId: "trace-1",
+ observationId: "obs-1",
+ sessionId: null,
+ });
+ });
+});
diff --git a/web/src/__tests__/transformScores.clienttest.ts b/web/src/__tests__/transformScores.clienttest.ts
new file mode 100644
index 0000000000..a5052b97ff
--- /dev/null
+++ b/web/src/__tests__/transformScores.clienttest.ts
@@ -0,0 +1,329 @@
+import { transformToAnnotationScores } from "@/src/features/scores/lib/transformScores";
+import {
+ type APIScoreV2,
+ type ScoreAggregate,
+ type ScoreConfigDomain,
+} from "@langfuse/shared";
+
+const mockConfigs: ScoreConfigDomain[] = [
+ {
+ id: "config-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ minValue: 0,
+ maxValue: 10,
+ isArchived: false,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId: "project-1",
+ },
+ {
+ id: "config-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ categories: [
+ { label: "positive", value: 1 },
+ { label: "negative", value: 0 },
+ ],
+ isArchived: false,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId: "project-1",
+ },
+];
+
+describe("transformToAnnotationScores - flat scores", () => {
+ it("should transform flat annotation scores correctly", () => {
+ const flatScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-1",
+ comment: "Good quality",
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ {
+ id: "score-2",
+ name: "sentiment",
+ source: "ANNOTATION",
+ dataType: "CATEGORICAL",
+ value: 1,
+ stringValue: "positive",
+ configId: "config-2",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const result = transformToAnnotationScores(flatScores, mockConfigs);
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual({
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: "Good quality",
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ });
+ expect(result[1]).toEqual({
+ id: "score-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ source: "ANNOTATION",
+ configId: "config-2",
+ value: 1,
+ stringValue: "positive",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ });
+ });
+
+ it("should filter out non-ANNOTATION scores", () => {
+ const flatScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "quality",
+ source: "API",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-1",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: null,
+ queueId: null,
+ },
+ {
+ id: "score-2",
+ name: "sentiment",
+ source: "ANNOTATION",
+ dataType: "CATEGORICAL",
+ value: 1,
+ stringValue: "positive",
+ configId: "config-2",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const result = transformToAnnotationScores(flatScores, mockConfigs);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.name).toBe("sentiment");
+ expect(result[0]?.source).toBe("ANNOTATION");
+ });
+
+ it("should filter out scores without matching config", () => {
+ const flatScores: APIScoreV2[] = [
+ {
+ id: "score-1",
+ name: "unknown",
+ source: "ANNOTATION",
+ dataType: "NUMERIC",
+ value: 8,
+ stringValue: null,
+ configId: "config-99",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ projectId: "project-1",
+ environment: "production",
+ timestamp: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ authorUserId: "user-1",
+ queueId: null,
+ },
+ ];
+
+ const result = transformToAnnotationScores(flatScores, mockConfigs);
+
+ expect(result).toHaveLength(0);
+ });
+
+ it("should handle empty array", () => {
+ const result = transformToAnnotationScores([], mockConfigs);
+ expect(result).toEqual([]);
+ });
+});
+
+describe("transformToAnnotationScores - aggregates", () => {
+ it("should transform single-value numeric aggregate correctly", () => {
+ const aggregates: ScoreAggregate = {
+ "quality-ANNOTATION-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [8],
+ average: 8,
+ comment: "Good quality",
+ },
+ };
+
+ const result = transformToAnnotationScores(
+ aggregates,
+ mockConfigs,
+ "trace-1",
+ "obs-1",
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ id: "score-1",
+ name: "quality",
+ dataType: "NUMERIC",
+ source: "ANNOTATION",
+ configId: "config-1",
+ value: 8,
+ stringValue: null,
+ comment: "Good quality",
+ traceId: "trace-1",
+ observationId: "obs-1",
+ sessionId: null,
+ });
+ });
+
+ it("should transform single-value categorical aggregate correctly", () => {
+ const aggregates: ScoreAggregate = {
+ "sentiment-ANNOTATION-CATEGORICAL": {
+ id: "score-2",
+ type: "CATEGORICAL",
+ values: ["positive"],
+ valueCounts: [{ value: "positive", count: 1 }],
+ comment: null,
+ },
+ };
+
+ const result = transformToAnnotationScores(
+ aggregates,
+ mockConfigs,
+ "trace-1",
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ id: "score-2",
+ name: "sentiment",
+ dataType: "CATEGORICAL",
+ source: "ANNOTATION",
+ configId: "config-2",
+ value: null,
+ stringValue: "positive",
+ comment: null,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ });
+ });
+
+ it("should skip multi-value aggregates (no id)", () => {
+ const aggregates: ScoreAggregate = {
+ "quality-ANNOTATION-NUMERIC": {
+ // No id - multi-value aggregate
+ type: "NUMERIC",
+ values: [8, 9, 7],
+ average: 8,
+ comment: null,
+ },
+ };
+
+ const result = transformToAnnotationScores(
+ aggregates,
+ mockConfigs,
+ "trace-1",
+ );
+
+ expect(result).toHaveLength(0);
+ });
+
+ it("should skip non-ANNOTATION source aggregates", () => {
+ const aggregates: ScoreAggregate = {
+ "quality-API-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [8],
+ average: 8,
+ comment: null,
+ },
+ };
+
+ const result = transformToAnnotationScores(
+ aggregates,
+ mockConfigs,
+ "trace-1",
+ );
+
+ expect(result).toHaveLength(0);
+ });
+
+ it("should skip aggregates without matching config", () => {
+ const aggregates: ScoreAggregate = {
+ "unknown-ANNOTATION-NUMERIC": {
+ id: "score-1",
+ type: "NUMERIC",
+ values: [8],
+ average: 8,
+ comment: null,
+ },
+ };
+
+ const result = transformToAnnotationScores(
+ aggregates,
+ mockConfigs,
+ "trace-1",
+ );
+
+ expect(result).toHaveLength(0);
+ });
+
+ it("should handle empty aggregates", () => {
+ const result = transformToAnnotationScores({}, mockConfigs, "trace-1");
+ expect(result).toEqual([]);
+ });
+});
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index aae9bdbda1..f3a4735260 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -16,7 +16,6 @@ import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import { Button } from "@/src/components/ui/button";
-import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { useSession } from "next-auth/react";
import Page from "@/src/components/layouts/page";
@@ -186,10 +185,6 @@ export const SessionPage: React.FC<{
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session.isSuccess, session.data]);
- const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
- string[]
- >("emptySelectedConfigIds", []);
-
const sessionCommentCounts = api.comments.getCountByObjectId.useQuery(
{
projectId,
@@ -287,10 +282,11 @@ export const SessionPage: React.FC<{
updatedAt: new Date(score.updatedAt),
})) ?? []
}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
+ scoreMetadata={{
+ projectId: projectId,
+ environment: session.data?.environment,
+ }}
buttonVariant="outline"
- hasGroupedButton={true}
/>
<CreateNewAnnotationQueueItem
projectId={projectId}
@@ -370,22 +366,22 @@ export const SessionPage: React.FC<{
buttonVariant="outline"
/>
<AnnotateDrawer
+ key={"annotation-drawer" + trace.id}
projectId={projectId}
scoreTarget={{
type: "trace",
traceId: trace.id,
}}
scores={trace.scores}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- variant="button"
buttonVariant="outline"
analyticsData={{
type: "trace",
source: "SessionDetail",
}}
- key={"annotation-drawer" + trace.id}
- environment={trace.environment}
+ scoreMetadata={{
+ projectId: projectId,
+ environment: trace.environment,
+ }}
/>
<CommentDrawerButton
projectId={projectId}
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index 855d8da658..8698c8e8ff 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -43,7 +43,7 @@ import { useJsonExpansion } from "@/src/components/trace/JsonExpansionContext";
export const ObservationPreview = ({
observations,
projectId,
- scores,
+ serverScores: scores,
currentObservationId,
traceId,
commentCounts,
@@ -52,7 +52,7 @@ export const ObservationPreview = ({
}: {
observations: Array<ObservationReturnType>;
projectId: string;
- scores: APIScoreV2[];
+ serverScores: APIScoreV2[];
currentObservationId: string;
traceId: string;
commentCounts?: Map<string, number>;
@@ -69,9 +69,6 @@ export const ObservationPreview = ({
);
const capture = usePostHogClientCapture();
const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(false);
- const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
- string[]
- >("emptySelectedConfigIds", []);
const isAuthenticatedAndProjectMember =
useIsAuthenticatedAndProjectMember(projectId);
@@ -84,6 +81,10 @@ export const ObservationPreview = ({
(o) => o.id === currentObservationId,
);
+ const currentObservationScores = scores.filter(
+ (s) => s.observationId === currentObservationId,
+ );
+
const observationWithInputAndOutput = api.observations.byId.useQuery({
observationId: currentObservationId,
startTime: currentObservation?.startTime,
@@ -168,11 +169,11 @@ export const ObservationPreview = ({
traceId: traceId,
observationId: preloadedObservation.id,
}}
- scores={scores}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- hasGroupedButton={true}
- environment={preloadedObservation.environment}
+ scores={currentObservationScores}
+ scoreMetadata={{
+ projectId: projectId,
+ environment: preloadedObservation.environment,
+ }}
/>
<CreateNewAnnotationQueueItem
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 6321580902..18807cc30c 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -49,7 +49,7 @@ import {
export const TracePreview = ({
trace,
observations,
- scores,
+ serverScores: scores,
commentCounts,
viewType = "detailed",
}: {
@@ -60,7 +60,7 @@ export const TracePreview = ({
metadata: string | null;
};
observations: ObservationReturnTypeWithMetadata[];
- scores: APIScoreV2[];
+ serverScores: APIScoreV2[];
commentCounts?: Map<string, number>;
viewType?: "detailed" | "focused";
}) => {
@@ -73,9 +73,6 @@ export const TracePreview = ({
"pretty",
);
const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(false);
- const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
- string[]
- >("emptySelectedConfigIds", []);
const isAuthenticatedAndProjectMember = useIsAuthenticatedAndProjectMember(
trace.projectId,
);
@@ -157,10 +154,10 @@ export const TracePreview = ({
traceId: trace.id,
}}
scores={scores}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- hasGroupedButton={true}
- environment={trace.environment}
+ scoreMetadata={{
+ projectId: trace.projectId,
+ environment: trace.environment,
+ }}
/>
<CreateNewAnnotationQueueItem
projectId={trace.projectId}
diff --git a/web/src/components/trace/TraceSearchList.tsx b/web/src/components/trace/TraceSearchList.tsx
index 5acd6206c9..e3f14088de 100644
--- a/web/src/components/trace/TraceSearchList.tsx
+++ b/web/src/components/trace/TraceSearchList.tsx
@@ -20,7 +20,7 @@ export interface TraceSearchListItem {
export interface TraceSearchListProps {
items: TraceSearchListItem[];
- scores: APIScoreV2[];
+ displayScores: APIScoreV2[];
onSelect: (observationId: string | undefined) => void;
comments?: Map<string, number>;
showMetrics: boolean;
@@ -32,7 +32,8 @@ export interface TraceSearchListProps {
export const TraceSearchList: React.FC<TraceSearchListProps> = ({
items,
- scores,
+ // Note: displayScores are merged with client-side score cache; handling optimistic updates
+ displayScores: scores,
onSelect,
comments,
showMetrics,
diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsx
index e98278a72c..0959cb0304 100644
--- a/web/src/components/trace/TraceTimelineView.tsx
+++ b/web/src/components/trace/TraceTimelineView.tsx
@@ -399,7 +399,8 @@ export function TraceTimelineView({
trace,
observations,
projectId,
- scores,
+ // Note: displayScores are merged with client-side score cache; handling optimistic updates
+ displayScores: scores,
currentObservationId,
setCurrentObservationId,
expandedItems,
@@ -420,7 +421,7 @@ export function TraceTimelineView({
};
observations: Array<ObservationReturnTypeWithMetadata>;
projectId: string;
- scores: APIScoreV2[];
+ displayScores: APIScoreV2[];
currentObservationId: string | null;
setCurrentObservationId: (id: string | null) => void;
expandedItems: string[];
diff --git a/web/src/components/trace/TraceTree.tsx b/web/src/components/trace/TraceTree.tsx
index ad7ba58131..668931a916 100644
--- a/web/src/components/trace/TraceTree.tsx
+++ b/web/src/components/trace/TraceTree.tsx
@@ -21,7 +21,7 @@ export const TraceTree = ({
tree,
collapsedNodes,
toggleCollapsedNode,
- scores,
+ displayScores: scores,
currentNodeId,
setCurrentNodeId,
showMetrics,
@@ -37,7 +37,8 @@ export const TraceTree = ({
tree: TreeNode;
collapsedNodes: string[];
toggleCollapsedNode: (id: string) => void;
- scores: APIScoreV2[];
+ // Note: displayScores are merged with client-side score cache; handling optimistic updates
+ displayScores: APIScoreV2[];
currentNodeId: string | undefined;
setCurrentNodeId: (id: string | undefined) => void;
showMetrics: boolean;
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 77e35d915a..214f431862 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -39,6 +39,7 @@ import {
ResizableHandle,
type ImperativePanelHandle,
} from "@/src/components/ui/resizable";
+import { useMergedScores } from "@/src/features/scores/lib/useMergedScores";
const getNestedObservationKeys = (
observations: ObservationReturnTypeWithMetadata[],
@@ -286,6 +287,16 @@ export function Trace(props: {
],
);
+ // Merge server scores with score cache for optimistic updates in the tree view
+ const displayScores = useMergedScores(
+ props.scores,
+ {
+ type: "trace",
+ traceId: props.trace.id,
+ },
+ "target-and-child-scores",
+ );
+
// Build UI data once
const {
tree: traceTree,
@@ -318,7 +329,7 @@ export function Trace(props: {
const treeOrSearchContent = hasQuery ? (
<TraceSearchList
items={searchItems}
- scores={props.scores}
+ displayScores={displayScores}
onSelect={setCurrentObservationId}
comments={commentsMap}
showMetrics={metricsOnObservationTree}
@@ -332,7 +343,7 @@ export function Trace(props: {
tree={traceTree}
collapsedNodes={collapsedNodes}
toggleCollapsedNode={toggleCollapsedNode}
- scores={props.scores}
+ displayScores={displayScores}
currentNodeId={currentObservationId ?? undefined}
setCurrentNodeId={setCurrentObservationId}
showMetrics={metricsOnObservationTree}
@@ -354,14 +365,14 @@ export function Trace(props: {
<TracePreview
trace={props.trace}
observations={props.observations}
- scores={props.scores}
+ serverScores={props.scores}
commentCounts={castToNumberMap(traceCommentCounts.data)}
viewType={viewType}
/>
) : isValidObservationId ? (
<ObservationPreview
observations={props.observations}
- scores={props.scores}
+ serverScores={props.scores}
projectId={props.projectId}
currentObservationId={currentObservationId}
traceId={props.trace.id}
@@ -526,7 +537,7 @@ export function Trace(props: {
<TraceTimelineView
key={props.trace.id}
trace={props.trace}
- scores={props.scores}
+ displayScores={displayScores}
observations={props.observations}
projectId={props.trace.projectId}
currentObservationId={currentObservationId ?? null}
@@ -797,7 +808,7 @@ export function Trace(props: {
<TraceTimelineView
key={`timeline-${props.trace.id}`}
trace={props.trace}
- scores={props.scores}
+ displayScores={displayScores}
observations={props.observations}
projectId={props.trace.projectId}
currentObservationId={
@@ -838,7 +849,7 @@ export function Trace(props: {
<TraceTimelineView
key={props.trace.id}
trace={props.trace}
- scores={props.scores}
+ displayScores={displayScores}
observations={props.observations}
projectId={props.trace.projectId}
currentObservationId={
diff --git a/web/src/components/ui/side-panel.tsx b/web/src/components/ui/side-panel.tsx
index f8692ae27d..1fedb7fc29 100644
--- a/web/src/components/ui/side-panel.tsx
+++ b/web/src/components/ui/side-panel.tsx
@@ -1,4 +1,4 @@
-import { useState, type ReactNode } from "react";
+import { useState, useCallback, type ReactNode } from "react";
import { Button } from "@/src/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { SubHeader } from "@/src/components/layouts/header";
@@ -19,47 +19,102 @@ const SidePanelContext = React.createContext<{
showPanel: boolean;
setShowPanel: (value: boolean) => void;
isMobile: boolean;
+ isControlled: boolean;
} | null>(null);
+/**
+ * Side panel component with controlled/uncontrolled modes.
+ *
+ * **Uncontrolled mode** (default):
+ * - Omit `openState` prop
+ * - Panel state persisted in session storage
+ * - User can toggle via chevron button
+ * - Example: `<SidePanel id="details">{content}</SidePanel>`
+ *
+ * **Controlled mode**:
+ * - Provide `openState` with `open` and `onOpenChange`
+ * - No session storage, no toggle button
+ * - Parent controls open/close state
+ * - Example: `<SidePanel id="annotate" openState={{ open: isOpen, onOpenChange: setIsOpen }}>{content}</SidePanel>`
+ */
const SidePanel = ({
id,
children,
className,
mobileTitle,
scrollable = true,
+ openState,
}: {
id: string;
children: ReactNode;
className?: string;
mobileTitle?: string;
scrollable?: boolean;
+ /** Controlled mode: provide to control panel state externally */
+ openState?: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ };
}) => {
- const [showPanel, setShowPanel] = useSessionStorage<boolean>(
+ const isControlled = openState !== undefined;
+ const controlledOpen = openState?.open;
+ const onOpenChange = openState?.onOpenChange;
+ const [uncontrolledOpen, setUncontrolledOpen] = useSessionStorage<boolean>(
`${id}-showPanel`,
true,
);
- const [isOpen, setIsOpen] = useState(false);
+ const [mobileSheetOpen, setMobileSheetOpen] = useState(false);
const isMobile = useIsMobile();
+ const showPanel = isControlled ? (controlledOpen ?? false) : uncontrolledOpen;
+
+ const setShowPanel = useCallback(
+ (value: boolean) => {
+ if (isControlled) {
+ onOpenChange?.(value);
+ } else {
+ setUncontrolledOpen(value);
+ }
+ },
+ [isControlled, onOpenChange, setUncontrolledOpen],
+ );
+
+ const handleMobileOpenChange = useCallback(
+ (open: boolean) => {
+ if (isControlled) {
+ onOpenChange?.(open);
+ } else {
+ setMobileSheetOpen(open);
+ }
+ },
+ [isControlled, onOpenChange],
+ );
+
const contextValue = React.useMemo(
() => ({
showPanel,
setShowPanel,
isMobile,
+ isControlled,
}),
- [showPanel, setShowPanel, isMobile],
+ [showPanel, setShowPanel, isMobile, isControlled],
);
if (isMobile) {
return (
- <Sheet open={isOpen} onOpenChange={setIsOpen}>
- <div className="border-l px-1 pt-2">
- <SheetTrigger asChild>
- <Button variant="ghost" size="icon" className="h-8 w-8">
- <ChevronLeft className="h-4 w-4" />
- </Button>
- </SheetTrigger>
- </div>
+ <Sheet
+ open={isControlled ? showPanel : mobileSheetOpen}
+ onOpenChange={handleMobileOpenChange}
+ >
+ {!isControlled && (
+ <div className="border-l px-1 pt-2">
+ <SheetTrigger asChild>
+ <Button variant="ghost" size="icon" className="h-8 w-8">
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ </SheetTrigger>
+ </div>
+ )}
<SheetContent>
<SheetHeader>
<SheetTitle>{mobileTitle}</SheetTitle>
@@ -85,7 +140,6 @@ const SidePanel = ({
<div
className={cn(
"flex h-full w-full flex-col gap-2",
- showPanel ? "p-2" : "p-1 pr-2 pt-2",
scrollable ? "overflow-y-auto" : "overflow-hidden",
)}
>
@@ -100,10 +154,20 @@ const SidePanel = ({
const SidePanelHeader = ({ children }: { children: ReactNode }) => {
const context = React.useContext(SidePanelContext);
- // Don't throw if we're in mobile mode (no context)
if (!context) return null;
- const { showPanel, setShowPanel } = context;
+ const { showPanel, setShowPanel, isControlled } = context;
+
+ if (isControlled) {
+ if (!showPanel) return null;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-row items-center gap-1">{children}</div>
+ <Separator />
+ </div>
+ );
+ }
if (!showPanel) {
return (
@@ -120,7 +184,7 @@ const SidePanelHeader = ({ children }: { children: ReactNode }) => {
return (
<div className="flex flex-col gap-2">
- <div className="flex h-fit w-full flex-row items-center justify-between gap-2">
+ <div className="flex h-fit w-full flex-row items-center justify-between p-2 pb-0">
<div className="flex flex-row items-center gap-1">{children}</div>
<Button
variant="outline"
diff --git a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
index 45bb216839..3c3a9ab113 100644
--- a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
@@ -62,14 +62,14 @@ export const TraceAnnotationProcessor: React.FC<
<TracePreview
key={data.id}
trace={data}
- scores={data.scores}
+ serverScores={data.scores}
observations={data.observations}
viewType="focused"
/>
) : (
<ObservationPreview
observations={data.observations}
- scores={data.scores}
+ serverScores={data.scores}
projectId={item.projectId}
currentObservationId={item.objectId}
traceId={traceId}
diff --git a/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx b/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx
index b99922cccb..bb220e90f5 100644
--- a/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx
+++ b/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx
@@ -5,7 +5,6 @@ import {
ResizablePanelGroup,
} from "@/src/components/ui/resizable";
import useSessionStorage from "@/src/components/useSessionStorage";
-import { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";
import { type ScoreTarget } from "@/src/features/scores/types";
import {
type AnnotationQueueItem,
@@ -15,8 +14,8 @@ import {
} from "@langfuse/shared";
import { TriangleAlertIcon } from "lucide-react";
import { useSession } from "next-auth/react";
-import { useMemo, useState } from "react";
import { CommentsSection } from "./CommentsSection";
+import { AnnotationForm } from "@/src/features/scores/components/AnnotationForm";
interface AnnotationDrawerSectionProps {
item: AnnotationQueueItem & {
@@ -41,7 +40,6 @@ export const AnnotationDrawerSection: React.FC<
onHasCommentDraftChange,
}) => {
const session = useSession();
- const [showSaving, setShowSaving] = useState(false);
const [verticalSize, setVerticalSize] = useSessionStorage(
`annotationQueueDrawerVertical-${item.projectId}`,
60,
@@ -49,14 +47,6 @@ export const AnnotationDrawerSection: React.FC<
const isLockedByOtherUser = item.lockedByUserId !== session.data?.user?.id;
- const emptySelectedConfigIds = useMemo(() => {
- return configs.map((c) => c.id);
- }, [configs]);
-
- const handleSavingChange = (saving: boolean) => {
- setShowSaving(saving);
- };
-
return (
<Card className="col-span-2 flex h-full flex-col overflow-hidden">
<ResizablePanelGroup
@@ -64,27 +54,24 @@ export const AnnotationDrawerSection: React.FC<
onLayout={(sizes) => setVerticalSize(sizes[0])}
>
<ResizablePanel
- className="w-full overflow-y-auto"
+ className="w-full overflow-y-auto p-3"
minSize={30}
defaultSize={verticalSize}
>
- <AnnotateDrawerContent
+ <AnnotationForm
key={"annotation-drawer-content" + item.objectId}
scoreTarget={scoreTarget}
- scores={scores}
- configs={configs}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={() => {}}
- projectId={item.projectId}
+ serverScores={scores}
+ configSelection={{ mode: "fixed", configs }}
+ scoreMetadata={{
+ projectId: item.projectId,
+ queueId: item.queueId,
+ environment,
+ }}
analyticsData={{
type: scoreTarget.type,
source: "AnnotationQueue",
}}
- isSelectHidden
- queueId={item.queueId}
- showSaving={showSaving}
- setShowSaving={handleSavingChange}
- environment={environment}
actionButtons={
isLockedByOtherUser && isPresent(item.lockedByUser?.name) ? (
<div className="flex items-center justify-center rounded-sm border border-dark-red bg-light-red p-1">
@@ -95,7 +82,6 @@ export const AnnotationDrawerSection: React.FC<
</div>
) : undefined
}
- isDrawerOpen={true}
/>
</ResizablePanel>
<ResizableHandle withHandle />
diff --git a/web/src/features/datasets/components/AnnotationPanel.tsx b/web/src/features/datasets/components/AnnotationPanel.tsx
new file mode 100644
index 0000000000..12c167a92c
--- /dev/null
+++ b/web/src/features/datasets/components/AnnotationPanel.tsx
@@ -0,0 +1,90 @@
+import { Button } from "@/src/components/ui/button";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@/src/components/ui/resizable";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import { CommentsSection } from "@/src/features/annotation-queues/components/shared/CommentsSection";
+import { useActiveCell } from "@/src/features/datasets/contexts/ActiveCellContext";
+import { AnnotationForm } from "@/src/features/scores/components/AnnotationForm";
+import { ChevronRight } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+
+export const AnnotationPanel = ({ projectId }: { projectId: string }) => {
+ const [hasCommentDraft, setHasCommentDraft] = useState(false);
+ const { activeCell, clearActiveCell } = useActiveCell();
+
+ const [verticalSize, setVerticalSize] = useSessionStorage(
+ `annotationQueueDrawerVertical-compare-${projectId}`,
+ 60,
+ );
+
+ if (!activeCell) {
+ return <Skeleton className="h-full w-full" />;
+ }
+
+ return (
+ <ResizablePanelGroup
+ direction="vertical"
+ onLayout={(sizes) => setVerticalSize(sizes[0])}
+ className="h-full"
+ >
+ <ResizablePanel
+ className="w-full overflow-y-auto p-2"
+ minSize={30}
+ defaultSize={verticalSize}
+ >
+ {activeCell ? (
+ <AnnotationForm
+ key={`annotation-drawer-content-${activeCell.traceId}-${activeCell.observationId}`}
+ scoreTarget={{
+ type: "trace",
+ traceId: activeCell.traceId,
+ observationId: activeCell.observationId,
+ }}
+ serverScores={activeCell.scoreAggregates}
+ analyticsData={{
+ type: "trace",
+ source: "DatasetCompare",
+ }}
+ scoreMetadata={{
+ projectId,
+ environment: activeCell.environment,
+ }}
+ actionButtons={
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => {
+ if (hasCommentDraft)
+ toast.error(
+ "Please save or discard your comment before proceeding",
+ );
+ else clearActiveCell();
+ }}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ }
+ />
+ ) : (
+ <Skeleton className="h-full w-full" />
+ )}
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <ResizablePanel className="overflow-y-auto" minSize={20}>
+ <CommentsSection
+ projectId={projectId}
+ objectId={activeCell.observationId ?? activeCell.traceId}
+ objectType={activeCell.observationId ? "OBSERVATION" : "TRACE"}
+ onDraftChange={(draft) => {
+ setHasCommentDraft(draft);
+ }}
+ />
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
index c881a7e3e0..a22b946f43 100644
--- a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
+++ b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx
@@ -1,6 +1,7 @@
import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
-import { IOTableCell } from "@/src/components/ui/IOTableCell";
+import { MemoizedIOTableCell } from "@/src/components/ui/IOTableCell";
+import { useActiveCell } from "@/src/features/datasets/contexts/ActiveCellContext";
import { useDatasetCompareFields } from "@/src/features/datasets/contexts/DatasetCompareFieldsContext";
import { api } from "@/src/utils/api";
import { formatIntervalSeconds } from "@/src/utils/dates";
@@ -11,18 +12,38 @@ import { type EnrichedDatasetRunItem } from "@langfuse/shared/src/server";
import { ScoreRow } from "@/src/features/scores/components/ScoreRow";
import { type ScoreColumn } from "@/src/features/scores/types";
import { useRouter } from "next/router";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { useMergedAggregates } from "@/src/features/scores/lib/useMergedAggregates";
+import { useMergeScoreColumns } from "@/src/features/scores/lib/mergeScoreColumns";
const DatasetAggregateCell = ({
value,
projectId,
- scoreColumns,
+ serverScoreColumns,
}: {
projectId: string;
value: EnrichedDatasetRunItem;
- scoreColumns: ScoreColumn[];
+ serverScoreColumns: ScoreColumn[];
}) => {
const { selectedFields } = useDatasetCompareFields();
+ const { activeCell, setActiveCell } = useActiveCell();
const router = useRouter();
+
+ const hasAnnotationWriteAccess = useHasProjectAccess({
+ projectId,
+ scope: "scores:CUD",
+ });
+
+ // Merge cached score writes into aggregates for optimistic display
+ const displayScores = useMergedAggregates(
+ value.scores,
+ value.trace.id,
+ value.observation?.id,
+ );
+
+ // Merge server columns with cache-only columns
+ const mergedScoreColumns = useMergeScoreColumns(serverScoreColumns);
+
// conditionally fetch the trace or observation depending on the presence of observationId
const trace = api.traces.byId.useQuery(
{ traceId: value.trace.id, projectId },
@@ -89,30 +110,56 @@ const DatasetAggregateCell = ({
);
};
+ const handleOpenReview = () => {
+ setActiveCell({
+ traceId: value.trace.id,
+ observationId: value.observation?.id,
+ scoreAggregates: displayScores,
+ environment: data?.environment,
+ });
+ };
+
+ const isActiveCell =
+ activeCell?.traceId === value.trace.id &&
+ activeCell?.observationId === value.observation?.id;
+
return (
<div
className={cn(
"group relative flex h-full w-full flex-col gap-2 overflow-hidden",
+ isActiveCell &&
+ "rounded-md p-1 ring-2 ring-inset ring-accent-dark-blue",
)}
>
- {/* Triggers peek view */}
- <Button
- variant="outline"
- size="icon"
- className="absolute bottom-2 right-2 z-10 h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100"
- title="View trace/observation"
- onClick={handleOpenPeek}
- >
- <ListTree className="h-3 w-3" />
- </Button>
+ <div className="absolute bottom-2 right-2 z-10 flex flex-row gap-1">
+ {/* Triggers review/annotation */}
+ <Button
+ disabled={!hasAnnotationWriteAccess}
+ variant="outline"
+ className="h-6 px-1 text-xs opacity-0 transition-opacity group-hover:opacity-100"
+ onClick={handleOpenReview}
+ >
+ Annotate
+ </Button>
+ {/* Triggers peek view */}
+ <Button
+ variant="outline"
+ size="icon"
+ className="h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100"
+ title="View trace/observation"
+ onClick={handleOpenPeek}
+ >
+ <ListTree className="h-3 w-3" />
+ </Button>
+ </div>
{/* Displays trace/observation output */}
<div
className={cn(
- "relative max-h-[50%] w-full min-w-0 overflow-auto",
+ "relative h-[50%] w-full min-w-0 flex-shrink-0 overflow-auto",
!selectedFields.includes("output") && "hidden",
)}
>
- <IOTableCell
+ <MemoizedIOTableCell
isLoading={
(!value.observation ? trace.isLoading : observation.isLoading) ||
!data
@@ -126,20 +173,20 @@ const DatasetAggregateCell = ({
{/* Displays scores */}
<div
className={cn(
- "flex max-h-[50%] flex-shrink-0 overflow-hidden px-1",
+ "flex max-h-[50%] flex-shrink overflow-hidden px-1",
!selectedFields.includes("scores") && "hidden",
)}
>
<div className="mt-1 w-full min-w-0 overflow-hidden">
<div className="flex max-h-full w-full flex-wrap gap-1 overflow-y-auto">
- {scoreColumns.length > 0 ? (
- scoreColumns.map((scoreColumn) => (
+ {mergedScoreColumns.length > 0 ? (
+ mergedScoreColumns.map((scoreColumn) => (
<ScoreRow
key={scoreColumn.key}
projectId={projectId}
name={scoreColumn.name}
source={scoreColumn.source}
- aggregate={value.scores[scoreColumn.key] ?? null}
+ aggregate={displayScores[scoreColumn.key] ?? null}
/>
))
) : (
@@ -180,19 +227,19 @@ const DatasetAggregateCell = ({
type DatasetAggregateTableCellProps = {
projectId: string;
value: EnrichedDatasetRunItem;
- scoreColumns: ScoreColumn[];
+ serverScoreColumns: ScoreColumn[];
};
export const DatasetAggregateTableCell = ({
projectId,
value,
- scoreColumns,
+ serverScoreColumns,
}: DatasetAggregateTableCellProps) => {
return (
<DatasetAggregateCell
projectId={projectId}
value={value}
- scoreColumns={scoreColumns}
+ serverScoreColumns={serverScoreColumns}
/>
);
};
diff --git a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
index 8b3f2fb855..46d997f387 100644
--- a/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
+++ b/web/src/features/datasets/components/DatasetRunAggregateColumnHelpers.tsx
@@ -65,19 +65,16 @@ export const constructDatasetRunAggregateColumns = ({
datasetColumns,
updateRunFilters,
getFiltersForRun,
- scoreColumns,
+ serverScoreColumns,
}: {
runAggregateColumnProps: RunAggregateColumnProps[];
projectId: string;
datasetColumns: ColumnDefinition[];
updateRunFilters: (runId: string, filters: FilterState) => void;
getFiltersForRun: (runId: string) => FilterState;
- scoreColumns?: ScoreColumn[];
+ serverScoreColumns?: ScoreColumn[];
}): LangfuseColumnDef<DatasetCompareRunRowData>[] => {
- const isDataLoading = !isScoreColumnsAvailable(scoreColumns);
- const sortedScoreColumns = !isDataLoading
- ? [...scoreColumns].sort((a, b) => a.name.localeCompare(b.name))
- : [];
+ const isDataLoading = !isScoreColumnsAvailable(serverScoreColumns);
return runAggregateColumnProps.map((col) => {
const { id, name, createdAt } = col;
@@ -116,7 +113,7 @@ export const constructDatasetRunAggregateColumns = ({
<DatasetAggregateTableCell
value={value}
projectId={projectId}
- scoreColumns={sortedScoreColumns}
+ serverScoreColumns={serverScoreColumns}
/>
);
},
diff --git a/web/src/features/datasets/contexts/ActiveCellContext.tsx b/web/src/features/datasets/contexts/ActiveCellContext.tsx
new file mode 100644
index 0000000000..429f7c3904
--- /dev/null
+++ b/web/src/features/datasets/contexts/ActiveCellContext.tsx
@@ -0,0 +1,63 @@
+import { type ScoreAggregate } from "@langfuse/shared";
+import {
+ createContext,
+ useContext,
+ useState,
+ useCallback,
+ useMemo,
+ type ReactNode,
+} from "react";
+
+type ActiveCell = {
+ traceId: string;
+ observationId?: string;
+ scoreAggregates: ScoreAggregate;
+ environment?: string;
+};
+
+type ActiveCellContextValue = {
+ activeCell: ActiveCell | null;
+ setActiveCell: (cell: ActiveCell | null) => void;
+ clearActiveCell: () => void;
+};
+
+/**
+ * Tracks active dataset run item cell for annotation UI.
+ *
+ * Single cell can be active at a time. Used for cell highlighting
+ * and side panel state management.
+ */
+const ActiveCellContext = createContext<ActiveCellContextValue | undefined>(
+ undefined,
+);
+
+export function ActiveCellProvider({ children }: { children: ReactNode }) {
+ const [activeCell, setActiveCellState] = useState<ActiveCell | null>(null);
+
+ const setActiveCell = useCallback((cell: ActiveCell | null) => {
+ setActiveCellState(cell);
+ }, []);
+
+ const clearActiveCell = useCallback(() => {
+ setActiveCellState(null);
+ }, []);
+
+ const value = useMemo(
+ () => ({ activeCell, setActiveCell, clearActiveCell }),
+ [activeCell, setActiveCell, clearActiveCell],
+ );
+
+ return (
+ <ActiveCellContext.Provider value={value}>
+ {children}
+ </ActiveCellContext.Provider>
+ );
+}
+
+export function useActiveCell() {
+ const context = useContext(ActiveCellContext);
+ if (!context) {
+ throw new Error("useActiveCell must be used within ActiveCellProvider");
+ }
+ return context;
+}
diff --git a/web/src/features/datasets/hooks/useDatasetRunAggregateColumns.ts b/web/src/features/datasets/hooks/useDatasetRunAggregateColumns.ts
index a0bcea8dac..d41fcc11dc 100644
--- a/web/src/features/datasets/hooks/useDatasetRunAggregateColumns.ts
+++ b/web/src/features/datasets/hooks/useDatasetRunAggregateColumns.ts
@@ -73,15 +73,13 @@ export function useDatasetRunAggregateColumns({
runAggregateColumnProps,
projectId,
datasetColumns,
- scoreColumns:
- runIds.length > 0 ? scoreKeysAndProps.data?.scoreColumns : [],
+ serverScoreColumns: scoreKeysAndProps.data?.scoreColumns,
updateRunFilters,
getFiltersForRun,
});
}, [
runAggregateColumnProps,
projectId,
- runIds,
datasetColumns,
scoreKeysAndProps.data?.scoreColumns,
updateRunFilters,
diff --git a/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx b/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx
index 9948d6f9a0..67528f7098 100644
--- a/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx
+++ b/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx
@@ -8,8 +8,8 @@ import {
import React from "react";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import useLocalStorage from "@/src/components/useLocalStorage";
import { api } from "@/src/utils/api";
+import { useEmptyScoreConfigs } from "@/src/features/scores/hooks/useEmptyConfigs";
export const ArchiveScoreConfigButton = ({
configId,
@@ -23,9 +23,8 @@ export const ArchiveScoreConfigButton = ({
name: string;
}) => {
const capture = usePostHogClientCapture();
- const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
- string[]
- >("emptySelectedConfigIds", []);
+ const { emptySelectedConfigIds, setEmptySelectedConfigIds } =
+ useEmptyScoreConfigs();
const hasAccess = useHasProjectAccess({
projectId: projectId,
diff --git a/web/src/features/scores/components/AnnotateDrawer.tsx b/web/src/features/scores/components/AnnotateDrawer.tsx
index 0f6939a77c..e5afed71c4 100644
--- a/web/src/features/scores/components/AnnotateDrawer.tsx
+++ b/web/src/features/scores/components/AnnotateDrawer.tsx
@@ -1,174 +1,65 @@
-import React, { useState, useEffect } from "react";
+import React from "react";
import { Button } from "@/src/components/ui/button";
-import { LockIcon, SquarePen, LoaderCircle } from "lucide-react";
+import { LockIcon, SquarePen } from "lucide-react";
import {
Drawer,
DrawerContent,
- DrawerHeader,
- DrawerTitle,
DrawerTrigger,
} from "@/src/components/ui/drawer";
-import { api } from "@/src/utils/api";
-import Header from "@/src/components/layouts/header";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";
-import { useIsMutating } from "@tanstack/react-query";
-import { z } from "zod/v4";
import { type AnnotateDrawerProps } from "@/src/features/scores/types";
import { type ScoreTarget } from "@/src/features/scores/types";
-import { formatAnnotateDescription } from "@/src/features/scores/lib/helpers";
-
-const mutationKeySchema = z.array(z.array(z.string()));
+import { AnnotationForm } from "@/src/features/scores/components/AnnotationForm";
export function AnnotateDrawer<Target extends ScoreTarget>({
+ projectId,
scoreTarget,
scores,
- emptySelectedConfigIds,
- setEmptySelectedConfigIds,
- projectId,
analyticsData = {
type: "trace",
source: "TraceDetail",
},
- variant = "button",
+ scoreMetadata,
buttonVariant = "secondary",
- hasGroupedButton = false,
- environment,
}: AnnotateDrawerProps<Target>) {
- const [isDrawerOpen, setIsDrawerOpen] = useState(false);
- const [showSaving, setShowSaving] = useState(false);
const capture = usePostHogClientCapture();
const hasAccess = useHasProjectAccess({
projectId,
scope: "scores:CUD",
});
- const description = formatAnnotateDescription(scoreTarget);
-
- const configsData = api.scoreConfigs.all.useQuery(
- {
- projectId,
- },
- {
- enabled: hasAccess && isDrawerOpen,
- },
- );
-
- const configs = configsData.data?.configs ?? [];
-
- // Validate if any of the scores mutations are in progress
- const isMutating = useIsMutating({
- predicate: (mutation) => {
- const mutationKey = mutation.options.mutationKey;
-
- const parsedMutationKey = mutationKeySchema.safeParse(mutationKey);
- if (!parsedMutationKey.success) return false;
-
- for (const key of parsedMutationKey.data) {
- const parsedKey = key.join(".");
- if (parsedKey === "scores.createAnnotationScore") return true;
- if (parsedKey === "scores.updateAnnotationScore") return true;
- if (parsedKey === "scores.deleteAnnotationScore") return true;
- }
-
- return false;
- },
- });
-
- useEffect(() => {
- if (isMutating > 0) {
- setShowSaving(true);
- } else {
- // Add delay before setting showSaving to ensure loading state persists for a short time after the mutation key indicates completion, allowing for any pending operations to finish
- const timer = setTimeout(() => {
- setShowSaving(false);
- }, 500); // 500ms delay
-
- return () => clearTimeout(timer);
- }
- }, [isMutating]);
-
- if (!hasAccess && variant === "badge") return null;
return (
- <Drawer onClose={() => setIsDrawerOpen(false)}>
+ <Drawer>
<DrawerTrigger asChild>
- {variant === "button" ? (
- <Button
- variant={buttonVariant}
- disabled={!hasAccess || showSaving}
- className={hasGroupedButton ? "rounded-r-none" : ""}
- onClick={() => {
- setIsDrawerOpen(true);
- capture(
- Boolean(scores.length)
- ? "score:update_form_open"
- : "score:create_form_open",
- analyticsData,
- );
- }}
- >
- {!hasAccess ? (
- <LockIcon className="mr-1.5 h-3 w-3" />
- ) : showSaving ? (
- <LoaderCircle className="mr-1.5 h-4 w-4 animate-spin text-muted-foreground" />
- ) : (
- <SquarePen className="mr-1.5 h-4 w-4" />
- )}
- <span>Annotate</span>
- </Button>
- ) : (
- <Button
- className="h-6 rounded-full px-3 text-xs"
- disabled={!hasAccess || showSaving}
- onClick={() => {
- setIsDrawerOpen(true);
- capture(
- Boolean(scores.length)
- ? "score:update_form_open"
- : "score:create_form_open",
- analyticsData,
- );
- }}
- >
- Annotate
- </Button>
- )}
+ <Button
+ variant={buttonVariant}
+ disabled={!hasAccess}
+ className="rounded-r-none"
+ onClick={() => {
+ capture(
+ Boolean(scores.length)
+ ? "score:update_form_open"
+ : "score:create_form_open",
+ analyticsData,
+ );
+ }}
+ >
+ {!hasAccess ? (
+ <LockIcon className="mr-1.5 h-3 w-3" />
+ ) : (
+ <SquarePen className="mr-1.5 h-4 w-4" />
+ )}
+ <span>Annotate</span>
+ </Button>
</DrawerTrigger>
- <DrawerContent>
- {configsData.isLoading ? (
- <DrawerHeader className="sticky top-0 z-10 rounded-sm bg-background">
- <DrawerTitle>
- <Header
- title="Annotate"
- help={{
- description,
- href: "https://langfuse.com/docs/evaluation/evaluation-methods/annotation",
- }}
- ></Header>
- </DrawerTitle>
- <div className="flex min-h-[9rem] items-center justify-center rounded border border-dashed p-2">
- <LoaderCircle className="mr-1.5 h-4 w-4 animate-spin text-muted-foreground" />
- <span className="text-xs text-muted-foreground opacity-60">
- Loading annotation data...
- </span>
- </div>
- </DrawerHeader>
- ) : (
- <AnnotateDrawerContent
- scores={scores}
- scoreTarget={scoreTarget}
- configs={configs}
- emptySelectedConfigIds={emptySelectedConfigIds}
- setEmptySelectedConfigIds={setEmptySelectedConfigIds}
- projectId={projectId}
- analyticsData={analyticsData}
- showSaving={showSaving}
- setShowSaving={setShowSaving}
- isDrawerOpen={isDrawerOpen}
- environment={environment}
- />
- )}
+ <DrawerContent className="p-3">
+ <AnnotationForm
+ serverScores={scores}
+ scoreTarget={scoreTarget}
+ analyticsData={analyticsData}
+ scoreMetadata={scoreMetadata}
+ />
</DrawerContent>
</Drawer>
);
diff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsx
deleted file mode 100644
index 7e9febdead..0000000000
--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx
+++ /dev/null
@@ -1,1146 +0,0 @@
-import React, { useEffect, useRef } from "react";
-import { Button } from "@/src/components/ui/button";
-import {
- MessageCircleMore,
- MessageCircle,
- X,
- Archive,
- Loader2,
- Check,
-} from "lucide-react";
-import {
- type ControllerRenderProps,
- useFieldArray,
- useForm,
- type ErrorOption,
-} from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/src/components/ui/form";
-import { DrawerHeader, DrawerTitle } from "@/src/components/ui/drawer";
-import {
- type APIScoreV2,
- isPresent,
- CreateAnnotationScoreData,
- UpdateAnnotationScoreData,
- type ScoreConfigDomain,
- type ScoreConfigCategoryDomain,
-} from "@langfuse/shared";
-import { Input } from "@/src/components/ui/input";
-import {
- Popover,
- PopoverClose,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-import { Textarea } from "@/src/components/ui/textarea";
-import { HoverCardContent } from "@radix-ui/react-hover-card";
-import { HoverCard, HoverCardTrigger } from "@/src/components/ui/hover-card";
-import {
- formatAnnotateDescription,
- isNumericDataType,
- isScoreUnsaved,
-} from "@/src/features/scores/lib/helpers";
-import { getDefaultAnnotationScoreData } from "@/src/features/scores/lib/getDefaultScoreData";
-import { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";
-import Header from "@/src/components/layouts/header";
-import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
-import { useRouter } from "next/router";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { cn } from "@/src/utils/tailwind";
-import { getScoreDataTypeIcon } from "@/src/features/scores/lib/scoreColumns";
-import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";
-import {
- type ScoreTarget,
- type AnnotateDrawerProps,
- type AnnotateFormSchemaType,
- type AnnotationScoreSchemaType,
-} from "@/src/features/scores/types";
-import { useScoreValues } from "@/src/features/scores/hooks/useScoreValues";
-import { useScoreMutations } from "@/src/features/scores/hooks/useScoreMutations";
-import { AnnotateFormSchema } from "@/src/features/scores/schema";
-import { ScoreConfigDetails } from "@/src/features/score-configs/components/ScoreConfigDetails";
-
-const CHAR_CUTOFF = 6;
-
-const renderSelect = (categories: ScoreConfigCategoryDomain[]) => {
- const hasMoreThanThreeCategories = categories.length > 3;
- const hasLongCategoryNames = categories.some(
- ({ label }) => label.length > CHAR_CUTOFF,
- );
-
- return (
- hasMoreThanThreeCategories ||
- (categories.length > 1 && hasLongCategoryNames)
- );
-};
-
-const getFormError = ({
- value,
- minValue,
- maxValue,
-}: {
- value?: number | null;
- minValue?: number | null;
- maxValue?: number | null;
-}): ErrorOption | null => {
- if (
- (isPresent(maxValue) && Number(value) > maxValue) ||
- (isPresent(minValue) && Number(value) < minValue)
- ) {
- return {
- type: "custom",
- message: `Not in range: [${minValue ?? "-∞"},${maxValue ?? "∞"}]`,
- };
- }
- return null;
-};
-
-function handleOnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
- if (e.key === "Enter") {
- e.preventDefault();
- const form = e.currentTarget.form;
- if (!form) return;
-
- const currentTabIndex = e.currentTarget.tabIndex;
- const nextElement = form.querySelector(
- `[tabindex="${currentTabIndex + 1}"]`,
- );
-
- if (nextElement instanceof HTMLElement) {
- nextElement.focus();
- } else {
- e.currentTarget.blur();
- }
- }
-}
-
-function enrichCategories(
- categories: ScoreConfigCategoryDomain[],
- currentStringValue?: string | null,
-) {
- if (categories.length === 0) return [];
-
- const enrichedCategories = categories.map((category) => ({
- ...category,
- isOutdated: false,
- }));
-
- if (!currentStringValue) return enrichedCategories;
-
- // If current value exists in categories, return as-is
- if (categories.some((category) => category.label === currentStringValue)) {
- return enrichedCategories;
- }
-
- return [
- {
- label: currentStringValue,
- value: 0,
- isOutdated: true,
- },
- ...enrichedCategories,
- ];
-}
-
-function AnnotateHeader({
- showSaving,
- actionButtons,
- description,
-}: {
- showSaving: boolean;
- actionButtons: React.ReactNode;
- description: string;
-}) {
- return (
- <Header
- title="Annotate"
- help={{
- description,
- href: "https://langfuse.com/docs/evaluation/evaluation-methods/annotation",
- className: "leading-relaxed",
- }}
- actionButtons={[
- <div className="flex items-center justify-end" key="saving-spinner">
- <div className="mr-1 items-center justify-center">
- {showSaving ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Check className="h-3 w-3" />
- )}
- </div>
- <span className="text-xs text-muted-foreground">
- {showSaving ? "Saving score data" : "Score data saved"}
- </span>
- </div>,
- actionButtons,
- ]}
- />
- );
-}
-
-type AnnotateDrawerContentProps<Target extends ScoreTarget> =
- AnnotateDrawerProps<Target> & {
- configs: ScoreConfigDomain[];
- isDrawerOpen: boolean;
- showSaving: boolean;
- setShowSaving: (showSaving: boolean) => void;
- isSelectHidden?: boolean;
- queueId?: string;
- actionButtons?: React.ReactNode;
- };
-
-export function AnnotateDrawerContent<Target extends ScoreTarget>({
- scoreTarget,
- scores,
- configs,
- analyticsData,
- emptySelectedConfigIds,
- setEmptySelectedConfigIds,
- projectId,
- showSaving,
- setShowSaving,
- isDrawerOpen = true,
- isSelectHidden = false,
- queueId,
- actionButtons,
- environment,
-}: AnnotateDrawerContentProps<Target>) {
- const capture = usePostHogClientCapture();
- const router = useRouter();
-
- const form = useForm({
- resolver: zodResolver(AnnotateFormSchema),
- defaultValues: {
- scoreData: getDefaultAnnotationScoreData({
- scores,
- emptySelectedConfigIds,
- configs,
- scoreTarget,
- }),
- },
- });
-
- const { fields, remove, update, replace } = useFieldArray({
- control: form.control,
- name: "scoreData",
- });
-
- const prevEmptySelectedConfigIdsRef = useRef(emptySelectedConfigIds);
-
- const { optimisticScores, setOptimisticScore } = useScoreValues({
- getValues: form.getValues,
- });
-
- const { createMutation, updateMutation, deleteMutation } = useScoreMutations(
- scoreTarget,
- projectId,
- fields,
- update,
- remove,
- configs,
- isDrawerOpen,
- setShowSaving,
- );
-
- useEffect(() => {
- // Only reset the form if emptySelectedConfigIds has changed, compare by value not reference
- if (
- prevEmptySelectedConfigIdsRef.current.length !==
- emptySelectedConfigIds.length ||
- !prevEmptySelectedConfigIdsRef.current.every(
- (id, index) => id === emptySelectedConfigIds[index],
- )
- ) {
- form.reset({
- scoreData: getDefaultAnnotationScoreData({
- scores,
- emptySelectedConfigIds,
- configs,
- scoreTarget,
- }),
- });
- }
-
- prevEmptySelectedConfigIdsRef.current = emptySelectedConfigIds;
- }, [emptySelectedConfigIds, scores, configs, scoreTarget, form]);
-
- const pendingCreates = useRef(new Map<number, Promise<APIScoreV2>>());
- const pendingDeletes = useRef(new Set<string>());
- // Track when deletion was initiated for each score ID
- const deletionTimestamps = useRef(new Map<string, number>());
- const description = formatAnnotateDescription(scoreTarget);
-
- async function handleScoreChange(
- score: AnnotationScoreSchemaType,
- index: number,
- value: number,
- stringValue: string | null,
- ) {
- // Check if this score is currently being deleted
- if (score.scoreId && pendingDeletes.current.has(score.scoreId)) {
- // Skip updates for scores that are being deleted
- return;
- }
-
- // Check if there was a recent deletion request for this score
- if (score.scoreId && deletionTimestamps.current.has(score.scoreId)) {
- const deleteTime = deletionTimestamps.current.get(score.scoreId) || 0;
- const now = Date.now();
- // If deletion was requested in the last 5 seconds, ignore updates
- if (now - deleteTime < 5000) {
- return;
- }
- // Otherwise clear the old timestamp
- deletionTimestamps.current.delete(score.scoreId);
- }
-
- // Optimistically update the UI
- setOptimisticScore({
- index,
- value,
- stringValue,
- });
-
- try {
- // If we have an ID, straightforward update
- if (!!score.scoreId) {
- const validatedScore = UpdateAnnotationScoreData.parse({
- id: score.scoreId,
- projectId,
- scoreTarget,
- name: score.name,
- dataType: score.dataType,
- configId: score.configId,
- stringValue: stringValue ?? score.stringValue,
- comment: score.comment,
- value,
- queueId,
- environment,
- });
-
- await updateMutation.mutateAsync({
- ...validatedScore,
- });
-
- capture("score:update", {
- ...analyticsData,
- dataType: score.dataType,
- });
- } else {
- const pendingCreate = pendingCreates.current.get(index);
-
- if (pendingCreate) {
- // Wait for the pending create to complete to get the ID
- const createdScore = await pendingCreate;
- const validatedScore = UpdateAnnotationScoreData.parse({
- id: createdScore.id,
- projectId,
- scoreTarget,
- name: score.name,
- dataType: score.dataType,
- configId: score.configId,
- stringValue: stringValue ?? score.stringValue,
- comment: score.comment,
- value,
- queueId,
- environment,
- });
-
- await updateMutation.mutateAsync({
- ...validatedScore,
- });
-
- capture("score:update", {
- ...analyticsData,
- dataType: score.dataType,
- });
- } else {
- // If no pending create, straightforward create
- const validatedScore = CreateAnnotationScoreData.parse({
- projectId,
- scoreTarget,
- name: score.name,
- dataType: score.dataType,
- configId: score.configId,
- stringValue: stringValue ?? score.stringValue,
- comment: score.comment,
- value,
- queueId,
- environment,
- });
-
- const createPromise = createMutation.mutateAsync({
- ...validatedScore,
- });
-
- capture("score:create", {
- ...analyticsData,
- dataType: score.dataType,
- });
-
- pendingCreates.current.set(index, createPromise);
-
- // Wait for creation and cleanup
- const createdScore = await createPromise;
- pendingCreates.current.delete(index);
-
- // Update the form with the new ID
- update(index, {
- ...score,
- scoreId: createdScore.id,
- value: createdScore.value,
- stringValue: createdScore.stringValue ?? undefined,
- });
- }
- }
- } catch (error) {
- // Handle error and revert optimistic update
- console.error(error);
- setOptimisticScore({
- index,
- value: score.value ?? null,
- stringValue: score.stringValue ?? null,
- });
- }
- }
-
- function handleOnBlur({
- config,
- field,
- index,
- score,
- }: {
- config: ScoreConfigDomain;
- field: ControllerRenderProps<
- AnnotateFormSchemaType,
- `scoreData.${number}.value`
- >;
- index: number;
- score: AnnotationScoreSchemaType;
- }): React.FocusEventHandler<HTMLInputElement> | undefined {
- return async () => {
- const { maxValue, minValue, dataType } = config;
-
- if (isNumericDataType(dataType)) {
- const formError = getFormError({
- value: field.value,
- maxValue,
- minValue,
- });
- if (!!formError) {
- form.setError(`scoreData.${index}.value`, formError);
- return;
- }
- }
-
- form.clearErrors(`scoreData.${index}.value`);
-
- if (isPresent(field.value)) {
- await handleScoreChange(score, index, Number(field.value), null);
- }
- };
- }
-
- useEffect(() => {
- if (
- updateMutation.isPending ||
- createMutation.isPending ||
- deleteMutation.isPending
- ) {
- setShowSaving(true);
- } else {
- setShowSaving(false);
- }
- }, [
- updateMutation.isPending,
- createMutation.isPending,
- deleteMutation.isPending,
- setShowSaving,
- ]);
-
- function handleOnCheckedChange(
- values: Record<string, string>[],
- changedValueId?: string,
- ) {
- if (values.length === 0) {
- const populatedScoreFields = fields.filter(({ scoreId }) => !!scoreId);
- replace(populatedScoreFields);
- setEmptySelectedConfigIds(
- populatedScoreFields
- .filter(({ configId }) => !!configId)
- .map(({ configId }) => configId as string),
- );
- return;
- }
- if (!changedValueId) return;
-
- const configToChange = configs.find(({ id }) => id === changedValueId);
- if (!configToChange) return;
- const { id, name, dataType } = configToChange;
-
- const index = fields.findIndex(({ configId }) => configId === id);
-
- if (index === -1) {
- setOptimisticScore({
- index: fields.length,
- value: null,
- stringValue: null,
- scoreId: null,
- name,
- dataType,
- configId: id,
- });
- replace([
- ...fields,
- {
- name,
- dataType,
- configId: id,
- },
- ]);
- setEmptySelectedConfigIds([...emptySelectedConfigIds, changedValueId]);
- } else {
- remove(index);
- setEmptySelectedConfigIds(
- emptySelectedConfigIds.filter((id) => id !== changedValueId),
- );
- }
- }
-
- function handleOnValueChange(
- score: AnnotationScoreSchemaType,
- index: number,
- configCategories: ScoreConfigCategoryDomain[],
- ): ((value: string) => void) | undefined {
- return async (stringValue) => {
- const selectedCategory = configCategories.find(
- ({ label }) => label === stringValue,
- );
- if (selectedCategory) {
- const newValue = Number(selectedCategory.value);
-
- await handleScoreChange(score, index, newValue, stringValue);
- form.setValue(`scoreData.${index}.value`, newValue, {
- shouldValidate: true,
- });
- }
- };
- }
-
- function handleCommentUpdate({
- field,
- score,
- comment,
- }: {
- field: ControllerRenderProps<
- AnnotateFormSchemaType,
- `scoreData.${number}.comment`
- >;
- score: AnnotationScoreSchemaType;
- comment?: string | null;
- }): React.MouseEventHandler<HTMLButtonElement> | undefined {
- return async () => {
- const { value, scoreId } = score;
- if (!!field.value && !!scoreId && isPresent(value)) {
- const validatedScore = UpdateAnnotationScoreData.parse({
- id: scoreId,
- projectId,
- scoreTarget,
- name: score.name,
- dataType: score.dataType,
- configId: score.configId,
- stringValue: score.stringValue,
- value,
- comment,
- queueId,
- environment,
- });
-
- await updateMutation.mutateAsync({
- ...validatedScore,
- });
-
- capture(
- comment ? "score:update_comment" : "score:delete_comment",
- analyticsData,
- );
- }
- };
- }
-
- return (
- <div className="mx-auto w-full overflow-y-auto md:max-h-full">
- <DrawerHeader className="sticky top-0 z-10 rounded-sm bg-background">
- {isSelectHidden ? (
- <AnnotateHeader
- showSaving={showSaving}
- actionButtons={actionButtons}
- description={description}
- />
- ) : (
- <DrawerTitle>
- <AnnotateHeader
- showSaving={showSaving}
- actionButtons={actionButtons}
- description={description}
- />
- </DrawerTitle>
- )}
-
- {!isSelectHidden && (
- <div className="grid grid-flow-col items-center">
- <MultiSelectKeyValues
- placeholder="Value"
- align="end"
- items="empty scores"
- className="grid grid-cols-[auto,1fr,auto,auto] gap-2"
- onValueChange={handleOnCheckedChange}
- options={configs
- .filter(
- (config) =>
- !config.isArchived ||
- fields.find((field) => field.configId === config.id),
- )
- .map((config) => ({
- key: config.id,
- value: `${getScoreDataTypeIcon(config.dataType)} ${config.name}`,
- disabled:
- fields.some(
- (field) =>
- !!field.scoreId && field.configId === config.id,
- ) ||
- optimisticScores.some(
- (score) => score.configId === config.id && !!score.value,
- ) ||
- deleteMutation.isPending,
- isArchived: config.isArchived,
- }))}
- values={fields
- .filter((field) => !!field.configId)
- .map((field) => ({
- value: `${getScoreDataTypeIcon(field.dataType)} ${field.name}`,
- key: field.configId as string,
- }))}
- controlButtons={
- <DropdownMenuItem
- onSelect={() => {
- capture(
- "score_configs:manage_configs_item_click",
- analyticsData,
- );
- router.push(`/project/${projectId}/settings/scores`);
- }}
- >
- Manage score configs
- </DropdownMenuItem>
- }
- />
- </div>
- )}
- </DrawerHeader>
- <Form {...form}>
- <form className="flex flex-col gap-4">
- <div className="grid grid-flow-row gap-2 px-4">
- <FormField
- control={form.control}
- name="scoreData"
- render={() => (
- <>
- {fields.map((score, index) => {
- const config = configs.find(
- (config) => config.id === score.configId,
- );
- if (!config) return null;
- const categories = enrichCategories(
- config.categories ?? [],
- score.stringValue,
- );
-
- return (
- <div
- key={score.id}
- className="grid w-full grid-cols-[1fr,2fr] items-center gap-8 text-left"
- >
- <div className="grid h-full grid-cols-[1fr,auto] items-center">
- {config.description ||
- isPresent(config.maxValue) ||
- isPresent(config.minValue) ? (
- <HoverCard>
- <HoverCardTrigger asChild>
- <span
- className={cn(
- "line-clamp-2 break-words text-xs font-medium underline decoration-muted-gray decoration-dashed underline-offset-2",
- config.isArchived
- ? "text-foreground/40"
- : "",
- )}
- >
- {score.name}
- </span>
- </HoverCardTrigger>
- <HoverCardContent className="z-20 max-h-[60vh] max-w-64 overflow-y-auto rounded border">
- <ScoreConfigDetails config={config} />
- </HoverCardContent>
- </HoverCard>
- ) : (
- <span
- className={cn(
- "line-clamp-2 break-words text-xs font-medium",
- config.isArchived ? "text-foreground/40" : "",
- )}
- title={score.name}
- >
- {score.name}
- </span>
- )}
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="link"
- type="button"
- size="xs"
- title="Add or view score comment"
- className="h-full items-start px-0 pl-1 disabled:text-primary/50 disabled:opacity-100"
- disabled={
- isScoreUnsaved(score.scoreId) ||
- (config.isArchived && !score.comment)
- }
- >
- {score.comment ? (
- <MessageCircleMore className="h-4 w-4" />
- ) : (
- <MessageCircle className="h-4 w-4" />
- )}
- </Button>
- </PopoverTrigger>
- <PopoverContent>
- <FormField
- control={form.control}
- name={`scoreData.${index}.comment`}
- render={({ field }) => (
- <FormItem className="space-y-4">
- <FormLabel className="text-sm">
- Comment (optional)
- </FormLabel>
- {!!field.value &&
- field.value !== score.comment && (
- <HoverCard>
- <HoverCardTrigger asChild>
- <span className="ml-2 mr-2 rounded-sm bg-input p-1 text-xs">
- Draft
- </span>
- </HoverCardTrigger>
- <HoverCardContent side="top">
- {!!score.comment && (
- <div className="mb-4 max-w-48 rounded border bg-background p-2 shadow-sm">
- <p className="text-xs">
- Saved comment:{" "}
- <span className="whitespace-pre-wrap">
- {score.comment}
- </span>
- </p>
- </div>
- )}
- </HoverCardContent>
- </HoverCard>
- )}
- <FormControl>
- <>
- <Textarea
- {...field}
- className="text-xs"
- value={field.value || ""}
- />
- {field.value !== score.comment && (
- <div className="grid w-full grid-cols-[1fr,1fr] gap-2">
- <PopoverClose asChild>
- <Button
- variant="secondary"
- type="button"
- size="sm"
- className="text-xs"
- disabled={!field.value}
- onClick={() => {
- form.setValue(
- `scoreData.${index}.comment`,
- score.comment ?? "",
- );
- }}
- >
- Discard
- </Button>
- </PopoverClose>
- <Button
- type="button"
- size="sm"
- className="text-xs"
- disabled={
- !field.value ||
- config.isArchived
- }
- loading={updateMutation.isPending}
- onClick={handleCommentUpdate({
- field,
- score,
- comment: field.value,
- })}
- >
- Save
- </Button>
- </div>
- )}
- {field.value === score.comment && (
- <div className="flex justify-end">
- <Button
- variant="destructive"
- type="button"
- size="sm"
- className="text-xs"
- disabled={
- !field.value || !score.comment
- }
- loading={updateMutation.isPending}
- onClick={handleCommentUpdate({
- field,
- score,
- comment: null,
- })}
- >
- Delete
- </Button>
- </div>
- )}
- </>
- </FormControl>
- <FormMessage className="text-xs" />
- </FormItem>
- )}
- />
- </PopoverContent>
- </Popover>
- </div>
- <div className="grid grid-cols-[11fr,1fr] items-center py-1">
- <FormField
- control={form.control}
- name={`scoreData.${index}.value`}
- render={({ field }) => (
- <FormItem>
- <FormControl>
- {isNumericDataType(score.dataType) ? (
- <Input
- {...field}
- value={
- optimisticScores[index].value ?? ""
- }
- // manually manage controlled input state
- onChange={(e) => {
- const value = e.target.value;
- const numValue =
- value === "" ? null : Number(value);
- setOptimisticScore({
- index,
- value: numValue,
- stringValue: null,
- scoreId: null,
- });
- field.onChange(numValue);
- }}
- type="number"
- className="text-xs"
- disabled={config.isArchived}
- onBlur={handleOnBlur({
- config,
- field,
- index,
- score,
- })}
- onKeyDown={handleOnKeyDown}
- onKeyUp={() => {
- const formError = getFormError({
- value: field.value,
- maxValue: config.maxValue,
- minValue: config.minValue,
- });
- if (!!formError) {
- form.setError(
- `scoreData.${index}.value`,
- formError,
- );
- } else {
- form.clearErrors(
- `scoreData.${index}.value`,
- );
- }
- }}
- />
- ) : config.categories &&
- renderSelect(categories) ? (
- <Select
- name={field.name}
- value={
- optimisticScores[index].stringValue ??
- ""
- }
- defaultValue={score.stringValue}
- disabled={config.isArchived}
- onValueChange={handleOnValueChange(
- score,
- index,
- categories,
- )}
- >
- <SelectTrigger>
- <div className="text-xs">
- <SelectValue placeholder="Select category" />
- </div>
- </SelectTrigger>
- <SelectContent>
- {categories.map((category) =>
- category.isOutdated ? (
- <SelectItem
- key={category.value}
- value={category.label}
- disabled
- className="text-muted-foreground line-through"
- >
- {category.label}
- </SelectItem>
- ) : (
- <SelectItem
- key={category.value}
- value={category.label}
- className="text-xs"
- >
- {category.label}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
- ) : (
- <ToggleGroup
- type="single"
- value={
- optimisticScores[index].stringValue ??
- ""
- }
- defaultValue={score.stringValue}
- disabled={config.isArchived}
- className={`grid grid-cols-${categories.length}`}
- onValueChange={handleOnValueChange(
- score,
- index,
- categories,
- )}
- >
- {categories.map((category) =>
- category.isOutdated ? (
- <ToggleGroupItem
- key={category.value}
- value={category.label}
- disabled
- variant="outline"
- className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal opacity-50"
- >
- <span
- className="truncate"
- title={category.label}
- >
- {category.label}
- </span>
- <span>{`(${category.value})`}</span>
- </ToggleGroupItem>
- ) : (
- <ToggleGroupItem
- key={category.value}
- value={category.label}
- variant="outline"
- className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal"
- >
- <span
- className="truncate"
- title={category.label}
- >
- {category.label}
- </span>
- </ToggleGroupItem>
- ),
- )}
- </ToggleGroup>
- )}
- </FormControl>
- <FormMessage className="text-xs" />
- </FormItem>
- )}
- />
- {config.isArchived ? (
- <Popover key={score.id}>
- <PopoverTrigger asChild>
- <Button
- variant="link"
- type="button"
- className="px-0 pl-1"
- title="Delete archived score"
- disabled={isScoreUnsaved(score.scoreId)}
- >
- <Archive className="h-4 w-4"></Archive>
- </Button>
- </PopoverTrigger>
- <PopoverContent>
- <h2 className="text-md mb-3 font-semibold">
- Your score is archived
- </h2>
- <p className="mb-3 text-sm">
- This action will delete your score
- irreversibly.
- </p>
- <div className="flex justify-end space-x-4">
- <Button
- type="button"
- variant="destructive"
- loading={deleteMutation.isPending}
- onClick={async () => {
- if (score.scoreId) {
- // Record deletion timestamp
- deletionTimestamps.current.set(
- score.scoreId,
- Date.now(),
- );
-
- setOptimisticScore({
- index,
- value: null,
- stringValue: null,
- scoreId: null,
- });
-
- // Track pending delete
- pendingDeletes.current.add(
- score.scoreId,
- );
-
- try {
- await deleteMutation.mutateAsync({
- id: score.scoreId,
- projectId,
- });
- capture(
- "score:delete",
- analyticsData,
- );
- form.clearErrors(
- `scoreData.${index}.value`,
- );
-
- // Update the form with the new ID
- update(index, {
- ...score,
- scoreId: undefined,
- value: null,
- stringValue: undefined,
- });
- } finally {
- // Clean up pending delete tracking
- pendingDeletes.current.delete(
- score.scoreId,
- );
- }
- }
- }}
- >
- Delete
- </Button>
- </div>
- </PopoverContent>
- </Popover>
- ) : (
- <Button
- variant="link"
- type="button"
- className="px-0 pl-1"
- title="Delete score from trace/observation"
- disabled={
- isScoreUnsaved(score.scoreId) ||
- updateMutation.isPending
- }
- loading={
- deleteMutation.isPending &&
- !optimisticScores.some(
- (s) => s.scoreId === score.scoreId,
- ) &&
- !isScoreUnsaved(score.scoreId)
- }
- onClick={async () => {
- if (score.scoreId) {
- // Record deletion timestamp
- deletionTimestamps.current.set(
- score.scoreId,
- Date.now(),
- );
-
- setOptimisticScore({
- index,
- value: null,
- stringValue: null,
- scoreId: null,
- });
-
- // Track pending delete
- pendingDeletes.current.add(score.scoreId);
-
- try {
- await deleteMutation.mutateAsync({
- id: score.scoreId,
- projectId,
- });
- capture("score:delete", analyticsData);
- form.clearErrors(
- `scoreData.${index}.value`,
- );
-
- // Update the form with the new ID
- update(index, {
- ...score,
- scoreId: undefined,
- value: null,
- stringValue: undefined,
- });
- } finally {
- // Clean up pending delete tracking
- pendingDeletes.current.delete(
- score.scoreId,
- );
- }
- }
- }}
- >
- <X className="h-4 w-4" />
- </Button>
- )}
- </div>
- </div>
- );
- })}
- </>
- )}
- />
- </div>
- </form>
- </Form>
- </div>
- );
-}
diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsx
new file mode 100644
index 0000000000..e8db12414b
--- /dev/null
+++ b/web/src/features/scores/components/AnnotationForm.tsx
@@ -0,0 +1,841 @@
+import React, { useEffect, useMemo, useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import {
+ MessageCircleMore,
+ MessageCircle,
+ X,
+ Archive,
+ Loader2,
+ Check,
+ Trash,
+} from "lucide-react";
+import { useFieldArray, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import {
+ isPresent,
+ type ScoreConfigDomain,
+ type ScoreConfigCategoryDomain,
+ type UpdateAnnotationScoreData,
+ type CreateAnnotationScoreData,
+} from "@langfuse/shared";
+import { Input } from "@/src/components/ui/input";
+import {
+ Popover,
+ PopoverClose,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { Textarea } from "@/src/components/ui/textarea";
+import { HoverCardContent } from "@radix-ui/react-hover-card";
+import { HoverCard, HoverCardTrigger } from "@/src/components/ui/hover-card";
+import {
+ formatAnnotateDescription,
+ isNumericDataType,
+ isScoreUnsaved,
+} from "@/src/features/scores/lib/helpers";
+import { ToggleGroup, ToggleGroupItem } from "@/src/components/ui/toggle-group";
+import Header from "@/src/components/layouts/header";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { cn } from "@/src/utils/tailwind";
+import {
+ type AnnotationScoreFormData,
+ type InnerAnnotationFormProps,
+ type ScoreTarget,
+ type AnnotationForm as AnnotationFormType,
+} from "@/src/features/scores/types";
+import { AnnotateFormSchema } from "@/src/features/scores/schema";
+import { ScoreConfigDetails } from "@/src/features/score-configs/components/ScoreConfigDetails";
+import {
+ enrichCategoryOptionsWithStaleScoreValue,
+ resolveConfigValue,
+ validateNumericScore,
+} from "@/src/features/scores/lib/annotationFormHelpers";
+import { useMergedAnnotationScores } from "@/src/features/scores/lib/useMergedAnnotationScores";
+import { transformToAnnotationScores } from "@/src/features/scores/lib/transformScores";
+import { v4 as uuid } from "uuid";
+import { useScoreMutations } from "@/src/features/scores/hooks/useScoreMutations";
+import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
+import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";
+import { useScoreConfigSelection } from "@/src/features/scores/hooks/useScoreConfigSelection";
+import { useRouter } from "next/router";
+import { useAnnotationScoreConfigs } from "@/src/features/scores/hooks/useScoreConfigs";
+import { Skeleton } from "@/src/components/ui/skeleton";
+
+const CHAR_CUTOFF = 6;
+
+function CommentField({
+ savedComment,
+ disabled,
+ loading,
+ onSave,
+}: {
+ savedComment: string | null;
+ disabled: boolean;
+ loading: boolean;
+ onSave: (comment: string | null) => void;
+}) {
+ const [localValue, setLocalValue] = useState(savedComment || "");
+
+ // Reset local value when saved comment changes (after mutation completes)
+ useEffect(() => {
+ setLocalValue(savedComment || "");
+ }, [savedComment]);
+
+ const hasChanges = localValue.trim() !== (savedComment || "");
+
+ return (
+ <div className="relative">
+ <div className="mb-1 flex items-center justify-between">
+ <FormLabel className="text-sm">Score Notes</FormLabel>
+ <div className="relative">
+ {savedComment && (
+ <PopoverClose asChild>
+ <Button
+ variant="ghost"
+ type="button"
+ size="icon-xs"
+ loading={loading}
+ onClick={() => onSave(null)}
+ >
+ <Trash className="h-3 w-3" />
+ </Button>
+ </PopoverClose>
+ )}
+ </div>
+ </div>
+ <Textarea
+ className="text-xs"
+ value={localValue}
+ onChange={(e) => setLocalValue(e.target.value)}
+ disabled={disabled}
+ />
+
+ {hasChanges && (
+ <div className="mt-2 flex justify-end gap-1">
+ <PopoverClose asChild>
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ className="text-xs"
+ disabled={disabled}
+ loading={loading}
+ onClick={() => {
+ setLocalValue(savedComment || "");
+ }}
+ >
+ Discard Changes
+ </Button>
+ </PopoverClose>
+ <PopoverClose asChild>
+ <Button
+ type="button"
+ size="sm"
+ className="text-xs"
+ disabled={disabled}
+ loading={loading}
+ onClick={() => {
+ onSave(localValue);
+ }}
+ >
+ Save Changes
+ </Button>
+ </PopoverClose>
+ </div>
+ )}
+ </div>
+ );
+}
+
+const renderSelect = (categories: ScoreConfigCategoryDomain[]) => {
+ const hasMoreThanThreeCategories = categories.length > 3;
+ const hasLongCategoryNames = categories.some(
+ ({ label }) => label.length > CHAR_CUTOFF,
+ );
+
+ return (
+ hasMoreThanThreeCategories ||
+ (categories.length > 1 && hasLongCategoryNames)
+ );
+};
+
+function AnnotateHeader({
+ showSaving,
+ actionButtons,
+ description,
+}: {
+ showSaving: boolean;
+ actionButtons: React.ReactNode;
+ description: string;
+}) {
+ return (
+ <Header
+ title="Annotate"
+ help={{
+ description,
+ href: "https://langfuse.com/docs/evaluation/evaluation-methods/annotation",
+ className: "leading-relaxed",
+ }}
+ actionButtons={[
+ <div className="flex items-center justify-end" key="saving-spinner">
+ <div className="mr-1 items-center justify-center">
+ {showSaving ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Check className="h-3 w-3" />
+ )}
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {showSaving ? "Saving score data" : "Score data saved"}
+ </span>
+ </div>,
+ actionButtons,
+ ]}
+ />
+ );
+}
+
+const isInputDisabled = (config: ScoreConfigDomain) => {
+ return config.isArchived;
+};
+
+function InnerAnnotationForm<Target extends ScoreTarget>({
+ scoreTarget,
+ initialFormData,
+ scoreMetadata,
+ analyticsData,
+ actionButtons,
+ configControl,
+}: InnerAnnotationFormProps<Target>) {
+ const capture = usePostHogClientCapture();
+ const router = useRouter();
+ const { configs, allowManualSelection } = configControl;
+
+ // Initialize form with initial data (never updates)
+ const form = useForm({
+ resolver: zodResolver(AnnotateFormSchema),
+ defaultValues: { scoreData: initialFormData },
+ });
+
+ const { fields, update, remove, insert } = useFieldArray({
+ control: form.control,
+ name: "scoreData",
+ });
+
+ // Watch form values to keep fields in sync
+ const watchedScoreData = form.watch("scoreData");
+ const controlledFields = fields.map((field, index) => {
+ return {
+ ...field,
+ ...watchedScoreData[index],
+ };
+ });
+
+ const description = formatAnnotateDescription(scoreTarget);
+
+ // Mutations - write to cache but form doesn't consume cache updates
+ const { createMutation, updateMutation, deleteMutation } = useScoreMutations({
+ scoreTarget,
+ scoreMetadata,
+ });
+
+ // Config selection
+ const { selectionOptions, handleSelectionChange } = useScoreConfigSelection({
+ configs,
+ controlledFields,
+ isInputDisabled,
+ insert,
+ remove,
+ });
+
+ const [showSaving, setShowSaving] = useState(false);
+
+ useEffect(() => {
+ const isPending =
+ createMutation.isPending ||
+ updateMutation.isPending ||
+ deleteMutation.isPending;
+ setShowSaving(isPending);
+ }, [
+ createMutation.isPending,
+ updateMutation.isPending,
+ deleteMutation.isPending,
+ ]);
+
+ const handleDeleteScore = (index: number) => {
+ const field = controlledFields[index];
+
+ if (field.id) {
+ deleteMutation.mutate({
+ id: field.id,
+ projectId: scoreMetadata.projectId,
+ });
+ }
+
+ // Capture delete event
+ capture("score:delete", analyticsData);
+
+ // Remove from form
+ form.clearErrors(`scoreData.${index}.value`);
+ update(index, {
+ name: field.name,
+ dataType: field.dataType,
+ configId: field.configId,
+ id: null,
+ value: null,
+ stringValue: null,
+ comment: null,
+ });
+ };
+
+ const handleUpsert = (
+ index: number,
+ value: number | null,
+ stringValue: string | null,
+ ) => {
+ const field = controlledFields[index];
+ if (!field) return;
+
+ // Clear errors
+ form.clearErrors(`scoreData.${index}.value`);
+
+ // Keep form state in sync - update both value and stringValue
+ form.setValue(`scoreData.${index}.value`, value);
+ form.setValue(`scoreData.${index}.stringValue`, stringValue);
+
+ // Fire mutation
+ const { id: scoreId, ...fieldWithoutId } = field;
+
+ const baseScoreData = {
+ ...fieldWithoutId,
+ ...scoreMetadata,
+ value,
+ stringValue,
+ scoreTarget,
+ };
+
+ if (scoreId) {
+ updateMutation.mutate({
+ ...baseScoreData,
+ id: scoreId,
+ } as UpdateAnnotationScoreData);
+ } else {
+ const id = uuid();
+ // Update scoreId in form for future updates
+ form.setValue(`scoreData.${index}.id`, id);
+ createMutation.mutate({
+ ...baseScoreData,
+ id,
+ } as CreateAnnotationScoreData);
+ }
+ };
+
+ const handleNumericUpsert = (index: number) => {
+ const field = controlledFields[index];
+ const config = configs.find((c) => c.id === field.configId);
+
+ if (!config || !field) return;
+
+ // Client-side validation - don't fire mutation if invalid
+ const errorMessage = validateNumericScore({
+ value: field.value,
+ maxValue: config.maxValue,
+ minValue: config.minValue,
+ });
+
+ if (!!errorMessage) {
+ form.setError(`scoreData.${index}.value`, {
+ type: "custom",
+ message: errorMessage,
+ });
+ return;
+ }
+
+ form.clearErrors(`scoreData.${index}.value`);
+ handleUpsert(index, field.value as number, null);
+ };
+
+ const handleCategoricalUpsert = (index: number, stringValue: string) => {
+ const field = controlledFields[index];
+ const config = configs.find((c) => c.id === field.configId);
+
+ if (!config || !field) return;
+
+ const numericCategoryValue = config.categories?.find(
+ ({ label }) => label === stringValue,
+ )?.value;
+
+ if (!isPresent(numericCategoryValue)) return;
+
+ handleUpsert(index, numericCategoryValue, stringValue);
+ };
+
+ const handleCommentUpdate = (index: number, newComment: string | null) => {
+ const field = controlledFields[index];
+ if (!field || !field.id) return;
+
+ // Update form with the new comment value
+ update(index, {
+ ...field,
+ comment: newComment,
+ });
+
+ // Fire mutation with new comment (only pass necessary fields)
+ updateMutation.mutate({
+ ...field,
+ ...scoreMetadata,
+ scoreTarget,
+ comment: newComment,
+ } as UpdateAnnotationScoreData);
+ };
+
+ return (
+ <div className="mx-auto w-full space-y-2 overflow-y-auto md:max-h-full">
+ <div className="sticky top-0 z-10 rounded-sm bg-background">
+ <AnnotateHeader
+ showSaving={showSaving}
+ actionButtons={actionButtons}
+ description={description}
+ />
+ {allowManualSelection ? (
+ <div className="grid grid-flow-col items-center">
+ <MultiSelectKeyValues
+ placeholder="Value"
+ align="end"
+ items="empty scores"
+ className="grid grid-cols-[auto,1fr,auto,auto] gap-2"
+ options={selectionOptions}
+ onValueChange={handleSelectionChange}
+ values={fields
+ .filter((field) => !!field.configId)
+ .map((field) => ({
+ key: field.configId as string,
+ value: resolveConfigValue({
+ dataType: field.dataType,
+ name: field.name,
+ }),
+ }))}
+ controlButtons={
+ <DropdownMenuItem
+ onSelect={() => {
+ capture(
+ "score_configs:manage_configs_item_click",
+ analyticsData,
+ );
+ router.push(
+ `/project/${scoreMetadata.projectId}/settings/scores`,
+ );
+ }}
+ >
+ Manage score configs
+ </DropdownMenuItem>
+ }
+ />
+ </div>
+ ) : null}
+ </div>
+ <Form {...form}>
+ <form className="flex flex-col gap-4">
+ <div className="grid grid-flow-row gap-2">
+ <FormField
+ control={form.control}
+ name="scoreData"
+ render={() => (
+ <>
+ {controlledFields.map((score, index) => {
+ const config = configs.find(
+ (config) => config.id === score.configId,
+ );
+ if (!config) return null;
+ const categories = enrichCategoryOptionsWithStaleScoreValue(
+ config.categories ?? [],
+ score.stringValue,
+ );
+
+ return (
+ <div
+ key={fields[index]?.id}
+ className="grid w-full grid-cols-[1fr,2fr] items-center gap-8 text-left"
+ >
+ <div className="grid h-full grid-cols-[1fr,auto] items-center">
+ {config.description ||
+ isPresent(config.maxValue) ||
+ isPresent(config.minValue) ? (
+ <HoverCard>
+ <HoverCardTrigger asChild>
+ <span
+ className={cn(
+ "line-clamp-2 break-words text-xs font-medium underline decoration-muted-gray decoration-dashed underline-offset-2",
+ config.isArchived
+ ? "text-foreground/40"
+ : "",
+ )}
+ >
+ {score.name}
+ </span>
+ </HoverCardTrigger>
+ <HoverCardContent className="z-20 max-h-[60vh] max-w-64 overflow-y-auto rounded border">
+ <ScoreConfigDetails config={config} />
+ </HoverCardContent>
+ </HoverCard>
+ ) : (
+ <span
+ className={cn(
+ "line-clamp-2 break-words text-xs font-medium",
+ config.isArchived ? "text-foreground/40" : "",
+ )}
+ title={score.name}
+ >
+ {score.name}
+ </span>
+ )}
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="link"
+ type="button"
+ size="xs"
+ title="Add or view score comment"
+ className="h-full items-start px-0 pl-1 disabled:text-primary/50 disabled:opacity-100"
+ disabled={
+ isScoreUnsaved(score.id) ||
+ (config.isArchived && !score.comment)
+ }
+ >
+ {score.comment ? (
+ <MessageCircleMore className="h-4 w-4" />
+ ) : (
+ <MessageCircle className="h-4 w-4" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent>
+ <FormField
+ control={form.control}
+ name={`scoreData.${index}.comment`}
+ render={() => (
+ <FormItem className="space-y-4">
+ <FormControl>
+ <CommentField
+ savedComment={score.comment ?? null}
+ disabled={isInputDisabled(config)}
+ loading={updateMutation.isPending}
+ onSave={(newComment) => {
+ const trimmed = newComment?.trim();
+ handleCommentUpdate(
+ index,
+ trimmed || null,
+ );
+ }}
+ />
+ </FormControl>
+ <FormMessage className="text-xs" />
+ </FormItem>
+ )}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div className="grid grid-cols-[11fr,1fr] items-center py-1">
+ {isNumericDataType(score.dataType) ? (
+ <FormField
+ control={form.control}
+ name={`scoreData.${index}.value`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ onChange={(e) => {
+ const value = e.target.value;
+ if (value === "") {
+ return;
+ }
+ field.onChange(Number(value));
+ }}
+ type="number"
+ className="text-xs"
+ disabled={isInputDisabled(config)}
+ onBlur={() => handleNumericUpsert(index)}
+ />
+ </FormControl>
+ <FormMessage className="text-xs" />
+ </FormItem>
+ )}
+ />
+ ) : config.categories && renderSelect(categories) ? (
+ <FormField
+ control={form.control}
+ name={`scoreData.${index}.stringValue`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Select
+ name={field.name}
+ value={field.value ?? ""}
+ disabled={isInputDisabled(config)}
+ onValueChange={(value) => {
+ field.onChange(value);
+ handleCategoricalUpsert(index, value);
+ }}
+ >
+ <SelectTrigger>
+ <div className="text-xs">
+ <SelectValue placeholder="Select category" />
+ </div>
+ </SelectTrigger>
+ <SelectContent>
+ {categories.map((category) =>
+ category.isOutdated ? (
+ <SelectItem
+ key={category.value}
+ value={category.label}
+ disabled
+ className="text-muted-foreground line-through"
+ >
+ {category.label}
+ </SelectItem>
+ ) : (
+ <SelectItem
+ key={category.value}
+ value={category.label}
+ className="text-xs"
+ >
+ {category.label}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage className="text-xs" />
+ </FormItem>
+ )}
+ />
+ ) : (
+ <FormField
+ control={form.control}
+ name={`scoreData.${index}.stringValue`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <ToggleGroup
+ type="single"
+ value={field.value ?? ""}
+ disabled={isInputDisabled(config)}
+ className={`grid grid-cols-${categories.length}`}
+ onValueChange={(value) => {
+ field.onChange(value);
+ handleCategoricalUpsert(index, value);
+ }}
+ >
+ {categories.map((category) =>
+ category.isOutdated ? (
+ <ToggleGroupItem
+ key={category.value}
+ value={category.label}
+ disabled
+ variant="outline"
+ className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal opacity-50"
+ >
+ <span
+ className="truncate"
+ title={category.label}
+ >
+ {category.label}
+ </span>
+ <span>{`(${category.value})`}</span>
+ </ToggleGroupItem>
+ ) : (
+ <ToggleGroupItem
+ key={category.value}
+ value={category.label}
+ variant="outline"
+ className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal"
+ >
+ <span
+ className="truncate"
+ title={category.label}
+ >
+ {category.label}
+ </span>
+ </ToggleGroupItem>
+ ),
+ )}
+ </ToggleGroup>
+ </FormControl>
+ <FormMessage className="text-xs" />
+ </FormItem>
+ )}
+ />
+ )}
+ {config.isArchived ? (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="link"
+ type="button"
+ className="px-0 pl-1"
+ title="Delete archived score"
+ disabled={isScoreUnsaved(score.id)}
+ >
+ <Archive className="h-4 w-4"></Archive>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent>
+ <h2 className="text-md mb-3 font-semibold">
+ Your score is archived
+ </h2>
+ <p className="mb-3 text-sm">
+ This action will delete your score
+ irreversibly.
+ </p>
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="button"
+ variant="destructive"
+ loading={deleteMutation.isPending}
+ onClick={() => handleDeleteScore(index)}
+ >
+ Delete
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ ) : (
+ <Button
+ variant="link"
+ type="button"
+ className="px-0 pl-1"
+ title="Delete score from trace/observation"
+ disabled={
+ isScoreUnsaved(score.id) ||
+ updateMutation.isPending
+ }
+ loading={
+ deleteMutation.isPending &&
+ !isScoreUnsaved(score.id)
+ }
+ onClick={() => handleDeleteScore(index)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </>
+ )}
+ />
+ </div>
+ </form>
+ </Form>
+ </div>
+ );
+}
+
+export function AnnotationForm<Target extends ScoreTarget>({
+ scoreTarget,
+ serverScores,
+ scoreMetadata,
+ analyticsData,
+ actionButtons,
+ configSelection = { mode: "selectable" },
+}: AnnotationFormType<Target>) {
+ const { projectId } = scoreMetadata;
+ const { isLoading, availableConfigs, selectedConfigIds } =
+ useAnnotationScoreConfigs({
+ projectId,
+ configSelection,
+ });
+
+ // Step 1: Transform server scores to annotation scores
+ const serverAnnotationScores = useMemo(() => {
+ if (Array.isArray(serverScores)) {
+ // Flat scores from trace/session detail
+ return transformToAnnotationScores(serverScores, availableConfigs);
+ } else {
+ // Aggregates from compare view
+ return transformToAnnotationScores(
+ serverScores,
+ availableConfigs,
+ scoreTarget.type === "trace" ? scoreTarget.traceId : "",
+ scoreTarget.type === "trace" ? scoreTarget.observationId : undefined,
+ );
+ }
+ }, [serverScores, availableConfigs, scoreTarget]);
+
+ // Step 2: Merge with cache
+ const annotationScores = useMergedAnnotationScores(
+ serverAnnotationScores,
+ scoreTarget,
+ );
+
+ const initialFormData: AnnotationScoreFormData[] = [];
+ const configIds = new Set<string>();
+ annotationScores.forEach((score) => {
+ configIds.add(score.configId);
+ initialFormData.push({
+ id: score.id,
+ configId: score.configId,
+ name: score.name,
+ dataType: score.dataType,
+ value: score.value,
+ stringValue: score.stringValue,
+ comment: score.comment,
+ });
+ });
+
+ selectedConfigIds.forEach((configId) => {
+ if (!configIds.has(configId)) {
+ const config = availableConfigs.find((c) => c.id === configId);
+ if (!config) return;
+ initialFormData.push({
+ id: null,
+ configId,
+ name: config.name,
+ dataType: config.dataType,
+ value: null,
+ stringValue: null,
+ comment: null,
+ });
+ }
+ });
+
+ const sortedInitialFormData = initialFormData.sort((a, b) =>
+ a.name.localeCompare(b.name),
+ );
+
+ return isLoading ? (
+ <Skeleton className="h-full w-full" />
+ ) : (
+ <InnerAnnotationForm
+ scoreTarget={scoreTarget}
+ initialFormData={sortedInitialFormData}
+ scoreMetadata={scoreMetadata}
+ analyticsData={analyticsData}
+ actionButtons={actionButtons}
+ configControl={{
+ configs: availableConfigs,
+ allowManualSelection: configSelection.mode === "selectable",
+ }}
+ />
+ );
+}
diff --git a/web/src/features/scores/components/ScoreRow.tsx b/web/src/features/scores/components/ScoreRow.tsx
index bfe23ed8a0..3cd03793ef 100644
--- a/web/src/features/scores/components/ScoreRow.tsx
+++ b/web/src/features/scores/components/ScoreRow.tsx
@@ -69,7 +69,7 @@ const ScoreRowContent = ({
</span>
<div className="flex flex-shrink-0 items-center gap-1">
{aggregate ? (
- <span className="line-clamp-1 text-sm font-medium">
+ <span className="line-clamp-1 font-medium">
{resolveScoreValue(aggregate)}
</span>
) : (
diff --git a/web/src/features/scores/contexts/ScoreCacheContext.tsx b/web/src/features/scores/contexts/ScoreCacheContext.tsx
new file mode 100644
index 0000000000..6c7a70dbd6
--- /dev/null
+++ b/web/src/features/scores/contexts/ScoreCacheContext.tsx
@@ -0,0 +1,196 @@
+import { type ScoreDomain } from "@langfuse/shared";
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useState,
+} from "react";
+import { type ScoreColumn } from "@/src/features/scores/types";
+import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";
+
+/**
+ * Cached score shape - stored in client-side cache for optimistic updates
+ */
+export type CachedScore = Pick<
+ ScoreDomain,
+ // Required for cache operations
+ | "id"
+ // Project context
+ | "projectId"
+ | "environment"
+ // Score identity
+ | "name"
+ | "dataType"
+ // Score values
+ | "value"
+ | "stringValue"
+ | "comment"
+ // Target
+ | "traceId"
+ | "observationId"
+ | "sessionId"
+> & {
+ // Score identity - non-nullable
+ configId: string;
+ source: "ANNOTATION";
+};
+
+type ScoreCacheContextValue = {
+ set: (id: string, score: CachedScore) => void;
+ get: (id: string) => CachedScore | undefined;
+ delete: (id: string) => void;
+ isDeleted: (id: string) => boolean;
+ clear: () => void;
+
+ getAllForTarget: (
+ mode: "target-and-child-scores" | "target-scores-only",
+ target: {
+ traceId?: string;
+ observationId?: string;
+ sessionId?: string;
+ },
+ ) => CachedScore[];
+
+ getAll: () => CachedScore[];
+
+ // Score columns cache
+ setColumn: (column: Omit<ScoreColumn, "key">) => void;
+ getColumnsMap: () => Map<string, ScoreColumn>;
+};
+
+const ScoreCacheContext = createContext<ScoreCacheContextValue | undefined>(
+ undefined,
+);
+
+export function ScoreCacheProvider({ children }: { children: ReactNode }) {
+ const [cache, setCache] = useState<Map<string, CachedScore>>(new Map());
+ const [deletedIds, setDeletedIds] = useState<Set<string>>(new Set());
+ const [columnsCache, setColumnsCache] = useState<Map<string, ScoreColumn>>(
+ new Map(),
+ );
+
+ const set = useCallback((id: string, score: CachedScore) => {
+ setCache((prev) => {
+ const newCache = new Map(prev);
+ newCache.set(id, score);
+ return newCache;
+ });
+ }, []);
+
+ const get = useCallback(
+ (id: string) => {
+ return cache.get(id);
+ },
+ [cache],
+ );
+
+ const deleteScore = useCallback((id: string) => {
+ setDeletedIds((prev) => {
+ const newSet = new Set(prev);
+ newSet.add(id);
+ return newSet;
+ });
+ // Also remove from cache if present
+ setCache((prev) => {
+ if (!prev.has(id)) return prev;
+ const newCache = new Map(prev);
+ newCache.delete(id);
+ return newCache;
+ });
+ }, []);
+
+ const isDeleted = useCallback(
+ (id: string) => {
+ return deletedIds.has(id);
+ },
+ [deletedIds],
+ );
+
+ const clear = useCallback(() => {
+ setCache(new Map());
+ setDeletedIds(new Set());
+ }, []);
+
+ const getAllForTarget = useCallback(
+ (
+ mode: "target-and-child-scores" | "target-scores-only",
+ target: {
+ traceId?: string;
+ observationId?: string;
+ sessionId?: string;
+ },
+ ) => {
+ const matchObservationScore = (
+ mode: "target-and-child-scores" | "target-scores-only",
+ ) => {
+ switch (mode) {
+ case "target-and-child-scores":
+ return () => true;
+ case "target-scores-only":
+ return (s: CachedScore) =>
+ s.observationId === (target.observationId ?? null);
+ default:
+ throw new Error(`Invalid mode: ${mode}`);
+ }
+ };
+
+ return Array.from(cache.values()).filter((s) => {
+ // Session target
+ if (target.sessionId) {
+ return s.sessionId === target.sessionId;
+ }
+
+ // Trace/observation target
+ return s.traceId === target.traceId && matchObservationScore(mode)(s);
+ });
+ },
+ [cache],
+ );
+
+ const getAll = useCallback(() => {
+ return Array.from(cache.values());
+ }, [cache]);
+
+ const setColumn = useCallback((column: Omit<ScoreColumn, "key">) => {
+ setColumnsCache((prev) => {
+ const key = composeAggregateScoreKey(column);
+ if (prev.has(key)) {
+ return prev;
+ }
+ const newCache = new Map(prev);
+ newCache.set(key, { ...column, key });
+ return newCache;
+ });
+ }, []);
+
+ const getColumnsMap = useCallback(() => {
+ return columnsCache;
+ }, [columnsCache]);
+
+ return (
+ <ScoreCacheContext.Provider
+ value={{
+ set,
+ get,
+ delete: deleteScore,
+ isDeleted,
+ clear,
+ getAllForTarget,
+ getAll,
+ setColumn,
+ getColumnsMap,
+ }}
+ >
+ {children}
+ </ScoreCacheContext.Provider>
+ );
+}
+
+export function useScoreCache() {
+ const context = useContext(ScoreCacheContext);
+ if (!context) {
+ throw new Error("useScoreCache must be used within ScoreCacheProvider");
+ }
+ return context;
+}
diff --git a/web/src/features/scores/hooks/useEmptyConfigs.ts b/web/src/features/scores/hooks/useEmptyConfigs.ts
new file mode 100644
index 0000000000..b8ea99a7e1
--- /dev/null
+++ b/web/src/features/scores/hooks/useEmptyConfigs.ts
@@ -0,0 +1,9 @@
+import useLocalStorage from "@/src/components/useLocalStorage";
+
+export function useEmptyScoreConfigs() {
+ const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
+ string[]
+ >("emptySelectedConfigIds", []);
+
+ return { emptySelectedConfigIds, setEmptySelectedConfigIds };
+}
diff --git a/web/src/features/scores/hooks/useScoreConfigSelection.ts b/web/src/features/scores/hooks/useScoreConfigSelection.ts
new file mode 100644
index 0000000000..316429a2dd
--- /dev/null
+++ b/web/src/features/scores/hooks/useScoreConfigSelection.ts
@@ -0,0 +1,131 @@
+import { useEmptyScoreConfigs } from "@/src/features/scores/hooks/useEmptyConfigs";
+import { resolveConfigValue } from "@/src/features/scores/lib/annotationFormHelpers";
+import {
+ type AnnotateFormSchemaType,
+ type AnnotationScoreSchemaType,
+} from "@/src/features/scores/types";
+import { type ScoreConfigDomain } from "@langfuse/shared";
+import { useCallback, useMemo } from "react";
+import {
+ type UseFieldArrayRemove,
+ type UseFieldArrayInsert,
+} from "react-hook-form";
+import { toast } from "sonner";
+
+const resolveAlphabeticalPosition = (
+ name: string,
+ controlledFields: AnnotationScoreSchemaType[],
+) => {
+ const alphabeticalIndex = controlledFields.findIndex(
+ (f) => f.name.localeCompare(name) > 0,
+ );
+ // If no field comes after this one alphabetically (-1), insert at the end
+ if (alphabeticalIndex === -1) return controlledFields.length;
+
+ return alphabeticalIndex;
+};
+
+export function useScoreConfigSelection({
+ configs,
+ controlledFields,
+ isInputDisabled,
+ insert,
+ remove,
+}: {
+ configs: ScoreConfigDomain[];
+ controlledFields: AnnotationScoreSchemaType[];
+ isInputDisabled: (config: ScoreConfigDomain) => boolean;
+ insert: UseFieldArrayInsert<AnnotateFormSchemaType, "scoreData">;
+ remove: UseFieldArrayRemove;
+}): {
+ selectionOptions: {
+ key: string;
+ value: string;
+ disabled: boolean;
+ }[];
+ handleSelectionChange: (
+ values: Record<string, string>[],
+ changedValueId?: string,
+ ) => void;
+} {
+ const { emptySelectedConfigIds, setEmptySelectedConfigIds } =
+ useEmptyScoreConfigs();
+
+ const selectionOptions = useMemo(() => {
+ return configs
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((config) => {
+ return {
+ key: config.id,
+ value: resolveConfigValue({
+ dataType: config.dataType,
+ name: config.name,
+ }),
+ disabled: isInputDisabled(config),
+ };
+ });
+ }, [configs, isInputDisabled]);
+
+ const handleSelectionChange = useCallback(
+ (values: Record<string, string>[], changedValueId?: string) => {
+ if (!changedValueId) return;
+
+ const fieldIndex = controlledFields.findIndex(
+ (f) => f.configId === changedValueId,
+ );
+ const isCurrentlyInForm = fieldIndex !== -1;
+
+ if (!isCurrentlyInForm) {
+ // Config was just selected -> add empty row to form
+ const config = configs.find((c) => c.id === changedValueId);
+ if (config) {
+ // find correct alphabetical position to insert new field at
+ const position = resolveAlphabeticalPosition(
+ config.name,
+ controlledFields,
+ );
+
+ insert(position, {
+ id: null,
+ configId: config.id,
+ name: config.name,
+ dataType: config.dataType,
+ value: null,
+ stringValue: null,
+ comment: null,
+ });
+ }
+ setEmptySelectedConfigIds?.([
+ ...emptySelectedConfigIds,
+ changedValueId,
+ ]);
+ } else {
+ // Config was deselected
+ const field = controlledFields[fieldIndex];
+ if (field?.id) {
+ toast.error("Cannot deselect a populated score");
+ return;
+ } else {
+ // No score -> remove row from form and empty selected config ids
+ remove(fieldIndex);
+ setEmptySelectedConfigIds?.(
+ emptySelectedConfigIds.filter((id) => id !== changedValueId),
+ );
+ }
+ }
+ },
+ [
+ controlledFields,
+ configs,
+ insert,
+ remove,
+ emptySelectedConfigIds,
+ setEmptySelectedConfigIds,
+ ],
+ );
+
+ return {
+ selectionOptions,
+ handleSelectionChange,
+ };
+}
diff --git a/web/src/features/scores/hooks/useScoreConfigs.ts b/web/src/features/scores/hooks/useScoreConfigs.ts
new file mode 100644
index 0000000000..cb24a4899d
--- /dev/null
+++ b/web/src/features/scores/hooks/useScoreConfigs.ts
@@ -0,0 +1,54 @@
+import { useEmptyScoreConfigs } from "@/src/features/scores/hooks/useEmptyConfigs";
+import { type ScoreConfigSelection } from "@/src/features/scores/types";
+import { api } from "@/src/utils/api";
+import { type ScoreConfigDomain } from "@langfuse/shared";
+
+/**
+ * Prepares score configs for the AnnotationForm based on selection mode.
+ *
+ * Two modes:
+ * - **Fixed**: Uses pre-selected configs (no fetching required)
+ * - **Selectable**: Fetches all available configs and tracks user selections
+ *
+ * @param projectId - Project to fetch configs for (only used in selectable mode)
+ * @param configSelection - Either fixed configs or selectable mode
+ * @returns isLoading - True while fetching configs (always false in fixed mode)
+ * @returns availableConfigs - All score configs to display
+ * @returns selectedConfigIds - IDs of configs that are pre-selected
+ */
+export function useAnnotationScoreConfigs({
+ projectId,
+ configSelection,
+}: {
+ projectId: string;
+ configSelection: ScoreConfigSelection;
+}): {
+ isLoading: boolean;
+ availableConfigs: ScoreConfigDomain[];
+ selectedConfigIds: string[];
+} {
+ const { emptySelectedConfigIds } = useEmptyScoreConfigs();
+
+ const configs = api.scoreConfigs.all.useQuery(
+ {
+ projectId,
+ },
+ {
+ enabled: configSelection.mode === "selectable",
+ },
+ );
+
+ if (configSelection.mode === "fixed") {
+ return {
+ isLoading: false,
+ selectedConfigIds: configSelection.configs.map((c) => c.id),
+ availableConfigs: configSelection.configs,
+ };
+ } else {
+ return {
+ isLoading: configs.isLoading,
+ selectedConfigIds: emptySelectedConfigIds,
+ availableConfigs: configs.data?.configs ?? [],
+ };
+ }
+}
diff --git a/web/src/features/scores/hooks/useScoreCustomOptimistic.ts b/web/src/features/scores/hooks/useScoreCustomOptimistic.ts
deleted file mode 100644
index 9165e7f031..0000000000
--- a/web/src/features/scores/hooks/useScoreCustomOptimistic.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { useCallback, useState } from "react";
-
-export function useScoreCustomOptimistic<State, Action>(
- initialState: State,
- reducer: (state: State, action: Action) => State,
-): [State, (action: Action) => void] {
- const [state, setState] = useState<State>(initialState);
-
- const dispatch = useCallback(
- (action: Action) => {
- setState((currentState) => reducer(currentState, action));
- },
- [reducer],
- );
-
- return [state, dispatch];
-}
diff --git a/web/src/features/scores/hooks/useScoreMutations.ts b/web/src/features/scores/hooks/useScoreMutations.ts
index 629b5264a9..80f4fd9a24 100644
--- a/web/src/features/scores/hooks/useScoreMutations.ts
+++ b/web/src/features/scores/hooks/useScoreMutations.ts
@@ -1,194 +1,110 @@
import { api } from "@/src/utils/api";
-import { type AnnotateFormSchemaType, type ScoreTarget } from "../types";
-import { type ScoreConfigDomain, type APIScoreV2 } from "@langfuse/shared";
import {
- type UseFieldArrayUpdate,
- type UseFieldArrayRemove,
- type FieldArrayWithId,
- type useFieldArray,
-} from "react-hook-form";
-import { isTraceScore } from "@/src/features/scores/lib/helpers";
-
-const onTraceScoreSettledUpsert =
- ({
- utils,
- fields,
- update,
- isDrawerOpen,
- setShowSaving,
- }: {
- utils: ReturnType<typeof api.useUtils>;
- fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];
- update: UseFieldArrayUpdate<AnnotateFormSchemaType>;
- isDrawerOpen: boolean;
- setShowSaving: (showSaving: boolean) => void;
- }) =>
- async (data?: APIScoreV2, error?: unknown) => {
- if (!data || error) return;
-
- const { id, value, stringValue, name, dataType, configId, comment } = data;
- const updatedScoreIndex = fields.findIndex(
- (field) => field.configId === configId,
- );
-
- update(updatedScoreIndex, {
- value,
- name,
- dataType,
- scoreId: id,
- stringValue: stringValue ?? undefined,
- configId: configId ?? undefined,
- comment: comment ?? undefined,
- });
-
- await Promise.all([
- utils.scores.invalidate(),
- utils.traces.byIdWithObservationsAndScores.invalidate(),
- utils.sessions.invalidate(),
- ]);
-
- if (!isDrawerOpen) setShowSaving(false);
+ isSessionScore,
+ isTraceScore,
+} from "@/src/features/scores/lib/helpers";
+import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { type ScoreTarget } from "@langfuse/shared";
+
+export function useScoreMutations({
+ scoreTarget,
+ scoreMetadata,
+}: {
+ scoreTarget: ScoreTarget;
+ scoreMetadata: {
+ projectId: string;
+ queueId?: string;
+ environment?: string;
};
-
-const onScoreSettledDelete =
- ({
- utils,
- fields,
- update,
- configs,
- remove,
- isDrawerOpen,
- setShowSaving,
- }: {
- utils: ReturnType<typeof api.useUtils>;
- fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];
- update: UseFieldArrayUpdate<AnnotateFormSchemaType>;
- configs: ScoreConfigDomain[];
- remove: ReturnType<typeof useFieldArray>["remove"];
- isDrawerOpen: boolean;
- setShowSaving: (showSaving: boolean) => void;
- }) =>
- async (data?: APIScoreV2, error?: unknown) => {
- if (!data || error) return;
-
- const { id, name, dataType, configId } = data;
- const updatedScoreIndex = fields.findIndex((field) => field.scoreId === id);
-
- const config = configs.find((config) => config.id === configId);
- if (config && config.isArchived) {
- remove(updatedScoreIndex);
- } else {
- update(updatedScoreIndex, {
- name,
- dataType,
- configId: configId ?? undefined,
- value: null,
- scoreId: undefined,
- stringValue: undefined,
- comment: undefined,
- });
- }
-
- await Promise.all(
- [
- utils.scores.invalidate(),
- utils.traces.byIdWithObservationsAndScores.invalidate(),
- utils.sessions.invalidate(),
- ].filter(Boolean),
- );
-
- if (!isDrawerOpen) setShowSaving(false);
+}) {
+ const {
+ set: cacheSet,
+ get: cacheGet,
+ delete: cacheDelete,
+ setColumn: cacheSetColumn,
+ } = useScoreCache();
+
+ // Rather than rolling back optimistic updates, we reload the page to clear the cache and invalidate trpc queries
+ const onError = () => {
+ window.location.reload();
};
-const onSessionScoreSettledUpsert =
- ({
- utils,
- fields,
- update,
- isDrawerOpen,
- setShowSaving,
- }: {
- utils: ReturnType<typeof api.useUtils>;
- fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];
- update: UseFieldArrayUpdate<AnnotateFormSchemaType>;
- isDrawerOpen: boolean;
- setShowSaving: (showSaving: boolean) => void;
- }) =>
- async (data?: APIScoreV2, error?: unknown) => {
- if (!data || error) return;
-
- const { id, value, stringValue, name, dataType, configId, comment } = data;
- const updatedScoreIndex = fields.findIndex(
- (field) => field.configId === configId,
- );
-
- update(updatedScoreIndex, {
- value,
- name,
- dataType,
- scoreId: id,
- stringValue: stringValue ?? undefined,
- configId: configId ?? undefined,
- comment: comment ?? undefined,
- });
-
- await Promise.all([
- utils.scores.invalidate(),
- utils.sessions.byIdWithScores.invalidate(),
- ]);
-
- if (!isDrawerOpen) setShowSaving(false);
- };
-
-export function useScoreMutations(
- scoreTarget: ScoreTarget,
- projectId: string,
- fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[],
- update: UseFieldArrayUpdate<AnnotateFormSchemaType>,
- remove: UseFieldArrayRemove,
- configs: ScoreConfigDomain[],
- isDrawerOpen: boolean,
- setShowSaving: (showSaving: boolean) => void,
-) {
- const utils = api.useUtils();
-
- const onSettledUpsert = isTraceScore(scoreTarget)
- ? onTraceScoreSettledUpsert({
- utils,
- fields,
- update,
- isDrawerOpen,
- setShowSaving,
- })
- : onSessionScoreSettledUpsert({
- utils,
- fields,
- update,
- isDrawerOpen,
- setShowSaving,
+ // Create mutations with cache writes
+ const createMutation = api.scores.createAnnotationScore.useMutation({
+ onMutate: (variables) => {
+ if (!variables.id) return;
+
+ // Write to columns cache
+ cacheSetColumn({
+ name: variables.name,
+ dataType: variables.dataType,
+ source: "ANNOTATION",
});
- const onSettledDelete = onScoreSettledDelete({
- utils,
- fields,
- update,
- remove,
- configs,
- isDrawerOpen,
- setShowSaving,
- });
-
- // Create mutations with shared invalidation logic
- const createMutation = api.scores.createAnnotationScore.useMutation({
- onSettled: onSettledUpsert,
+ // Write to cache for optimistic update
+ cacheSet(variables.id, {
+ id: variables.id,
+ projectId: scoreMetadata.projectId,
+ environment: scoreMetadata.environment ?? "default",
+ traceId: isTraceScore(scoreTarget) ? scoreTarget.traceId : null,
+ observationId: isTraceScore(scoreTarget)
+ ? (scoreTarget.observationId ?? null)
+ : null,
+ sessionId: isSessionScore(scoreTarget) ? scoreTarget.sessionId : null,
+ configId: variables.configId,
+ name: variables.name,
+ dataType: variables.dataType,
+ source: "ANNOTATION",
+ value: variables.value ?? null,
+ stringValue: variables.stringValue ?? null,
+ comment: variables.comment ?? null,
+ });
+ },
+ onError,
});
const updateMutation = api.scores.updateAnnotationScore.useMutation({
- onSettled: onSettledUpsert,
+ onMutate: (variables) => {
+ const existing = cacheGet(variables.id);
+
+ if (!existing) {
+ // Write to cache for optimistic update
+ cacheSet(variables.id, {
+ id: variables.id,
+ projectId: scoreMetadata.projectId,
+ environment: scoreMetadata.environment ?? "default",
+ traceId: isTraceScore(scoreTarget) ? scoreTarget.traceId : null,
+ observationId: isTraceScore(scoreTarget)
+ ? (scoreTarget.observationId ?? null)
+ : null,
+ sessionId: isSessionScore(scoreTarget) ? scoreTarget.sessionId : null,
+ configId: variables.configId,
+ name: variables.name,
+ dataType: variables.dataType,
+ source: "ANNOTATION",
+ value: variables.value ?? null,
+ stringValue: variables.stringValue ?? null,
+ comment: variables.comment ?? null,
+ });
+ } else {
+ // Merge update into existing cache entry
+ cacheSet(variables.id, {
+ ...existing,
+ value: variables.value ?? existing.value,
+ stringValue: variables.stringValue ?? existing.stringValue,
+ comment: variables.comment ?? null,
+ });
+ }
+ },
+ onError,
});
const deleteMutation = api.scores.deleteAnnotationScore.useMutation({
- onSettled: onSettledDelete,
+ onMutate: (variables) => {
+ // Mark score as deleted
+ cacheDelete(variables.id);
+ },
+ onError,
});
return {
diff --git a/web/src/features/scores/hooks/useScoreValues.ts b/web/src/features/scores/hooks/useScoreValues.ts
deleted file mode 100644
index e977304218..0000000000
--- a/web/src/features/scores/hooks/useScoreValues.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useScoreCustomOptimistic } from "@/src/features/scores/hooks/useScoreCustomOptimistic";
-import { type AnnotateFormSchemaType } from "@/src/features/scores/types";
-import { ScoreDataType } from "@langfuse/shared";
-import { type UseFormGetValues } from "react-hook-form";
-
-export function useScoreValues({
- getValues,
-}: {
- getValues: UseFormGetValues<AnnotateFormSchemaType>;
-}) {
- const [optimisticScores, setOptimisticScore] = useScoreCustomOptimistic<
- AnnotateFormSchemaType["scoreData"],
- {
- index: number;
- value: number | null;
- stringValue: string | null;
- name?: string | null;
- dataType?: ScoreDataType | null;
- configId?: string | null;
- scoreId?: string | null;
- }
- >(getValues().scoreData, (state, updatedScore) => {
- const stateCopy = state.map((score, idx) =>
- idx === updatedScore.index
- ? {
- ...score,
- value: updatedScore.value,
- stringValue: updatedScore.stringValue ?? undefined,
- scoreId: updatedScore.scoreId ?? undefined,
- }
- : score,
- );
-
- if (updatedScore.index === stateCopy.length) {
- const newScore = {
- name: updatedScore.name ?? "",
- dataType: updatedScore.dataType ?? ScoreDataType.NUMERIC,
- configId: updatedScore.configId ?? undefined,
- value: updatedScore.value,
- stringValue: updatedScore.stringValue ?? undefined,
- scoreId: updatedScore.scoreId ?? undefined,
- };
- return [...stateCopy, newScore];
- }
- return stateCopy;
- });
-
- return { optimisticScores, setOptimisticScore };
-}
diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.ts
index 14ec06b42c..143b823a60 100644
--- a/web/src/features/scores/lib/aggregateScores.ts
+++ b/web/src/features/scores/lib/aggregateScores.ts
@@ -7,6 +7,14 @@ import {
type ScoreDataType,
} from "@langfuse/shared";
+/**
+ * Normalizes score names for comparison by converting - and . to _
+ * "-" and "." reserved for splitting in namespace
+ */
+export const normalizeScoreName = (name: string): string => {
+ return name.replaceAll(/[-\.]/g, "_");
+};
+
export const composeAggregateScoreKey = ({
name,
source,
@@ -17,7 +25,7 @@ export const composeAggregateScoreKey = ({
dataType: ScoreDataType;
keyPrefix?: string;
}): string => {
- const formattedName = name.replaceAll(/[-\.]/g, "_"); // "-" and "." reserved for splitting in namespace
+ const formattedName = normalizeScoreName(name);
return `${formattedName}-${source}-${dataType}`;
};
@@ -45,6 +53,17 @@ type ScoreToAggregate = (APIScoreV2 | ScoreSimplified) & {
hasMetadata?: boolean;
};
+/**
+ * Maps score data types to aggregate types for processing.
+ * Boolean scores are treated as categorical since they share the same
+ * aggregation logic (value counting vs numeric averaging).
+ */
+export const resolveAggregateType = (
+ dataType: ScoreDataType,
+): "NUMERIC" | "CATEGORICAL" => {
+ return dataType === "BOOLEAN" ? "CATEGORICAL" : dataType;
+};
+
export const aggregateScores = <T extends ScoreToAggregate>(
scores: T[],
): ScoreAggregate => {
@@ -70,12 +89,13 @@ export const aggregateScores = <T extends ScoreToAggregate>(
* When the aggregate contains multiple values, these extra fields are undefined.
*/
return Object.entries(groupedScores).reduce((acc, [key, scores]) => {
- if (scores[0].dataType === "NUMERIC") {
+ const aggregateType = resolveAggregateType(scores[0].dataType);
+ if (aggregateType === "NUMERIC") {
const values = scores.map((score) => score.value ?? 0);
if (!Boolean(values.length)) return acc;
const average = values.reduce((a, b) => a + b, 0) / values.length;
acc[key] = {
- type: "NUMERIC",
+ type: aggregateType,
values,
average,
comment: values.length === 1 ? scores[0].comment : undefined,
@@ -93,7 +113,7 @@ export const aggregateScores = <T extends ScoreToAggregate>(
{} as Record<string, number>,
);
acc[key] = {
- type: "CATEGORICAL",
+ type: aggregateType,
values,
valueCounts: Object.entries(valueCounts).map(([value, count]) => ({
value,
diff --git a/web/src/features/scores/lib/annotationFormHelpers.ts b/web/src/features/scores/lib/annotationFormHelpers.ts
new file mode 100644
index 0000000000..10a66b392e
--- /dev/null
+++ b/web/src/features/scores/lib/annotationFormHelpers.ts
@@ -0,0 +1,63 @@
+import { getScoreDataTypeIcon } from "@/src/features/scores/lib/scoreColumns";
+import {
+ isPresent,
+ type ScoreConfigCategoryDomain,
+ type ScoreDataType,
+} from "@langfuse/shared";
+
+export const resolveConfigValue = ({
+ name,
+ dataType,
+}: {
+ name: string;
+ dataType: ScoreDataType;
+}) => {
+ return `${getScoreDataTypeIcon(dataType)} ${name}`;
+};
+
+export const validateNumericScore = ({
+ value,
+ minValue,
+ maxValue,
+}: {
+ value?: number | null;
+ minValue?: number | null;
+ maxValue?: number | null;
+}): string | null => {
+ if (
+ (isPresent(maxValue) && Number(value) > maxValue) ||
+ (isPresent(minValue) && Number(value) < minValue)
+ ) {
+ return `Not in range: [${minValue ?? "-∞"},${maxValue ?? "∞"}]`;
+ }
+ return null;
+};
+
+// In case the underlying score config categories have changed, we need to enrich the category options with a stale score value
+export const enrichCategoryOptionsWithStaleScoreValue = (
+ categories: ScoreConfigCategoryDomain[],
+ currentStringValue?: string | null,
+): (ScoreConfigCategoryDomain & { isOutdated: boolean })[] => {
+ if (categories.length === 0) return [];
+
+ const enrichedCategories = categories.map((category) => ({
+ ...category,
+ isOutdated: false,
+ }));
+
+ if (!currentStringValue) return enrichedCategories;
+
+ // If current value exists in categories, return as-is
+ if (categories.some((category) => category.label === currentStringValue)) {
+ return enrichedCategories;
+ }
+
+ return [
+ {
+ label: currentStringValue,
+ value: 0,
+ isOutdated: true,
+ },
+ ...enrichedCategories,
+ ];
+};
diff --git a/web/src/features/scores/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.ts
index d2a0b0236e..72b0322e19 100644
--- a/web/src/features/scores/lib/getDefaultScoreData.ts
+++ b/web/src/features/scores/lib/getDefaultScoreData.ts
@@ -4,15 +4,19 @@ import {
type ScoreTargetSession,
} from "@langfuse/shared";
import { ScoreSource } from "@langfuse/shared";
-import { type APIScoreV2, type ScoreConfigDomain } from "@langfuse/shared";
+import { type ScoreConfigDomain } from "@langfuse/shared";
import { isTraceScore } from "@/src/features/scores/lib/helpers";
import { type AnnotationScoreDataSchema } from "@/src/features/scores/schema";
import { type z } from "zod/v4";
+import { type AnnotationScore } from "@/src/features/scores/types";
+
+const isAnnotationScore = (score: AnnotationScore) =>
+ score.source === ScoreSource.ANNOTATION;
const filterTraceAnnotationScores =
({ traceId, observationId }: ScoreTargetTrace) =>
- (s: APIScoreV2) =>
- s.source === ScoreSource.ANNOTATION &&
+ (s: AnnotationScore) =>
+ isAnnotationScore(s) &&
s.traceId === traceId &&
(observationId !== undefined
? s.observationId === observationId
@@ -20,8 +24,8 @@ const filterTraceAnnotationScores =
const filterSessionAnnotationScores =
({ sessionId }: ScoreTargetSession) =>
- (s: APIScoreV2) =>
- s.source === ScoreSource.ANNOTATION && s.sessionId === sessionId;
+ (s: AnnotationScore) =>
+ isAnnotationScore(s) && s.sessionId === sessionId;
export const getDefaultAnnotationScoreData = ({
scores,
@@ -29,7 +33,7 @@ export const getDefaultAnnotationScoreData = ({
configs,
scoreTarget,
}: {
- scores: APIScoreV2[];
+ scores: AnnotationScore[];
emptySelectedConfigIds: string[];
configs: ScoreConfigDomain[];
scoreTarget: ScoreTarget;
@@ -40,27 +44,15 @@ export const getDefaultAnnotationScoreData = ({
const populatedScores = scores
.filter(isValidScore)
- .map(
- ({
- id,
- name,
- value,
- dataType,
- stringValue,
- configId,
- comment,
- metadata,
- }) => ({
- scoreId: id,
- name,
- value,
- dataType,
- stringValue: stringValue ?? undefined,
- configId: configId ?? undefined,
- comment: comment ?? undefined,
- metadata: metadata ?? undefined,
- }),
- );
+ .map(({ id, name, value, dataType, stringValue, configId, comment }) => ({
+ scoreId: id ?? undefined,
+ name,
+ value,
+ dataType,
+ stringValue: stringValue ?? undefined,
+ configId: configId ?? undefined,
+ comment: comment ?? undefined,
+ }));
const populatedScoresConfigIds = new Set(
populatedScores.map((s) => s.configId),
@@ -80,7 +72,6 @@ export const getDefaultAnnotationScoreData = ({
stringValue: undefined,
configId: id,
comment: undefined,
- metadata: undefined,
}));
return [...populatedScores, ...emptyScores];
diff --git a/web/src/features/scores/lib/helpers.ts b/web/src/features/scores/lib/helpers.ts
index b8ce553421..ca76d59f77 100644
--- a/web/src/features/scores/lib/helpers.ts
+++ b/web/src/features/scores/lib/helpers.ts
@@ -15,7 +15,7 @@ export const isCategoricalDataType = (dataType: ScoreDataType) =>
export const isBooleanDataType = (dataType: ScoreDataType) =>
dataType === ScoreDataType.BOOLEAN;
-export const isScoreUnsaved = (scoreId?: string): boolean => !scoreId;
+export const isScoreUnsaved = (scoreId?: string | null): boolean => !scoreId;
export const toOrderedScoresList = (list: ScoreData[]): ScoreData[] =>
list.sort((a, b) => a.key.localeCompare(b.key));
diff --git a/web/src/features/scores/lib/mergeScoreColumns.ts b/web/src/features/scores/lib/mergeScoreColumns.ts
new file mode 100644
index 0000000000..e287b53a9c
--- /dev/null
+++ b/web/src/features/scores/lib/mergeScoreColumns.ts
@@ -0,0 +1,27 @@
+import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { type ScoreColumn } from "@/src/features/scores/types";
+
+/**
+ * Merges server score columns with cached score columns.
+ * Deduplicates by key - if a column exists in both server and cache,
+ * the server version is used (source of truth).
+ *
+ * @param serverColumns - Score columns from server
+ * @returns Combined and deduplicated score columns, sorted alphabetically
+ */
+export function useMergeScoreColumns(
+ serverColumns: ScoreColumn[],
+): ScoreColumn[] {
+ const { getColumnsMap } = useScoreCache();
+
+ // Dedupe by key: combine server + cache columns, server wins conflicts
+ const columnsMap = getColumnsMap();
+
+ // Add all server columns (overwrites duplicates from cache)
+ serverColumns.forEach((col) => columnsMap.set(col.key, col));
+
+ // Return deduplicated, sorted list
+ return Array.from(columnsMap.values()).sort((a, b) =>
+ a.key.localeCompare(b.key),
+ );
+}
diff --git a/web/src/features/scores/lib/mergeScoresWithCache.ts b/web/src/features/scores/lib/mergeScoresWithCache.ts
new file mode 100644
index 0000000000..bf5bbf219d
--- /dev/null
+++ b/web/src/features/scores/lib/mergeScoresWithCache.ts
@@ -0,0 +1,172 @@
+import { type APIScoreV2, type ScoreAggregate } from "@langfuse/shared";
+import { type CachedScore } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { type AnnotationScore } from "@/src/features/scores/types";
+import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";
+
+/**
+ * Pure function: Merge APIScoreV2[] with cache
+ *
+ * Applies cache operations while preserving complete server objects:
+ * - Update existing: Overlays only editable fields (value, stringValue, comment)
+ * - Add new: Adds cache-only scores (these are incomplete but OK for optimistic UI)
+ * - Delete: Removes deleted scores
+ *
+ * @param serverScores - Scores from tRPC
+ * @param cachedScores - Scores from cache for this target
+ * @param deletedIds - Set of deleted score IDs
+ * @returns Merged scores with cache overlay
+ */
+export function mergeScoresWithCache(
+ serverScores: APIScoreV2[],
+ cachedScores: CachedScore[],
+ deletedIds: Set<string>,
+): APIScoreV2[] {
+ const merged = new Map<string, APIScoreV2>();
+
+ // Start with server scores (filter out deleted ones)
+ serverScores.forEach((s) => {
+ if (!deletedIds.has(s.id)) {
+ merged.set(s.id, s);
+ }
+ });
+
+ // Overlay cached scores
+ cachedScores.forEach((cached) => {
+ const existing = merged.get(cached.id);
+
+ if (existing) {
+ // Update existing: preserve server object, overlay editable fields only
+ merged.set(cached.id, {
+ ...existing,
+ value: cached.value,
+ stringValue: cached.stringValue,
+ comment: cached.comment,
+ } as APIScoreV2);
+ } else {
+ // New score: only exists in cache (incomplete but OK for optimistic UI)
+ merged.set(cached.id, cached as APIScoreV2);
+ }
+ });
+
+ return Array.from(merged.values());
+}
+
+/**
+ * Pure function: Merge ScoreAggregate with cache
+ *
+ * Removes deleted aggregates and overlays cached values.
+ *
+ * @param serverAggregates - Aggregates from tRPC
+ * @param cachedScores - Scores from cache for this target
+ * @param deletedIds - Set of deleted score IDs
+ * @returns Merged aggregates with cache overlay
+ */
+export function mergeAggregatesWithCache(
+ serverAggregates: ScoreAggregate,
+ cachedScores: CachedScore[],
+ deletedIds: Set<string>,
+): ScoreAggregate {
+ const merged = { ...serverAggregates };
+
+ // Remove deleted scores from server aggregates
+ Object.entries(merged).forEach(([key, aggregate]) => {
+ if (aggregate.id && deletedIds.has(aggregate.id)) {
+ delete merged[key];
+ }
+ });
+
+ // Apply cached scores to aggregates
+ cachedScores.forEach((cached) => {
+ const key = composeAggregateScoreKey({
+ name: cached.name,
+ source: cached.source,
+ dataType: cached.dataType,
+ });
+
+ // Add or update aggregate with cached values
+ if (cached.dataType === "NUMERIC") {
+ merged[key] = {
+ type: "NUMERIC",
+ values: [cached.value as number],
+ average: cached.value as number,
+ comment: cached.comment,
+ id: cached.id,
+ };
+ } else {
+ merged[key] = {
+ type: "CATEGORICAL",
+ values: [cached.stringValue as string],
+ valueCounts: [
+ {
+ value: cached.stringValue as string,
+ count: 1,
+ },
+ ],
+ comment: cached.comment,
+ id: cached.id,
+ };
+ }
+ });
+
+ return merged;
+}
+
+/**
+ * Pure function: Merge AnnotationScore[] with cache
+ *
+ * Applies cache operations while preserving complete server objects:
+ * - Update existing: Overlays only editable fields (value, stringValue, comment)
+ * - Add new: Creates new AnnotationScore from cached data
+ * - Delete: Removes deleted scores
+ *
+ * @param serverAnnotationScores - Already-transformed annotation scores from server
+ * @param cachedScores - Scores from cache for this target
+ * @param deletedIds - Set of deleted score IDs
+ * @returns Merged annotation scores with cache overlay
+ */
+export function mergeAnnotationScoresWithCache(
+ serverAnnotationScores: AnnotationScore[],
+ cachedScores: CachedScore[],
+ deletedIds: Set<string>,
+): AnnotationScore[] {
+ const merged = new Map<string, AnnotationScore>();
+
+ // Start with server scores (filter out deleted ones)
+ serverAnnotationScores.forEach((s) => {
+ if (!deletedIds.has(s.id ?? "")) {
+ merged.set(s.id ?? "", s);
+ }
+ });
+
+ // Overlay cached scores
+ cachedScores.forEach((cached) => {
+ const existing = merged.get(cached.id);
+
+ if (existing) {
+ // Update existing: preserve server object, overlay editable fields only
+ merged.set(cached.id, {
+ ...existing,
+ value: cached.value,
+ stringValue: cached.stringValue,
+ comment: cached.comment,
+ });
+ } else {
+ // New score: create AnnotationScore from cached data
+ merged.set(cached.id, {
+ id: cached.id,
+ name: cached.name,
+ dataType: cached.dataType,
+ source: cached.source,
+ configId: cached.configId,
+ value: cached.value,
+ stringValue: cached.stringValue,
+ comment: cached.comment,
+ traceId: cached.traceId ?? null,
+ observationId: cached.observationId ?? null,
+ sessionId: cached.sessionId ?? null,
+ });
+ }
+ });
+
+ return Array.from(merged.values());
+}
diff --git a/web/src/features/scores/lib/transformScores.ts b/web/src/features/scores/lib/transformScores.ts
new file mode 100644
index 0000000000..8aa58e6b07
--- /dev/null
+++ b/web/src/features/scores/lib/transformScores.ts
@@ -0,0 +1,135 @@
+import { type APIScoreV2, type ScoreConfigDomain } from "@langfuse/shared";
+import { type ScoreAggregate } from "@langfuse/shared";
+import { type AnnotationScore } from "@/src/features/scores/types";
+import {
+ decomposeAggregateScoreKey,
+ normalizeScoreName,
+} from "@/src/features/scores/lib/aggregateScores";
+
+/**
+ * Transform flat merged scores to annotation scores (Trace/Observation/Session Detail)
+ */
+export function transformToAnnotationScores(
+ mergedScores: APIScoreV2[],
+ configs: ScoreConfigDomain[],
+): AnnotationScore[];
+
+/**
+ * Transform aggregates to annotation scores (Compare View)
+ */
+export function transformToAnnotationScores(
+ mergedAggregates: ScoreAggregate,
+ configs: ScoreConfigDomain[],
+ traceId: string,
+ observationId?: string,
+): AnnotationScore[];
+
+/**
+ * Transform merged scores (flat or aggregate) to annotation scores
+ *
+ * Handles two input formats:
+ * - APIScoreV2[] (flat scores from trace detail)
+ * - ScoreAggregate (aggregated scores from compare view)
+ *
+ * Filters to ANNOTATION source only and excludes multi-value aggregates.
+ */
+export function transformToAnnotationScores(
+ input: APIScoreV2[] | ScoreAggregate,
+ configs: ScoreConfigDomain[],
+ traceId?: string,
+ observationId?: string,
+): AnnotationScore[] {
+ // Check if input is an array (flat scores)
+ if (Array.isArray(input)) {
+ return transformFlatScores(input, configs);
+ }
+
+ // Otherwise, it's aggregates
+ if (!traceId) {
+ throw new Error(
+ "traceId is required when transforming score aggregates to annotation scores",
+ );
+ }
+ return transformAggregates(input, configs, traceId, observationId);
+}
+
+/**
+ * Transform flat merged scores to annotation scores
+ * Used for trace/observation/session detail annotation drawer
+ */
+function transformFlatScores(
+ mergedScores: APIScoreV2[],
+ configs: ScoreConfigDomain[],
+): AnnotationScore[] {
+ return mergedScores
+ .filter((score) => score.source === "ANNOTATION")
+ .map((score) => {
+ const config = configs.find((c) => c.id === score.configId);
+ if (!config || !score.configId) return null;
+
+ return {
+ id: score.id,
+ name: score.name,
+ dataType: score.dataType,
+ source: score.source,
+ configId: score.configId,
+ value: score.value,
+ stringValue: score.stringValue,
+ comment: score.comment,
+ traceId: score.traceId ?? null,
+ observationId: score.observationId ?? null,
+ sessionId: score.sessionId ?? null,
+ };
+ })
+ .filter((score) => score !== null);
+}
+
+/**
+ * Transform aggregates to annotation scores
+ * Used for compare view annotation panel (compare drawer)
+ */
+function transformAggregates(
+ mergedAggregates: ScoreAggregate,
+ configs: ScoreConfigDomain[],
+ traceId: string,
+ observationId?: string,
+): AnnotationScore[] {
+ const scores: AnnotationScore[] = [];
+
+ Object.entries(mergedAggregates).forEach(([key, aggregate]) => {
+ const { name, source, dataType } = decomposeAggregateScoreKey(key);
+
+ // Only ANNOTATION source can be edited, and must have single ID
+ // Multi-value aggregates (no id) are child observation scores - skip them
+ if (source !== "ANNOTATION" || !aggregate.id) return;
+
+ const config = configs.find(
+ (c) => normalizeScoreName(c.name) === name && c.dataType === dataType,
+ );
+ if (!config) return;
+
+ const score: AnnotationScore = {
+ id: aggregate.id,
+ name,
+ dataType,
+ source,
+ configId: config.id,
+ traceId,
+ observationId: observationId ?? null,
+ sessionId: null,
+ comment: aggregate.comment ?? null,
+ value: null,
+ stringValue: null,
+ };
+
+ if (aggregate.type === "NUMERIC") {
+ score.value = aggregate.average ?? null;
+ } else {
+ score.stringValue = aggregate.values[0] ?? null;
+ }
+
+ scores.push(score);
+ });
+
+ return scores;
+}
diff --git a/web/src/features/scores/lib/useMergedAggregates.ts b/web/src/features/scores/lib/useMergedAggregates.ts
new file mode 100644
index 0000000000..6b528d47e2
--- /dev/null
+++ b/web/src/features/scores/lib/useMergedAggregates.ts
@@ -0,0 +1,45 @@
+import { useMemo } from "react";
+import { type ScoreAggregate } from "@langfuse/shared";
+import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { mergeAggregatesWithCache } from "@/src/features/scores/lib/mergeScoresWithCache";
+
+/**
+ * Hook for merging server aggregates with cached scores (F3: Compare View)
+ *
+ * Applies all cache operations to server aggregates:
+ * - Adds new cache-only scores as single-value aggregates
+ * - Updates existing scores with cached values
+ * - Removes deleted scores from aggregates
+ *
+ * Used in compare view table cells for optimistic score display.
+ *
+ * @param serverAggregates - Score aggregates from server
+ * @param traceId - Trace ID for filtering cache
+ * @param observationId - Optional observation ID for filtering cache
+ * @param mode - Describes whether to include child observation scores or only target scores. Defaults to only target scores.
+ * @returns Merged aggregates with all cache operations applied
+ */
+export function useMergedAggregates(
+ serverAggregates: ScoreAggregate,
+ traceId: string,
+ observationId?: string,
+ mode: "target-and-child-scores" | "target-scores-only" = "target-scores-only",
+): ScoreAggregate {
+ const { getAllForTarget, isDeleted } = useScoreCache();
+
+ const cachedScores = getAllForTarget(mode, { traceId, observationId });
+
+ // Build deletedIds Set
+ const deletedIds = useMemo(() => {
+ const ids = new Set<string>();
+ Object.values(serverAggregates).forEach((agg) => {
+ if (agg.id && isDeleted(agg.id)) ids.add(agg.id);
+ });
+ return ids;
+ }, [serverAggregates, isDeleted]);
+
+ return useMemo(
+ () => mergeAggregatesWithCache(serverAggregates, cachedScores, deletedIds),
+ [serverAggregates, cachedScores, deletedIds],
+ );
+}
diff --git a/web/src/features/scores/lib/useMergedAnnotationScores.ts b/web/src/features/scores/lib/useMergedAnnotationScores.ts
new file mode 100644
index 0000000000..e87e368d0d
--- /dev/null
+++ b/web/src/features/scores/lib/useMergedAnnotationScores.ts
@@ -0,0 +1,55 @@
+import { useMemo } from "react";
+import {
+ type ScoreTarget,
+ type AnnotationScore,
+} from "@/src/features/scores/types";
+import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { mergeAnnotationScoresWithCache } from "@/src/features/scores/lib/mergeScoresWithCache";
+
+/**
+ * Hook for merging server annotation scores with cached scores
+ *
+ * Takes already-transformed AnnotationScore[] from server and overlays:
+ * - Cached creates/updates (optimistic)
+ * - Cached deletes (filters out)
+ *
+ * This is the single merge point for AnnotationScore[] + cache.
+ * Callers must transform their server data to AnnotationScore[] first.
+ *
+ * @param serverAnnotationScores - Pre-transformed annotation scores from server
+ * @param target - Target for cache filtering
+ * @param mode - Describes whether to include child observation scores or only target scores. Defaults to only target scores.
+ * @returns Merged annotation scores with cache overlay
+ */
+export function useMergedAnnotationScores(
+ serverAnnotationScores: AnnotationScore[],
+ target: ScoreTarget,
+ mode: "target-and-child-scores" | "target-scores-only" = "target-scores-only",
+): AnnotationScore[] {
+ const { getAllForTarget, isDeleted } = useScoreCache();
+
+ const cachedScores = getAllForTarget(mode, {
+ traceId: target.type === "trace" ? target.traceId : undefined,
+ observationId: target.type === "trace" ? target.observationId : undefined,
+ sessionId: target.type === "session" ? target.sessionId : undefined,
+ });
+
+ // Build deletedIds Set
+ const deletedIds = useMemo(() => {
+ const ids = new Set<string>();
+ serverAnnotationScores.forEach((s) => {
+ if (s.id && isDeleted(s.id)) ids.add(s.id);
+ });
+ return ids;
+ }, [serverAnnotationScores, isDeleted]);
+
+ return useMemo(
+ () =>
+ mergeAnnotationScoresWithCache(
+ serverAnnotationScores,
+ cachedScores,
+ deletedIds,
+ ),
+ [serverAnnotationScores, cachedScores, deletedIds],
+ );
+}
diff --git a/web/src/features/scores/lib/useMergedScores.ts b/web/src/features/scores/lib/useMergedScores.ts
new file mode 100644
index 0000000000..0994197cb4
--- /dev/null
+++ b/web/src/features/scores/lib/useMergedScores.ts
@@ -0,0 +1,48 @@
+import { useMemo } from "react";
+import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { type ScoreTarget } from "@/src/features/scores/types";
+import { mergeScoresWithCache } from "@/src/features/scores/lib/mergeScoresWithCache";
+import { type APIScoreV2 } from "@langfuse/shared";
+
+/**
+ * Hook for merging server scores with cached scores
+ *
+ * Applies all cache operations to server scores:
+ * - Adds new cache-only scores
+ * - Updates existing scores with cached values
+ * - Removes deleted scores
+ *
+ * Used in trace detail annotation drawer for flat score list.
+ *
+ * @param serverScores - Flat scores from tRPC query
+ * @param target - Target to filter cache by (traceId, observationId, sessionId)
+ * @param mode - Describes whether to include child observation scores or only target scores. Defaults to only target scores.
+ * @returns APIScoreV2[] with all cache operations applied
+ */
+export function useMergedScores(
+ serverScores: APIScoreV2[],
+ target: ScoreTarget,
+ mode: "target-and-child-scores" | "target-scores-only" = "target-scores-only",
+): APIScoreV2[] {
+ const { getAllForTarget, isDeleted } = useScoreCache();
+
+ const cachedScores = getAllForTarget(mode, {
+ traceId: target.type === "trace" ? target.traceId : undefined,
+ observationId: target.type === "trace" ? target.observationId : undefined,
+ sessionId: target.type === "session" ? target.sessionId : undefined,
+ });
+
+ // Build deletedIds Set
+ const deletedIds = useMemo(() => {
+ const ids = new Set<string>();
+ serverScores.forEach((s) => {
+ if (isDeleted(s.id)) ids.add(s.id);
+ });
+ return ids;
+ }, [serverScores, isDeleted]);
+
+ return useMemo(
+ () => mergeScoresWithCache(serverScores, cachedScores, deletedIds),
+ [serverScores, cachedScores, deletedIds],
+ );
+}
diff --git a/web/src/features/scores/schema.ts b/web/src/features/scores/schema.ts
index c7d633022a..b30ddb8547 100644
--- a/web/src/features/scores/schema.ts
+++ b/web/src/features/scores/schema.ts
@@ -3,12 +3,12 @@ import { z } from "zod/v4";
export const AnnotationScoreDataSchema = z.object({
name: z.string(),
- scoreId: z.string().optional(),
- value: z.number().nullable().optional(),
- stringValue: z.string().optional(),
+ id: z.string().nullish(),
+ value: z.number().nullish(),
+ stringValue: z.string().nullish(),
dataType: z.enum(ScoreDataType),
- configId: z.string().optional(),
- comment: z.string().optional(),
+ configId: z.string(),
+ comment: z.string().nullish(),
});
export const AnnotateFormSchema = z.object({
diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.ts
index 0082f232df..a689b4cf6a 100644
--- a/web/src/features/scores/types.ts
+++ b/web/src/features/scores/types.ts
@@ -2,8 +2,10 @@ import { type AnnotationScoreDataSchema } from "@/src/features/scores/schema";
import { type AnnotateFormSchema } from "@/src/features/scores/schema";
import {
type ScoreSourceType,
- type APIScoreV2,
type ScoreDataType,
+ type APIScoreV2,
+ type ScoreAggregate,
+ type ScoreConfigDomain,
} from "@langfuse/shared";
import { type z } from "zod/v4";
@@ -50,20 +52,40 @@ export type TraceScoreTarget = {
export type ScoreTarget = SessionScoreTarget | TraceScoreTarget;
+export type AnnotationScore = {
+ id: string | null;
+ name: string;
+ dataType: ScoreDataType;
+ source: ScoreSourceType;
+ value?: number | null;
+ stringValue?: string | null;
+ configId: string;
+ traceId?: string | null;
+ observationId?: string | null;
+ sessionId?: string | null;
+ comment?: string | null;
+};
+
+type AnalyticsData = {
+ type: "trace" | "session";
+ source:
+ | "TraceDetail"
+ | "SessionDetail"
+ | "AnnotationQueue"
+ | "DatasetCompare";
+};
+
export type AnnotateDrawerProps<Target extends ScoreTarget> = {
projectId: string;
scoreTarget: Target;
scores: APIScoreV2[];
- emptySelectedConfigIds: string[];
- setEmptySelectedConfigIds: (ids: string[]) => void;
- analyticsData?: {
- type: "trace" | "session";
- source: "TraceDetail" | "SessionDetail" | "AnnotationQueue";
+ analyticsData?: AnalyticsData;
+ scoreMetadata: {
+ projectId: string;
+ queueId?: string;
+ environment?: string;
};
- variant?: "button" | "badge";
buttonVariant?: "secondary" | "outline";
- hasGroupedButton?: boolean;
- environment?: string;
};
export type AnnotateFormSchemaType = z.infer<typeof AnnotateFormSchema>;
@@ -77,3 +99,46 @@ export type ScoreColumn = {
source: ScoreSourceType;
dataType: ScoreDataType;
};
+
+export type ScoreConfigSelection =
+ | { mode: "fixed"; configs: ScoreConfigDomain[] }
+ | { mode: "selectable" };
+
+export type AnnotationForm<Target extends ScoreTarget> = {
+ scoreTarget: Target;
+ serverScores: APIScoreV2[] | ScoreAggregate;
+ scoreMetadata: {
+ projectId: string;
+ queueId?: string;
+ environment?: string;
+ };
+ configSelection?: ScoreConfigSelection;
+ analyticsData?: AnalyticsData;
+ actionButtons?: React.ReactNode;
+};
+
+export type AnnotationScoreFormData = {
+ id: string | null;
+ configId: string;
+ name: string;
+ dataType: ScoreDataType;
+ value?: number | null;
+ stringValue?: string | null;
+ comment?: string | null;
+};
+
+export type InnerAnnotationFormProps<Target extends ScoreTarget> = {
+ scoreTarget: Target;
+ initialFormData: AnnotationScoreFormData[];
+ configControl: {
+ configs: ScoreConfigDomain[];
+ allowManualSelection: boolean;
+ };
+ scoreMetadata: {
+ projectId: string;
+ queueId?: string;
+ environment?: string;
+ };
+ analyticsData?: AnalyticsData;
+ actionButtons?: React.ReactNode;
+};
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsx
index ea97a426fd..14811487c3 100644
--- a/web/src/pages/_app.tsx
+++ b/web/src/pages/_app.tsx
@@ -35,6 +35,7 @@ import { ThemeProvider } from "@/src/features/theming/ThemeProvider";
import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";
import { SupportDrawerProvider } from "@/src/features/support-chat/SupportDrawerProvider";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import { ScoreCacheProvider } from "@/src/features/scores/contexts/ScoreCacheContext";
// Check that PostHog is client-side (used to handle Next.js SSR) and that env vars are set
if (
@@ -100,13 +101,15 @@ const MyApp: AppType<{ session: Session | null }> = ({
enableSystem
disableTransitionOnChange
>
- <SupportDrawerProvider defaultOpen={false}>
- <Layout>
- <Component {...pageProps} />
- <UserTracking />
- </Layout>
- </SupportDrawerProvider>
- <BetterStackUptimeStatusMessage />
+ <ScoreCacheProvider>
+ <SupportDrawerProvider defaultOpen={false}>
+ <Layout>
+ <Component {...pageProps} />
+ <UserTracking />
+ </Layout>
+ </SupportDrawerProvider>
+ <BetterStackUptimeStatusMessage />
+ </ScoreCacheProvider>
</ThemeProvider>
</MarkdownContextProvider>
</DetailPageListsProvider>
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/index.tsx
index 083c65e9d7..706d8ce5f3 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/index.tsx
@@ -3,7 +3,7 @@ import { DatasetCompareRunsTable } from "@/src/features/datasets/components/Data
import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
import { FlaskConical, List } from "lucide-react";
import { useRouter } from "next/router";
-import { useState } from "react";
+import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
@@ -18,8 +18,14 @@ import {
getDatasetRunCompareTabs,
} from "@/src/features/navigation/utils/dataset-run-compare-tabs";
import { useDatasetRunsCompare } from "@/src/features/datasets/hooks/useDatasetRunsCompare";
+import {
+ ActiveCellProvider,
+ useActiveCell,
+} from "@/src/features/datasets/contexts/ActiveCellContext";
+import { SidePanel, SidePanelContent } from "@/src/components/ui/side-panel";
+import { AnnotationPanel } from "@/src/features/datasets/components/AnnotationPanel";
-export default function DatasetCompare() {
+function DatasetCompareInternal() {
const router = useRouter();
const capture = usePostHogClientCapture();
const projectId = router.query.projectId as string;
@@ -27,6 +33,7 @@ export default function DatasetCompare() {
const [isCreateExperimentDialogOpen, setIsCreateExperimentDialogOpen] =
useState(false);
+ const [isAnnotationPanelOpen, setIsAnnotationPanelOpen] = useState(false);
const hasExperimentWriteAccess = useHasProjectAccess({
projectId,
@@ -44,6 +51,8 @@ export default function DatasetCompare() {
setLocalRuns,
} = useDatasetRunsCompare(projectId, datasetId);
+ const { activeCell, clearActiveCell } = useActiveCell();
+
const handleExperimentSettled = async (data?: {
success: boolean;
datasetId: string;
@@ -54,7 +63,25 @@ export default function DatasetCompare() {
await handleExperimentSettledBase(data);
};
- if (!runsData.data || !router.isReady || runs.length === 0) {
+ // Clear annotation state on URL change (filters, navigation, etc.)
+ useEffect(() => {
+ clearActiveCell();
+ }, [router.query, clearActiveCell]);
+
+ // Open panel when cell becomes active, close when cleared
+ useEffect(() => {
+ setIsAnnotationPanelOpen(!!activeCell);
+ }, [activeCell]);
+
+ // Clear active cell when panel manually closed
+ const handlePanelOpenChange = (open: boolean) => {
+ if (!open) {
+ clearActiveCell();
+ }
+ setIsAnnotationPanelOpen(open);
+ };
+
+ if (!runsData.data || runs.length === 0) {
return <span>Loading...</span>;
}
@@ -147,13 +174,45 @@ export default function DatasetCompare() {
),
}}
>
- <DatasetCompareRunsTable
- key={runIds?.join(",") ?? "empty"}
- projectId={projectId}
- datasetId={datasetId}
- runIds={runIds ?? []}
- localExperiments={localRuns}
- />
+ <div className="grid flex-1 grid-cols-[1fr,auto] overflow-hidden">
+ <div className="flex h-full flex-col overflow-hidden">
+ <DatasetCompareRunsTable
+ key={runIds?.join(",") ?? "empty"}
+ projectId={projectId}
+ datasetId={datasetId}
+ runIds={runIds ?? []}
+ localExperiments={localRuns}
+ />
+ </div>
+ <SidePanel
+ id="annotation-panel"
+ openState={{
+ open: isAnnotationPanelOpen,
+ onOpenChange: handlePanelOpenChange,
+ }}
+ mobileTitle="Annotate"
+ >
+ <SidePanelContent className="h-full">
+ {activeCell ? (
+ <AnnotationPanel projectId={projectId} />
+ ) : (
+ <div className="flex items-center justify-center p-4">
+ <span className="text-sm text-muted-foreground">
+ Loading annotation data...
+ </span>
+ </div>
+ )}
+ </SidePanelContent>
+ </SidePanel>
+ </div>
</Page>
);
}
+
+export default function DatasetCompare() {
+ return (
+ <ActiveCellProvider>
+ <DatasetCompareInternal />
+ </ActiveCellProvider>
+ );
+}
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 62c2656720..c44372a955 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -346,7 +346,7 @@ export const scoresRouter = createTRPCRouter({
timestamp: new Date(),
}
: {
- id: v4(),
+ id: input.id ?? v4(),
projectId: input.projectId,
environment: input.environment ?? "default",
...inflatedParams,