Skip to content

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

feat(corrections): add corrections to trace and observation preview (#11313)

marliessophie09986a745a16
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index bb58b5e65b..39a700b5a0 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -388,17 +388,20 @@ export const getTraceScoresForDatasetRuns = async (
}));
};
-// Used in multiple places, including the public API, hence the non-default exclusion of metadata via excludeMetadata flag
-export const getScoresForTraces = async <
+const getScoresForTracesInternal = async <
ExcludeMetadata extends boolean,
IncludeHasMetadata extends boolean,
+ DataTypes extends readonly ScoreDataTypeType[],
>(
- props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata>,
+ props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata> & {
+ dataTypes?: DataTypes;
+ },
) => {
const {
projectId,
traceIds,
timestamp,
+ dataTypes,
limit,
offset,
clickhouseConfigs,
@@ -415,7 +418,7 @@ export const getScoresForTraces = async <
from scores s
WHERE s.project_id = {projectId: String}
AND s.trace_id IN ({traceIds: Array(String)})
- AND s.data_type IN ({dataTypes: Array(String)})
+ ${dataTypes ? `AND s.data_type IN ({dataTypes: Array(String)})` : ""}
${timestamp ? `AND s.timestamp >= {traceTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
@@ -437,7 +440,7 @@ export const getScoresForTraces = async <
traceIds,
limit,
offset,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ ...(dataTypes ? { dataTypes: dataTypes.map((d) => d.toString()) } : {}),
...(timestamp
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
@@ -478,6 +481,30 @@ export const getScoresForTraces = async <
});
};
+// Used in multiple places, including the public API, hence the non-default exclusion of metadata via excludeMetadata flag
+export const getScoresForTraces = async <
+ ExcludeMetadata extends boolean,
+ IncludeHasMetadata extends boolean,
+>(
+ props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata>,
+) => {
+ return getScoresForTracesInternal({
+ ...props,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
+ });
+};
+
+export const getScoresAndCorrectionsForTraces = async <
+ ExcludeMetadata extends boolean,
+ IncludeHasMetadata extends boolean,
+>(
+ props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata>,
+) => {
+ return getScoresForTracesInternal({
+ ...props,
+ });
+};
+
export type GetScoresForObservationsProps<
ExcludeMetadata extends boolean,
IncludeHasMetadata extends boolean,
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 1bd2b74d60..4de5c32698 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -483,6 +483,9 @@ export const SessionIO = ({
input={trace.data.input}
output={trace.data.output}
hideIfNull
+ projectId={projectId}
+ traceId={traceId}
+ environment={trace.data.environment}
/>
) : (
<div className="p-2 text-xs text-muted-foreground">
diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsx
index 0962ea6335..cc935eeb65 100644
--- a/web/src/components/table/peek/peek-observation-detail.tsx
+++ b/web/src/components/table/peek/peek-observation-detail.tsx
@@ -36,6 +36,7 @@ export const PeekViewObservationDetail = ({
key={`${trace.data.id}-${peekId}`}
trace={trace.data}
scores={trace.data.scores}
+ corrections={trace.data.corrections}
projectId={trace.data.projectId}
observations={trace.data.observations}
selectedTab={selectedTab}
diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsx
index dc7795b100..b5e3c481ca 100644
--- a/web/src/components/table/peek/peek-trace-detail.tsx
+++ b/web/src/components/table/peek/peek-trace-detail.tsx
@@ -28,6 +28,7 @@ export const PeekViewTraceDetail = ({ projectId }: { projectId: string }) => {
key={trace.data.id}
trace={trace.data}
scores={trace.data.scores}
+ corrections={trace.data.corrections}
projectId={trace.data.projectId}
observations={trace.data.observations}
selectedTab={selectedTab}
diff --git a/web/src/components/trace2/ObservationPreview.tsx b/web/src/components/trace2/ObservationPreview.tsx
index def9511d9d..e86a4d1915 100644
--- a/web/src/components/trace2/ObservationPreview.tsx
+++ b/web/src/components/trace2/ObservationPreview.tsx
@@ -46,11 +46,13 @@ import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansion
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { useParsedObservation } from "@/src/hooks/useParsedObservation";
import { PromptBadge } from "@/src/components/trace2/components/_shared/PromptBadge";
+import { getMostRecentCorrection } from "@/src/features/corrections/utils/getMostRecentCorrection";
export const ObservationPreview = ({
observations,
projectId,
serverScores: scores,
+ corrections,
currentObservationId,
traceId,
commentCounts,
@@ -62,6 +64,7 @@ export const ObservationPreview = ({
observations: Array<ObservationReturnType>;
projectId: string;
serverScores: WithStringifiedMetadata<ScoreDomain>[];
+ corrections: ScoreDomain[];
currentObservationId: string;
traceId: string;
commentCounts?: Map<string, number>;
@@ -95,6 +98,10 @@ export const ObservationPreview = ({
(s) => s.observationId === currentObservationId,
);
+ const currentObservationCorrections = corrections.filter(
+ (c) => c.observationId === currentObservationId,
+ );
+
// Fetch and parse observation input/output in background (Web Worker)
const {
observation: observationWithIO,
@@ -469,6 +476,10 @@ export const ObservationPreview = ({
parsedInput={parsedInput}
parsedOutput={parsedOutput}
parsedMetadata={parsedMetadata}
+ outputCorrection={getMostRecentCorrection(
+ currentObservationCorrections,
+ )}
+ observationId={currentObservationId}
isLoading={isLoadingObservation}
isParsing={isWaitingForParsing}
media={observationMedia.data}
@@ -482,6 +493,9 @@ export const ObservationPreview = ({
onOutputExpansionChange={(expansion) =>
setFieldExpansion("output", expansion)
}
+ projectId={projectId}
+ traceId={traceId}
+ environment={preloadedObservation.environment}
/>
</div>
<div>
diff --git a/web/src/components/trace2/Trace.tsx b/web/src/components/trace2/Trace.tsx
index cc167ba333..30323ea535 100644
--- a/web/src/components/trace2/Trace.tsx
+++ b/web/src/components/trace2/Trace.tsx
@@ -30,6 +30,7 @@ export type TraceProps = {
output: string | null;
};
scores: WithStringifiedMetadata<ScoreDomain>[];
+ corrections: ScoreDomain[];
projectId: string;
viewType?: "detailed" | "focused";
context?: "peek" | "fullscreen";
@@ -45,6 +46,7 @@ export function Trace({
trace,
observations,
scores,
+ corrections,
projectId,
context,
}: TraceProps) {
@@ -69,6 +71,7 @@ export function Trace({
trace={trace}
observations={observations}
serverScores={scores}
+ corrections={corrections}
comments={commentsMap}
>
<TraceGraphDataProvider
diff --git a/web/src/components/trace2/TracePage.tsx b/web/src/components/trace2/TracePage.tsx
index 00697544b1..a6f2edf1fd 100644
--- a/web/src/components/trace2/TracePage.tsx
+++ b/web/src/components/trace2/TracePage.tsx
@@ -183,6 +183,7 @@ export function TracePage({
<Trace
trace={trace.data}
scores={trace.data.scores}
+ corrections={trace.data.corrections}
projectId={trace.data.projectId}
observations={trace.data.observations}
selectedTab={selectedTab}
diff --git a/web/src/components/trace2/TracePreview.tsx b/web/src/components/trace2/TracePreview.tsx
index b2a2ab6e01..9be78dd65a 100644
--- a/web/src/components/trace2/TracePreview.tsx
+++ b/web/src/components/trace2/TracePreview.tsx
@@ -48,6 +48,7 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/src/components/ui/tooltip";
+import { getMostRecentCorrection } from "@/src/features/corrections/utils/getMostRecentCorrection";
import TagList from "@/src/features/tag/components/TagList";
import {
AlertDialog,
@@ -68,6 +69,7 @@ export const TracePreview = ({
trace,
observations,
serverScores: scores,
+ corrections,
commentCounts,
viewType = "detailed",
showCommentButton = false,
@@ -80,6 +82,7 @@ export const TracePreview = ({
};
observations: ObservationReturnTypeWithMetadata[];
serverScores: WithStringifiedMetadata<ScoreDomain>[];
+ corrections: ScoreDomain[];
commentCounts?: Map<string, number>;
viewType?: "detailed" | "focused";
showCommentButton?: boolean;
@@ -116,6 +119,12 @@ export const TracePreview = ({
},
);
+ const traceCorrections = corrections.filter(
+ (c) => c.traceId === trace.id && c.observationId === null,
+ );
+
+ const outputCorrection = getMostRecentCorrection(traceCorrections);
+
// Parse trace I/O in background (Web Worker)
const { parsedInput, parsedOutput, parsedMetadata, isParsing } =
useParsedTrace({
@@ -425,6 +434,7 @@ export const TracePreview = ({
key={trace.id + "-io"}
input={trace.input ?? undefined}
output={trace.output ?? undefined}
+ outputCorrection={outputCorrection}
parsedInput={parsedInput}
parsedOutput={parsedOutput}
parsedMetadata={parsedMetadata}
@@ -440,6 +450,9 @@ export const TracePreview = ({
onOutputExpansionChange={(expansion) =>
setFieldExpansion("output", expansion)
}
+ projectId={trace.projectId}
+ traceId={trace.id}
+ environment={trace.environment}
/>
{trace.tags.length > 0 && (
@@ -475,6 +488,7 @@ export const TracePreview = ({
trace={trace}
observations={observations}
serverScores={scores}
+ corrections={corrections}
comments={commentCounts ?? new Map()}
>
<ViewPreferencesProvider>
diff --git a/web/src/components/trace2/components/IOPreview/IOPreview.tsx b/web/src/components/trace2/components/IOPreview/IOPreview.tsx
index 8a370e1e05..0a946a1b58 100644
--- a/web/src/components/trace2/components/IOPreview/IOPreview.tsx
+++ b/web/src/components/trace2/components/IOPreview/IOPreview.tsx
@@ -1,5 +1,5 @@
import { useEffect } from "react";
-import { type Prisma } from "@langfuse/shared";
+import { type ScoreDomain, type Prisma } from "@langfuse/shared";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import useLocalStorage from "@/src/components/useLocalStorage";
import usePreserveRelativeScroll from "@/src/hooks/usePreserveRelativeScroll";
@@ -33,6 +33,7 @@ export interface IOPreviewProps extends ExpansionStateProps {
input?: Prisma.JsonValue;
output?: Prisma.JsonValue;
metadata?: Prisma.JsonValue;
+ outputCorrection?: ScoreDomain;
// Pre-parsed data (optional, from useParsedObservation hook for performance)
parsedInput?: unknown;
parsedOutput?: unknown;
@@ -51,6 +52,11 @@ export interface IOPreviewProps extends ExpansionStateProps {
showMetadata?: boolean;
// Callback to inform parent if virtualization is being used (for scroll handling)
onVirtualizationChange?: (isVirtualized: boolean) => void;
+ // For CorrectedOutputField
+ observationId?: string;
+ projectId: string;
+ traceId: string;
+ environment?: string;
}
/**
@@ -69,6 +75,7 @@ export interface IOPreviewProps extends ExpansionStateProps {
export function IOPreview({
input,
output,
+ outputCorrection,
metadata,
parsedInput,
parsedOutput,
@@ -88,6 +95,10 @@ export function IOPreview({
setIsPrettyViewAvailable,
showMetadata = false,
onVirtualizationChange,
+ observationId,
+ projectId,
+ traceId,
+ environment = "default",
}: IOPreviewProps) {
const capture = usePostHogClientCapture();
const [dismissedTraceViewNotifications, setDismissedTraceViewNotifications] =
@@ -121,6 +132,7 @@ export function IOPreview({
const sharedProps = {
input,
output,
+ outputCorrection,
metadata,
parsedInput,
parsedOutput,
@@ -135,6 +147,10 @@ export function IOPreview({
outputExpansionState,
onInputExpansionChange,
onOutputExpansionChange,
+ observationId,
+ projectId,
+ traceId,
+ environment,
};
// Only show empty state popup for traces (not observations) when there's no input/output
@@ -174,6 +190,7 @@ export function IOPreview({
parsedInput={parsedInput}
parsedOutput={parsedOutput}
parsedMetadata={parsedMetadata}
+ outputCorrection={outputCorrection}
isParsing={isParsing}
hideIfNull={hideIfNull}
hideInput={hideInput}
@@ -184,6 +201,10 @@ export function IOPreview({
onInputExpansionChange={onInputExpansionChange}
onOutputExpansionChange={onOutputExpansionChange}
onVirtualizationChange={onVirtualizationChange}
+ observationId={observationId}
+ projectId={projectId}
+ traceId={traceId}
+ environment={environment}
/>
) : selectedView === "json" ? (
<IOPreviewJSONSimple {...sharedProps} />
diff --git a/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx b/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx
index 6ccdc18cf6..6f025d5122 100644
--- a/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx
+++ b/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx
@@ -16,10 +16,13 @@ import {
HoverCardContent,
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
+import { type ScoreDomain } from "@langfuse/shared";
+import { CorrectedOutputField } from "./components/CorrectedOutputField";
const VIRTUALIZATION_THRESHOLD = 3333;
export interface IOPreviewJSONProps extends ExpansionStateProps {
+ outputCorrection?: ScoreDomain;
// Pre-parsed data (from useParsedObservation hook)
parsedInput?: unknown;
parsedOutput?: unknown;
@@ -32,6 +35,10 @@ export interface IOPreviewJSONProps extends ExpansionStateProps {
media?: MediaReturnType[];
// Callback to inform parent if virtualization is being used (for scroll handling)
onVirtualizationChange?: (isVirtualized: boolean) => void;
+ observationId?: string;
+ projectId: string;
+ traceId: string;
+ environment?: string;
}
/**
@@ -50,12 +57,17 @@ export function IOPreviewJSON({
parsedInput,
parsedOutput,
parsedMetadata,
+ outputCorrection,
isParsing = false,
hideIfNull = false,
hideOutput = false,
hideInput = false,
media,
onVirtualizationChange,
+ observationId,
+ projectId,
+ traceId,
+ environment = "default",
}: IOPreviewJSONProps) {
const { resolvedTheme } = useTheme();
const isDark = resolvedTheme === "dark";
@@ -383,6 +395,14 @@ export function IOPreviewJSON({
indentSize: 12,
}}
/>
+ <CorrectedOutputField
+ actualOutput={parsedOutput}
+ existingCorrection={outputCorrection}
+ observationId={observationId}
+ projectId={projectId}
+ traceId={traceId}
+ environment={environment}
+ />
</div>
</div>
);
diff --git a/web/src/components/trace2/components/IOPreview/IOPreviewJSONSimple.tsx b/web/src/components/trace2/components/IOPreview/IOPreviewJSONSimple.tsx
index 15d815b647..556dc2eca7 100644
--- a/web/src/components/trace2/components/IOPreview/IOPreviewJSONSimple.tsx
+++ b/web/src/components/trace2/components/IOPreview/IOPreviewJSONSimple.tsx
@@ -1,13 +1,15 @@
import { useMemo } from "react";
-import { type Prisma, deepParseJson } from "@langfuse/shared";
+import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { type MediaReturnType } from "@/src/features/media/validation";
import { type ExpansionStateProps } from "./IOPreview";
+import { CorrectedOutputField } from "./components/CorrectedOutputField";
export interface IOPreviewJSONSimpleProps extends ExpansionStateProps {
input?: Prisma.JsonValue;
output?: Prisma.JsonValue;
metadata?: Prisma.JsonValue;
+ outputCorrection?: ScoreDomain;
// Pre-parsed data (optional, from useParsedObservation hook for performance)
parsedInput?: unknown;
parsedOutput?: unknown;
@@ -18,6 +20,10 @@ export interface IOPreviewJSONSimpleProps extends ExpansionStateProps {
media?: MediaReturnType[];
hideOutput?: boolean;
hideInput?: boolean;
+ observationId?: string;
+ projectId: string;
+ traceId: string;
+ environment?: string;
}
/**
@@ -33,6 +39,7 @@ export function IOPreviewJSONSimple({
input,
output,
metadata,
+ outputCorrection,
parsedInput,
parsedOutput,
parsedMetadata,
@@ -46,6 +53,10 @@ export function IOPreviewJSONSimple({
outputExpansionState,
onInputExpansionChange,
onOutputExpansionChange,
+ observationId,
+ projectId,
+ traceId,
+ environment = "default",
}: IOPreviewJSONSimpleProps) {
// Parse data if not pre-parsed
// IMPORTANT: Don't parse while isParsing=true to avoid double-parsing with different object references
@@ -96,6 +107,14 @@ export function IOPreviewJSONSimple({
onExternalExpansionChange={onOutputExpansionChange}
/>
)}
+ <CorrectedOutputField
+ actualOutput={effectiveOutput}
+ existingCorrection={outputCorrection}
+ observationId={observationId}
+ projectId={projectId}
+ traceId={traceId}
+ environment={environment}
+ />
{showMetadata && (
<PrettyJsonView
title="Metadata"
diff --git a/web/src/components/trace2/components/IOPreview/IOPreviewPretty.tsx b/web/src/components/trace2/components/IOPreview/IOPreviewPretty.tsx
index 03438b3b0f..3508c16c69 100644
--- a/web/src/components/trace2/components/IOPreview/IOPreviewPretty.tsx
+++ b/web/src/components/trace2/components/IOPreview/IOPreviewPretty.tsx
@@ -1,5 +1,5 @@
import { useMemo } from "react";
-import { type Prisma, deepParseJson } from "@langfuse/shared";
+import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";
import { type MediaReturnType } from "@/src/features/media/validation";
@@ -8,6 +8,7 @@ import { useChatMLParser } from "./hooks/useChatMLParser";
import { ChatMessageList } from "./components/ChatMessageList";
import { SectionToolDefinitions } from "./components/SectionToolDefinitions";
import { type ExpansionStateProps } from "./IOPreview";
+import { CorrectedOutputField } from "./components/CorrectedOutputField";
interface JsonInputOutputViewProps {
parsedInput: unknown;
@@ -79,6 +80,7 @@ export interface IOPreviewPrettyProps extends ExpansionStateProps {
input?: Prisma.JsonValue;
output?: Prisma.JsonValue;
metadata?: Prisma.JsonValue;
+ outputCorrection?: ScoreDomain;
// Pre-parsed data (optional, from useParsedObservation hook for performance)
parsedInput?: unknown;
parsedOutput?: unknown;
@@ -92,6 +94,10 @@ export interface IOPreviewPrettyProps extends ExpansionStateProps {
hideInput?: boolean;
// Whether to show metadata section (default: false)
showMetadata?: boolean;
+ observationId?: string;
+ projectId: string;
+ traceId: string;
+ environment?: string;
}
/**
@@ -110,6 +116,7 @@ export function IOPreviewPretty({
input,
output,
metadata,
+ outputCorrection,
parsedInput: preParsedInput,
parsedOutput: preParsedOutput,
parsedMetadata: preParsedMetadata,
@@ -125,6 +132,10 @@ export function IOPreviewPretty({
onInputExpansionChange,
onOutputExpansionChange,
showMetadata = false,
+ observationId,
+ projectId,
+ traceId,
+ environment = "default",
}: IOPreviewPrettyProps) {
// Use pre-parsed data if available (from useParsedObservation hook),
// otherwise parse with size/depth limits to prevent UI freeze
@@ -244,9 +255,29 @@ export function IOPreviewPretty({
messageToToolCallNumbers={messageToToolCallNumbers}
inputMessageCount={inputMessageCount}
/>
+ <CorrectedOutputField
+ actualOutput={parsedOutput}
+ existingCorrection={outputCorrection}
+ observationId={observationId}
+ projectId={projectId}
+ traceId={traceId}
+ environment={environment}
+ />
</div>
) : (
- <JsonInputOutputView {...jsonViewProps} />
+ <>
+ <JsonInputOutputView {...jsonViewProps} />
+ <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">
+ <CorrectedOutputField
+ actualOutput={parsedOutput}
+ existingCorrection={outputCorrection}
+ observationId={observationId}
+ projectId={projectId}
+ traceId={traceId}
+ environment={environment}
+ />
+ </div>
+ </>
)}
{/* Metadata Section */}
diff --git a/web/src/components/trace2/components/IOPreview/components/CorrectedOutputField.tsx b/web/src/components/trace2/components/IOPreview/components/CorrectedOutputField.tsx
new file mode 100644
index 0000000000..21eb5ebe10
--- /dev/null
+++ b/web/src/components/trace2/components/IOPreview/components/CorrectedOutputField.tsx
@@ -0,0 +1,160 @@
+import { Pencil, Trash } from "lucide-react";
+import { cn } from "@/src/utils/tailwind";
+import { Button } from "@/src/components/ui/button";
+import { type ScoreDomain } from "@langfuse/shared";
+import { useCorrectionData } from "./hooks/useCorrectionData";
+import { useCorrectionMutations } from "./hooks/useCorrectionMutations";
+import { useCorrectionEditor } from "./hooks/useCorrectionEditor";
+import { useMemo } from "react";
+import { CodeMirrorEditor } from "@/src/components/editor/CodeMirrorEditor";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+
+interface CorrectedOutputFieldProps {
+ projectId: string;
+ traceId: string;
+ environment: string;
+ actualOutput?: unknown;
+ existingCorrection?: ScoreDomain | null;
+ observationId?: string;
+}
+
+export function CorrectedOutputField({
+ actualOutput,
+ existingCorrection,
+ observationId,
+ projectId,
+ traceId,
+ environment = "default",
+}: CorrectedOutputFieldProps) {
+ const hasAccess = useHasProjectAccess({ projectId, scope: "scores:CUD" });
+
+ // Merge cache + server data
+ const { effectiveCorrection, correctionValue } = useCorrectionData(
+ existingCorrection,
+ observationId,
+ traceId,
+ );
+
+ // Handle mutations with optimistic updates
+ const { saveStatus, setSaveStatus, handleSave, handleDelete } =
+ useCorrectionMutations({
+ projectId,
+ traceId,
+ observationId,
+ environment,
+ effectiveCorrection,
+ });
+
+ // Manage editor state & debouncing
+ const { isEditing, value, isValidJson, handleEdit, handleChange } =
+ useCorrectionEditor({
+ correctionValue,
+ actualOutput,
+ onSave: handleSave,
+ setSaveStatus,
+ });
+
+ const hasContent = value.trim().length > 0;
+
+ // Format JSON for display
+ const displayValue = useMemo(() => {
+ if (!value) return "";
+ try {
+ const parsed = JSON.parse(value);
+ return JSON.stringify(parsed, null, 2);
+ } catch {
+ // If JSON parsing fails, return the raw value (don't clear it)
+ return value;
+ }
+ }, [value]);
+
+ const handleEditorChange = (newValue: string) => {
+ handleChange(newValue);
+ };
+
+ return (
+ <div className="px-2">
+ <div className="group relative rounded-md">
+ <div className="flex items-center justify-between bg-muted/30 py-1.5">
+ <span className="text-sm font-medium">Corrected Output (Beta)</span>
+ <div className="-mr-1 flex items-center -space-x-1 opacity-0 transition-opacity group-hover:opacity-100">
+ {!isValidJson && isEditing && hasContent && (
+ <span className="mr-2 text-xs text-red-500">
+ Invalid JSON - fix to save
+ </span>
+ )}
+ {isValidJson &&
+ saveStatus === "idle" &&
+ isEditing &&
+ hasContent && (
+ <span className="mr-2 text-xs text-muted-foreground">
+ DRAFT - Type any character to save
+ </span>
+ )}
+ {isValidJson && saveStatus === "saving" && (
+ <span className="mr-2 text-xs text-muted-foreground">
+ Saving...
+ </span>
+ )}
+ {isValidJson && saveStatus === "saved" && (
+ <span className="mr-2 text-xs">Saved ✓</span>
+ )}
+ {hasContent && !isEditing && (
+ <>
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ onClick={handleEdit}
+ disabled={!hasAccess}
+ className="hover:bg-border"
+ title="Edit corrected output"
+ >
+ <Pencil className="h-3 w-3" />
+ </Button>
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ onClick={handleDelete}
+ disabled={!hasAccess}
+ className="hover:bg-border"
+ title="Delete corrected output"
+ >
+ <Trash className="h-3 w-3" />
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+
+ {!hasContent && !isEditing ? (
+ <button
+ onClick={handleEdit}
+ disabled={!hasAccess}
+ className={cn(
+ "w-full cursor-pointer rounded-md border px-3 py-8 text-center text-sm text-muted-foreground transition-colors hover:bg-muted/50",
+ )}
+ >
+ Click to add corrected output
+ </button>
+ ) : isEditing ? (
+ <CodeMirrorEditor
+ value={displayValue}
+ onChange={handleEditorChange}
+ mode="json"
+ minHeight={200}
+ placeholder="Enter corrected output as JSON..."
+ className="bg-accent-light-green"
+ />
+ ) : (
+ <CodeMirrorEditor
+ value={displayValue}
+ mode="json"
+ minHeight={200}
+ editable={false}
+ className="bg-accent-light-green"
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/components/trace2/components/IOPreview/components/hooks/index.ts b/web/src/components/trace2/components/IOPreview/components/hooks/index.ts
new file mode 100644
index 0000000000..98133b6f67
--- /dev/null
+++ b/web/src/components/trace2/components/IOPreview/components/hooks/index.ts
@@ -0,0 +1,3 @@
+export { useCorrectionData } from "./useCorrectionData";
+export { useCorrectionMutations } from "./useCorrectionMutations";
+export { useCorrectionEditor } from "./useCorrectionEditor";
diff --git a/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionData.ts b/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionData.ts
new file mode 100644
index 0000000000..2c22db5a73
--- /dev/null
+++ b/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionData.ts
@@ -0,0 +1,75 @@
+import { useMemo } from "react";
+import { useCorrectionCache } from "@/src/features/corrections/contexts/CorrectionCacheContext";
+import { type ScoreDomain } from "@langfuse/shared";
+
+/**
+ * Merges cached correction with server data
+ * Cache takes precedence for optimistic updates (includes full value)
+ * Falls back to server data when cache is empty
+ */
+export function useCorrectionData(
+ existingCorrection: ScoreDomain | null | undefined,
+ observationId: string | undefined,
+ traceId: string,
+) {
+ const correctionCache = useCorrectionCache();
+
+ // Get cached correction - for observation or trace level
+ // NOTE: getForObservation/getForTrace filter out deleted items
+ const cachedMeta = useMemo(() => {
+ if (observationId) {
+ return correctionCache.getForObservation(traceId, observationId);
+ }
+ return correctionCache.getForTrace(traceId);
+ }, [correctionCache, observationId, traceId]);
+
+ // Merge: cache is source of truth, always prefer cache over server
+ const effectiveCorrection = useMemo(() => {
+ // 1. If cache exists (new/edited/being saved), use cache as source of truth
+ if (cachedMeta) {
+ return {
+ ...existingCorrection,
+ id: cachedMeta.id,
+ timestamp: cachedMeta.timestamp,
+ longStringValue: cachedMeta.value, // Use cached value for optimistic updates
+ } as ScoreDomain;
+ }
+
+ // 2. If server correction is marked as deleted, return null
+ if (
+ existingCorrection?.id &&
+ correctionCache.isDeleted(existingCorrection.id)
+ ) {
+ return null;
+ }
+
+ // 3. Otherwise, use server correction
+ return existingCorrection;
+ }, [cachedMeta, existingCorrection, correctionCache]);
+
+ // Check if deleted - check server correction ID since that's what we delete
+ const isDeleted = useMemo(() => {
+ return existingCorrection?.id
+ ? correctionCache.isDeleted(existingCorrection.id)
+ : false;
+ }, [existingCorrection?.id, correctionCache]);
+
+ // Extract value - prefer cached value (optimistic) over server value
+ const correctionValue = useMemo(() => {
+ // If deleted, return empty string
+ if (isDeleted) {
+ return "";
+ }
+ // If we have cached value, use it (optimistic update)
+ if (cachedMeta?.value !== undefined) {
+ return cachedMeta.value;
+ }
+ // Otherwise use server value
+ return existingCorrection?.longStringValue ?? "";
+ }, [cachedMeta, existingCorrection, isDeleted]);
+
+ return {
+ effectiveCorrection,
+ correctionValue,
+ };
+}
diff --git a/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionEditor.ts b/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionEditor.ts
new file mode 100644
index 0000000000..bf7c1e4c00
--- /dev/null
+++ b/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionEditor.ts
@@ -0,0 +1,100 @@
+import { useState, useRef, useEffect, useCallback } from "react";
+
+interface UseCorrectionEditorParams {
+ correctionValue: string;
+ actualOutput: unknown;
+ onSave: (value: string) => void;
+ setSaveStatus: (status: "idle" | "saving" | "saved") => void;
+ debounceMs?: number;
+}
+
+/**
+ * Manages correction editor state, debouncing, and auto-save
+ */
+export function useCorrectionEditor({
+ correctionValue,
+ actualOutput,
+ onSave,
+ setSaveStatus,
+ debounceMs = 500,
+}: UseCorrectionEditorParams) {
+ const [isEditing, setIsEditing] = useState(false);
+ const [value, setValue] = useState(correctionValue);
+ const [isValidJson, setIsValidJson] = useState(true);
+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ // Sync local value with correctionValue from cache/server
+ // This includes handling deletions (correctionValue becomes empty string)
+ useEffect(() => {
+ setValue(correctionValue);
+ }, [correctionValue]);
+
+ const handleEdit = useCallback(() => {
+ setIsEditing(true);
+ // Prepopulate with actual output if no existing correction
+ if (!value && actualOutput) {
+ try {
+ // Store as JSON string (not stringified string)
+ const jsonValue =
+ typeof actualOutput === "string"
+ ? actualOutput
+ : JSON.stringify(actualOutput);
+ setValue(jsonValue);
+ } catch {
+ setValue(String(actualOutput));
+ }
+ }
+ // Focus textarea after it renders
+ setTimeout(() => textareaRef.current?.focus(), 0);
+ }, [value, actualOutput]);
+
+ const handleChange = useCallback(
+ (newValue: string) => {
+ // Update local state immediately for responsive typing
+ setValue(newValue);
+
+ // Validate JSON
+ let valid = false;
+ try {
+ if (newValue.trim()) {
+ JSON.parse(newValue);
+ valid = true;
+ }
+ } catch {
+ valid = false;
+ }
+ setIsValidJson(valid);
+
+ // Only save if valid JSON
+ if (valid) {
+ setSaveStatus("saving");
+
+ // Clear existing timeout
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+
+ // Debounced save - triggers mutation (which updates cache) after 500ms
+ timeoutRef.current = setTimeout(() => {
+ onSave(newValue);
+ }, debounceMs);
+ } else {
+ setSaveStatus("idle");
+ // Clear timeout if JSON becomes invalid
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ }
+ },
+ [onSave, setSaveStatus, debounceMs],
+ );
+
+ return {
+ isEditing,
+ value,
+ isValidJson,
+ handleEdit,
+ handleChange,
+ };
+}
diff --git a/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionMutations.ts b/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionMutations.ts
new file mode 100644
index 0000000000..a2b73d631b
--- /dev/null
+++ b/web/src/components/trace2/components/IOPreview/components/hooks/useCorrectionMutations.ts
@@ -0,0 +1,139 @@
+import { useState, useCallback } from "react";
+import { api } from "@/src/utils/api";
+import { useCorrectionCache } from "@/src/features/corrections/contexts/CorrectionCacheContext";
+import { type ScoreDomain } from "@langfuse/shared";
+import { toast } from "sonner";
+import { v4 } from "uuid";
+
+interface UseCorrectionMutationsParams {
+ projectId: string;
+ traceId: string;
+ observationId: string | undefined;
+ environment: string | undefined;
+ effectiveCorrection:
+ | Pick<ScoreDomain, "id" | "longStringValue" | "timestamp">
+ | null
+ | undefined;
+}
+
+/**
+ * Handles correction save/delete mutations with optimistic updates
+ */
+export function useCorrectionMutations({
+ projectId,
+ traceId,
+ observationId,
+ environment,
+ effectiveCorrection,
+}: UseCorrectionMutationsParams) {
+ const correctionCache = useCorrectionCache();
+ const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved">(
+ "idle",
+ );
+
+ const upsertMutation = api.scores.upsertCorrection.useMutation({
+ onMutate: async (variables) => {
+ // Get previous cache value for rollback
+ const previousValue = correctionCache.get(variables.id);
+
+ // Write to cache with full value for optimistic updates
+ correctionCache.set(variables.id, {
+ id: variables.id,
+ timestamp: variables.timestamp,
+ projectId,
+ traceId,
+ observationId: observationId ?? null,
+ environment,
+ value: variables.value, // Store full value
+ });
+
+ setSaveStatus("saving");
+ return { previousValue, id: variables.id };
+ },
+ onError: (error, _, context) => {
+ if (!context?.id) return;
+
+ if (context.previousValue) {
+ // Restore previous value
+ correctionCache.set(context.id, context.previousValue);
+ } else {
+ // No previous value - rollback optimistic create
+ correctionCache.rollbackSet(context.id);
+ }
+ setSaveStatus("idle");
+ },
+ onSuccess: () => {
+ setSaveStatus("saved");
+ },
+ });
+
+ const deleteMutation = api.scores.deleteAnnotationScore.useMutation({
+ onMutate: async () => {
+ if (!effectiveCorrection) return;
+
+ // Get previous cache value for rollback
+ const previousValue = correctionCache.get(effectiveCorrection.id);
+
+ // Mark as deleted in cache (optimistic delete)
+ correctionCache.delete(effectiveCorrection.id);
+
+ return { previousValue, correctionId: effectiveCorrection.id };
+ },
+ onError: (error, _, context) => {
+ toast.error("Failed to delete correction");
+ // Rollback delete - restore to cache if we had a previous value
+ if (context?.correctionId) {
+ correctionCache.rollbackDelete(
+ context.correctionId,
+ context.previousValue,
+ );
+ }
+ },
+ });
+
+ const handleSave = useCallback(
+ (value: string) => {
+ const isDeleted = correctionCache.isDeleted(
+ effectiveCorrection?.id ?? "",
+ );
+
+ upsertMutation.mutate({
+ projectId,
+ id: isDeleted ? v4() : (effectiveCorrection?.id ?? v4()),
+ environment,
+ traceId,
+ observationId,
+ value,
+ timestamp: isDeleted
+ ? new Date()
+ : (effectiveCorrection?.timestamp ?? new Date()),
+ });
+ },
+ [
+ projectId,
+ traceId,
+ observationId,
+ environment,
+ effectiveCorrection?.id,
+ effectiveCorrection?.timestamp,
+ upsertMutation,
+ correctionCache,
+ ],
+ );
+
+ const handleDelete = useCallback(() => {
+ if (!effectiveCorrection) return;
+ deleteMutation.mutate({
+ projectId,
+ id: effectiveCorrection.id,
+ });
+ }, [projectId, effectiveCorrection, deleteMutation]);
+
+ return {
+ saveStatus,
+ setSaveStatus,
+ handleSave,
+ handleDelete,
+ isDeleting: deleteMutation.isPending,
+ };
+}
diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
index 1bf21d3b43..76eccd6fc7 100644
--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
@@ -28,6 +28,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { useMemo, useState } from "react";
import ScoresTable from "@/src/components/table/use-cases/scores";
import { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";
+import { getMostRecentCorrection } from "@/src/features/corrections/utils/getMostRecentCorrection";
import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";
import { useMedia } from "@/src/components/trace2/api/useMedia";
import { useSelection } from "@/src/components/trace2/contexts/SelectionContext";
@@ -74,15 +75,19 @@ export function ObservationDetailView({
const currentView = jsonViewPreference;
const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);
- const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false);
-
- // Get comments, scores, and expansion state from contexts
- const { comments, serverScores: scores } = useTraceData();
+ const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false); // Get comments, scores, corrections, and expansion state from contexts
+ const { comments, serverScores: scores, corrections } = useTraceData();
const { expansionState, setFieldExpansion } = useJsonExpansion();
const observationScores = useMemo(
() => scores.filter((s) => s.observationId === observation.id),
[scores, observation.id],
);
+ const observationCorrections = useMemo(
+ () => corrections.filter((c) => c.observationId === observation.id),
+ [corrections, observation.id],
+ );
+
+ const outputCorrection = getMostRecentCorrection(observationCorrections);
// Fetch and parse observation input/output in background (Web Worker)
// This combines tRPC fetch + non-blocking JSON parsing
@@ -190,6 +195,7 @@ export function ObservationDetailView({
observationName={observation.name ?? undefined}
input={observationWithIOCompat.data?.input ?? undefined}
output={observationWithIOCompat.data?.output ?? undefined}
+ outputCorrection={outputCorrection}
metadata={observationWithIOCompat.data?.metadata ?? undefined}
parsedInput={parsedInput}
parsedOutput={parsedOutput}
@@ -206,7 +212,11 @@ export function ObservationDetailView({
setFieldExpansion("output", exp)
}
showMetadata
+ observationId={observation.id}
onVirtualizationChange={setIsJSONBetaVirtualized}
+ projectId={projectId}
+ traceId={traceId}
+ environment={observation.environment}
/>
{currentView !== "json-beta" && (
<div className="h-4 w-full flex-shrink-0" />
diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx
index e50d3c7aa3..4e8bfea68b 100644
--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx
@@ -42,6 +42,7 @@ import { TraceDetailViewHeader } from "./TraceDetailViewHeader";
import { TraceLogView } from "../TraceLogView/TraceLogView";
import { TRACE_VIEW_CONFIG } from "@/src/components/trace2/config/trace-view-config";
import ScoresTable from "@/src/components/table/use-cases/scores";
+import { getMostRecentCorrection } from "@/src/features/corrections/utils/getMostRecentCorrection";
export interface TraceDetailViewProps {
trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {
@@ -50,6 +51,7 @@ export interface TraceDetailViewProps {
output: string | null;
};
observations: ObservationReturnTypeWithMetadata[];
+ corrections: ScoreDomain[];
scores: WithStringifiedMetadata<ScoreDomain>[];
projectId: string;
}
@@ -58,6 +60,7 @@ export function TraceDetailView({
trace,
observations,
scores,
+ corrections,
projectId,
}: TraceDetailViewProps) {
// Tab and view state from URL (via SelectionContext)
@@ -93,6 +96,13 @@ export function TraceDetailView({
[scores],
);
+ const traceCorrections = useMemo(
+ () => corrections.filter((c) => !c.observationId),
+ [corrections],
+ );
+
+ const outputCorrection = getMostRecentCorrection(traceCorrections);
+
const showLogViewTab = observations.length > 0;
// Check if log view will be virtualized (affects JSON tab availability)
@@ -277,6 +287,7 @@ export function TraceDetailView({
input={trace.input ?? undefined}
output={trace.output ?? undefined}
metadata={trace.metadata ?? undefined}
+ outputCorrection={outputCorrection}
parsedInput={parsedInput}
parsedOutput={parsedOutput}
parsedMetadata={parsedMetadata}
@@ -292,6 +303,9 @@ export function TraceDetailView({
}
showMetadata
onVirtualizationChange={setIsJSONBetaVirtualized}
+ projectId={projectId}
+ traceId={trace.id}
+ environment={trace.environment}
/>
</div>
</TabsBarContent>
diff --git a/web/src/components/trace2/components/_layout/TracePanelDetail.tsx b/web/src/components/trace2/components/_layout/TracePanelDetail.tsx
index 72fcce21b1..e124216440 100644
--- a/web/src/components/trace2/components/_layout/TracePanelDetail.tsx
+++ b/web/src/components/trace2/components/_layout/TracePanelDetail.tsx
@@ -23,7 +23,13 @@ import { useMemo } from "react";
export function TracePanelDetail() {
const { selectedNodeId } = useSelection();
- const { trace, nodeMap, observations, serverScores: scores } = useTraceData();
+ const {
+ trace,
+ nodeMap,
+ observations,
+ serverScores: scores,
+ corrections,
+ } = useTraceData();
// Memoize to prevent recreation when deps haven't changed
const content = useMemo(() => {
@@ -61,10 +67,11 @@ export function TracePanelDetail() {
trace={trace}
observations={observations}
scores={scores}
+ corrections={corrections}
projectId={trace.projectId}
/>
);
- }, [selectedNodeId, nodeMap, trace, observations, scores]);
+ }, [selectedNodeId, nodeMap, trace, observations, scores, corrections]);
return (
<div className="h-full w-full overflow-y-auto bg-background">{content}</div>
diff --git a/web/src/components/trace2/contexts/TraceDataContext.tsx b/web/src/components/trace2/contexts/TraceDataContext.tsx
index 136c5c5f1b..7028aa4dd5 100644
--- a/web/src/components/trace2/contexts/TraceDataContext.tsx
+++ b/web/src/components/trace2/contexts/TraceDataContext.tsx
@@ -33,6 +33,7 @@ interface TraceDataContextValue {
observations: ObservationReturnTypeWithMetadata[];
serverScores: WithStringifiedMetadata<ScoreDomain>[];
mergedScores: WithStringifiedMetadata<ScoreDomain>[];
+ corrections: ScoreDomain[];
tree: TreeNode;
nodeMap: Map<string, TreeNode>;
searchItems: TraceSearchListItem[];
@@ -54,6 +55,7 @@ interface TraceDataProviderProps {
trace: TraceType;
observations: ObservationReturnTypeWithMetadata[];
serverScores: WithStringifiedMetadata<ScoreDomain>[];
+ corrections: ScoreDomain[];
comments: Map<string, number>;
children: ReactNode;
}
@@ -66,6 +68,7 @@ export function TraceDataProvider({
trace,
observations,
serverScores,
+ corrections,
comments,
children,
}: TraceDataProviderProps) {
@@ -91,13 +94,22 @@ export function TraceDataProvider({
observations,
serverScores: serverScores,
mergedScores,
+ corrections,
tree: uiData.tree,
nodeMap: uiData.nodeMap,
searchItems: uiData.searchItems,
hiddenObservationsCount: uiData.hiddenObservationsCount,
comments,
}),
- [trace, observations, serverScores, mergedScores, uiData, comments],
+ [
+ trace,
+ observations,
+ serverScores,
+ mergedScores,
+ corrections,
+ uiData,
+ comments,
+ ],
);
return (
diff --git a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
index bca0f0dacd..06658373e1 100644
--- a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
@@ -111,6 +111,7 @@ export const TraceAnnotationProcessor: React.FC<
key={data.id}
trace={data}
serverScores={data.scores}
+ corrections={data.corrections}
observations={data.observations}
viewType="focused"
showCommentButton={true}
@@ -121,6 +122,7 @@ export const TraceAnnotationProcessor: React.FC<
<ObservationPreview
observations={data.observations}
serverScores={data.scores}
+ corrections={data.corrections}
projectId={item.projectId}
currentObservationId={item.objectId}
precomputedCost={nodeMap.get(item.objectId)?.totalCost}
@@ -138,6 +140,7 @@ export const TraceAnnotationProcessor: React.FC<
key={data.id}
trace={data}
scores={data.scores}
+ corrections={data.corrections}
projectId={data.projectId}
observations={data.observations}
viewType="focused"
diff --git a/web/src/features/corrections/contexts/CorrectionCacheContext.tsx b/web/src/features/corrections/contexts/CorrectionCacheContext.tsx
new file mode 100644
index 0000000000..554a0f1b64
--- /dev/null
+++ b/web/src/features/corrections/contexts/CorrectionCacheContext.tsx
@@ -0,0 +1,194 @@
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useState,
+} from "react";
+
+/**
+ * Cached correction - stored in client-side cache for optimistic updates
+ *
+ * Stores full value for optimistic UI updates. Values are cleared once mutation completes.
+ *
+ * Corrections are special annotation scores with the following constraints:
+ * - Name is always "output"
+ * - Only one correction per [traceId, observationId] combination
+ * - If observationId is null, correction applies to the trace
+ */
+export type CachedCorrectionMeta = {
+ id: string;
+ timestamp: Date;
+ projectId: string;
+ traceId: string;
+ observationId?: string | null;
+ environment?: string;
+ value: string; // Full correction value for optimistic updates
+};
+
+type CorrectionCacheContextValue = {
+ /** Add or update a correction in the cache (for optimistic updates) */
+ set: (id: string, meta: CachedCorrectionMeta) => void;
+
+ /** Retrieve a correction from the cache */
+ get: (id: string) => CachedCorrectionMeta | undefined;
+
+ /** Get correction for a specific observation within a trace */
+ getForObservation: (
+ traceId: string,
+ observationId: string,
+ ) => CachedCorrectionMeta | undefined;
+
+ /** Get correction for a trace (where observationId is null/undefined) */
+ getForTrace: (traceId: string) => CachedCorrectionMeta | undefined;
+
+ /** Mark a correction as deleted (user-initiated delete, adds to deletedIds Set + removes from cache Map) */
+ delete: (id: string) => void;
+
+ /** Rollback a failed optimistic set/update (removes from cache without marking as deleted) */
+ rollbackSet: (id: string) => void;
+
+ /** Rollback a failed delete (removes from deletedIds Set, optionally restores to cache Map if correction provided) */
+ rollbackDelete: (id: string, meta?: CachedCorrectionMeta) => void;
+
+ /** Check if a correction is marked as deleted */
+ isDeleted: (id: string) => boolean;
+
+ /** Clear all cached corrections and deletedIds */
+ clear: () => void;
+};
+
+const CorrectionCacheContext = createContext<
+ CorrectionCacheContextValue | undefined
+>(undefined);
+
+export function CorrectionCacheProvider({ children }: { children: ReactNode }) {
+ const [cache, setCache] = useState<Map<string, CachedCorrectionMeta>>(
+ new Map(),
+ );
+ const [deletedIds, setDeletedIds] = useState<Set<string>>(new Set());
+
+ const set = useCallback((id: string, meta: CachedCorrectionMeta) => {
+ setCache((prev) => {
+ const newCache = new Map(prev);
+ newCache.set(id, meta);
+ return newCache;
+ });
+ }, []);
+
+ const get = useCallback(
+ (id: string) => {
+ return cache.get(id);
+ },
+ [cache],
+ );
+
+ const getForObservation = useCallback(
+ (traceId: string, observationId: string) => {
+ return Array.from(cache.values()).find(
+ (meta) =>
+ meta.traceId === traceId &&
+ meta.observationId === observationId &&
+ !deletedIds.has(meta.id),
+ );
+ },
+ [cache, deletedIds],
+ );
+
+ const getForTrace = useCallback(
+ (traceId: string) => {
+ return Array.from(cache.values()).find(
+ (meta) =>
+ meta.traceId === traceId &&
+ (meta.observationId === null || meta.observationId === undefined) &&
+ !deletedIds.has(meta.id),
+ );
+ },
+ [cache, deletedIds],
+ );
+
+ const deleteCorrection = 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 rollbackSet = useCallback((id: string) => {
+ // Remove from cache without marking as deleted
+ setCache((prev) => {
+ if (!prev.has(id)) return prev;
+ const newCache = new Map(prev);
+ newCache.delete(id);
+ return newCache;
+ });
+ }, []);
+
+ const rollbackDelete = useCallback(
+ (id: string, meta?: CachedCorrectionMeta) => {
+ setDeletedIds((prev) => {
+ if (!prev.has(id)) return prev;
+ const newSet = new Set(prev);
+ newSet.delete(id);
+ return newSet;
+ });
+
+ if (meta) {
+ setCache((prev) => {
+ const newCache = new Map(prev);
+ newCache.set(id, meta);
+ return newCache;
+ });
+ }
+ },
+ [],
+ );
+
+ const isDeleted = useCallback(
+ (id: string) => {
+ return deletedIds.has(id);
+ },
+ [deletedIds],
+ );
+
+ const clear = useCallback(() => {
+ setCache(new Map());
+ setDeletedIds(new Set());
+ }, []);
+
+ return (
+ <CorrectionCacheContext.Provider
+ value={{
+ set,
+ get,
+ getForObservation,
+ getForTrace,
+ delete: deleteCorrection,
+ rollbackSet,
+ rollbackDelete,
+ isDeleted,
+ clear,
+ }}
+ >
+ {children}
+ </CorrectionCacheContext.Provider>
+ );
+}
+
+export function useCorrectionCache() {
+ const context = useContext(CorrectionCacheContext);
+ if (!context) {
+ throw new Error(
+ "useCorrectionCache must be used within CorrectionCacheProvider",
+ );
+ }
+ return context;
+}
diff --git a/web/src/features/corrections/utils/getMostRecentCorrection.ts b/web/src/features/corrections/utils/getMostRecentCorrection.ts
new file mode 100644
index 0000000000..ff803904ea
--- /dev/null
+++ b/web/src/features/corrections/utils/getMostRecentCorrection.ts
@@ -0,0 +1,18 @@
+import { type ScoreDomain } from "@langfuse/shared";
+
+/**
+ * Extracts the most recent correction from an array of corrections.
+ * Sorts by timestamp descending (most recent first) and returns the first item.
+ *
+ * @param corrections - Array of correction scores
+ * @returns The most recent correction or undefined if array is empty
+ */
+export function getMostRecentCorrection(
+ corrections: ScoreDomain[],
+): ScoreDomain | undefined {
+ if (corrections.length === 0) return undefined;
+
+ return corrections.sort(
+ (a, b) => b.timestamp.getTime() - a.timestamp.getTime(),
+ )[0];
+}
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsx
index 522f2b7a47..002c5839b5 100644
--- a/web/src/pages/_app.tsx
+++ b/web/src/pages/_app.tsx
@@ -76,6 +76,7 @@ import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownConte
import { SupportDrawerProvider } from "@/src/features/support-chat/SupportDrawerProvider";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { ScoreCacheProvider } from "@/src/features/scores/contexts/ScoreCacheContext";
+import { CorrectionCacheProvider } from "@/src/features/corrections/contexts/CorrectionCacheContext";
// Check that PostHog is client-side (used to handle Next.js SSR) and that env vars are set
if (
@@ -142,13 +143,15 @@ const MyApp: AppType<{ session: Session | null }> = ({
disableTransitionOnChange
>
<ScoreCacheProvider>
- <SupportDrawerProvider defaultOpen={false}>
- <AppLayout>
- <Component {...pageProps} />
- <UserTracking />
- </AppLayout>
- </SupportDrawerProvider>
- <BetterStackUptimeStatusMessage />
+ <CorrectionCacheProvider>
+ <SupportDrawerProvider defaultOpen={false}>
+ <AppLayout>
+ <Component {...pageProps} />
+ <UserTracking />
+ </AppLayout>
+ </SupportDrawerProvider>
+ <BetterStackUptimeStatusMessage />
+ </CorrectionCacheProvider>
</ScoreCacheProvider>
</ThemeProvider>
</MarkdownContextProvider>
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 69bd03a847..44937fa2aa 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -29,6 +29,7 @@ import {
type ScoreConfigDomain,
ScoreSourceEnum,
ScoreDataTypeEnum,
+ CORRECTION_NAME,
} from "@langfuse/shared";
import {
getScoresGroupedByNameSourceType,
@@ -722,6 +723,123 @@ export const scoresRouter = createTRPCRouter({
return validateDbScore(clickhouseScore);
}),
+ upsertCorrection: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ id: z.string(),
+ timestamp: z.date(),
+ traceId: z.string(),
+ observationId: z.string().optional(),
+ value: z.string(),
+ environment: z.string().optional(),
+ queueId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "scores:CUD",
+ });
+
+ const clickhouseTrace = await getTraceById({
+ traceId: input.traceId,
+ projectId: input.projectId,
+ clickhouseFeatureTag: "annotations-trpc",
+ });
+
+ if (!clickhouseTrace) {
+ logger.error(
+ `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
+ );
+ throw new LangfuseNotFoundError(
+ `No trace with id ${input.traceId} in project ${input.projectId} in Clickhouse`,
+ );
+ }
+
+ const clickhouseScore = await searchExistingAnnotationScore(
+ input.projectId,
+ input.observationId ?? null,
+ input.traceId,
+ null,
+ CORRECTION_NAME,
+ undefined,
+ ScoreDataTypeEnum.CORRECTION,
+ );
+
+ const timestamp = input.timestamp;
+
+ const score = !!clickhouseScore
+ ? {
+ ...clickhouseScore,
+ value: 0,
+ stringValue: null,
+ comment: null,
+ metadata: {},
+ authorUserId: ctx.session.user.id,
+ queueId: input.queueId ?? null,
+ longStringValue: input.value,
+ }
+ : {
+ id: input.id,
+ projectId: input.projectId,
+ environment: input.environment ?? "default",
+ traceId: input.traceId,
+ observationId: input.observationId ?? null,
+ sessionId: null,
+ // only trace and session scores are supported for annotation
+ datasetRunId: null,
+ value: 0,
+ stringValue: null,
+ dataType: ScoreDataTypeEnum.CORRECTION,
+ configId: null,
+ name: CORRECTION_NAME,
+ comment: null,
+ metadata: {},
+ authorUserId: ctx.session.user.id,
+ source: ScoreSourceEnum.ANNOTATION,
+ queueId: input.queueId ?? null,
+ executionTraceId: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ timestamp,
+ longStringValue: input.value,
+ };
+
+ await upsertScore({
+ id: score.id, // Reuse ID that was generated by Prisma
+ timestamp: convertDateToClickhouseDateTime(timestamp),
+ project_id: input.projectId,
+ environment: input.environment ?? "default",
+ trace_id: input.traceId,
+ observation_id: input.observationId ?? null,
+ session_id: null,
+ name: CORRECTION_NAME,
+ value: 0,
+ source: ScoreSourceEnum.ANNOTATION,
+ comment: null,
+ author_user_id: ctx.session.user.id,
+ config_id: null,
+ data_type: ScoreDataTypeEnum.CORRECTION,
+ string_value: null,
+ queue_id: input.queueId ?? null,
+ created_at: convertDateToClickhouseDateTime(score.createdAt),
+ updated_at: convertDateToClickhouseDateTime(score.updatedAt),
+ metadata: score.metadata as Record<string, string>,
+ long_string_value: input.value,
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "score",
+ resourceId: score.id,
+ action: "create",
+ after: score,
+ });
+
+ return validateDbScore(score);
+ }),
/**
* @deprecated, use getScoreColumns instead
*/
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index d5525112ed..791fda1252 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -22,6 +22,7 @@ import {
TracingSearchType,
type ScoreDomain,
AGGREGATABLE_SCORE_TYPES,
+ ScoreDataTypeEnum,
} from "@langfuse/shared";
import {
traceException,
@@ -46,6 +47,7 @@ import {
getTracesGroupedByUsers,
getTracesGroupedBySessionId,
updateEvents,
+ getScoresAndCorrectionsForTraces,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { createBatchActionJob } from "@/src/features/table/server/createBatchActionJob";
@@ -59,6 +61,7 @@ import {
toDomainWithStringifiedMetadata,
toDomainArrayWithStringifiedMetadata,
} from "@/src/utils/clientSideDomainTypes";
+import { partition } from "lodash";
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -351,7 +354,7 @@ export const traceRouter = createTRPCRouter({
timestamp: input.timestamp ?? input.fromTimestamp ?? undefined,
includeIO: false,
}),
- getScoresForTraces({
+ getScoresAndCorrectionsForTraces({
projectId: input.projectId,
traceIds: [input.traceId],
timestamp: input.timestamp ?? input.fromTimestamp ?? undefined,
@@ -360,10 +363,15 @@ export const traceRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores: traceScores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: [...AGGREGATABLE_SCORE_TYPES, ScoreDataTypeEnum.CORRECTION],
onParseError: traceException,
});
+ const [corrections, scores] = partition(
+ validatedScores,
+ (s) => s.dataType === ScoreDataTypeEnum.CORRECTION,
+ );
+
const obsStartTimes = observations
.map((o) => o.startTime)
.sort((a, b) => a.getTime() - b.getTime());
@@ -382,14 +390,15 @@ export const traceRouter = createTRPCRouter({
: undefined
: undefined;
- const scores =
- toDomainArrayWithStringifiedMetadata<ScoreDomain>(validatedScores);
+ const scoresDomain =
+ toDomainArrayWithStringifiedMetadata<ScoreDomain>(scores);
return {
...toDomainWithStringifiedMetadata(ctx.trace),
input: ctx.trace.input ? JSON.stringify(ctx.trace.input) : null,
output: ctx.trace.output ? JSON.stringify(ctx.trace.output) : null,
- scores,
+ scores: scoresDomain,
+ corrections,
latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
observations: observations.map((o) => ({
...toDomainWithStringifiedMetadata(o),