Skip to content

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

feat(trace): allow trace comments inline on fractions of IO data (#11171)

Nimar57537ad59e66
diff --git a/fern/apis/server/definition/comments.yml b/fern/apis/server/definition/comments.yml
index e9baaa7dbe..b4c4fec019 100644
--- a/fern/apis/server/definition/comments.yml
+++ b/fern/apis/server/definition/comments.yml
@@ -62,6 +62,18 @@ types:
authorUserId:
type: optional<string>
docs: The id of the user who created the comment.
+ dataField:
+ type: optional<string>
+ docs: For inline comments on IO, specifies which field (input, output, or metadata). Must be set together with path, rangeStart, and rangeEnd.
+ path:
+ type: optional<list<string>>
+ docs: JSON Path expressions specifying comment location within the dataField. Must have same length as rangeStart and rangeEnd.
+ rangeStart:
+ type: optional<list<integer>>
+ docs: Start character offsets (inclusive, UTF-16 code units) for each path entry.
+ rangeEnd:
+ type: optional<list<integer>>
+ docs: End character offsets (exclusive, UTF-16 code units) for each path entry.
CreateCommentResponse:
properties:
id:
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 2fdcdef75b..03ac97424e 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -377,6 +377,18 @@ types:
objectId: string
content: string
authorUserId: optional<string>
+ dataField:
+ type: optional<string>
+ docs: For inline comments, the IO field (input, output, metadata)
+ path:
+ type: optional<list<string>>
+ docs: JSON Path expressions for comment location
+ rangeStart:
+ type: optional<list<integer>>
+ docs: Start character offsets (inclusive, UTF-16)
+ rangeEnd:
+ type: optional<list<integer>>
+ docs: End character offsets (exclusive, UTF-16)
Dataset:
properties:
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 737039da7e..28674a1a69 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -380,6 +380,10 @@ export type Comment = {
updated_at: Generated<Timestamp>;
content: string;
author_user_id: string | null;
+ data_field: string | null;
+ path: Generated<string[]>;
+ range_start: Generated<number[]>;
+ range_end: Generated<number[]>;
};
export type CommentReaction = {
id: string;
diff --git a/packages/shared/prisma/migrations/20260106120000_add_inline_comment_columns/migration.sql b/packages/shared/prisma/migrations/20260106120000_add_inline_comment_columns/migration.sql
new file mode 100644
index 0000000000..3a4c179cb4
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260106120000_add_inline_comment_columns/migration.sql
@@ -0,0 +1,14 @@
+-- Add inline comment positioning columns to comments table
+-- These columns enable character-based inline comments on trace/observation IO
+
+-- data_field: which IO field the comment is on ('input' | 'output' | 'metadata')
+ALTER TABLE "comments" ADD COLUMN "data_field" TEXT;
+
+-- path: JSON Path expressions array, e.g., ["$.messages[1].text"]
+ALTER TABLE "comments" ADD COLUMN "path" TEXT[] DEFAULT '{}';
+
+-- range_start: start offsets per path (inclusive), UTF-16 code units
+ALTER TABLE "comments" ADD COLUMN "range_start" INTEGER[] DEFAULT '{}';
+
+-- range_end: end offsets per path (exclusive), UTF-16 code units
+ALTER TABLE "comments" ADD COLUMN "range_end" INTEGER[] DEFAULT '{}';
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 8a613def92..4cc368d51b 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -722,6 +722,15 @@ model Comment {
authorUserId String? @map("author_user_id") // no fk constraint, user can be deleted
reactions CommentReaction[]
+ // Inline comment positioning (all must be set together or all null/empty)
+ // dataField: which IO field the comment is on ('input' | 'output' | 'metadata')
+ // path: Array of JSON Path expressions, e.g., ["$.messages[1].text"]
+ // rangeStart/rangeEnd: parallel arrays for start/end offsets per path (exclusive end, UTF-16 code units)
+ dataField String? @map("data_field")
+ path String[] @default([]) @map("path")
+ rangeStart Int[] @default([]) @map("range_start")
+ rangeEnd Int[] @default([]) @map("range_end")
+
@@index([projectId, objectType, objectId])
@@map("comments")
}
diff --git a/packages/shared/src/features/comments/types.ts b/packages/shared/src/features/comments/types.ts
index 821ca933fd..c011f84b3c 100644
--- a/packages/shared/src/features/comments/types.ts
+++ b/packages/shared/src/features/comments/types.ts
@@ -2,19 +2,73 @@ import { z } from "zod/v4";
const MAX_COMMENT_LENGTH = 5000;
-const COMMENT_OBJECT_TYPES = [
+export const COMMENT_OBJECT_TYPES = [
"TRACE",
"OBSERVATION",
"SESSION",
"PROMPT",
] as const;
-export const CreateCommentData = z.object({
- projectId: z.string(),
- content: z.string().trim().min(1).max(MAX_COMMENT_LENGTH),
- objectId: z.string(),
- objectType: z.enum(COMMENT_OBJECT_TYPES),
-});
+export const COMMENT_DATA_FIELDS = ["input", "output", "metadata"] as const;
+
+// JSON Path validation
+// TODO: simplify
+// Allows: $ (root), $.foo, $[0], $.foo[0].bar, $['key-with-dash'], etc.
+export const jsonPathSchema = z
+ .string()
+ .regex(
+ /^\$(\.[a-zA-Z_][a-zA-Z0-9_-]*|\[\d+\]|\['[^']+'\]|\["[^"]+"\])*$/,
+ "Invalid JSON Path syntax",
+ );
+
+export const CreateCommentData = z
+ .object({
+ projectId: z.string(),
+ content: z.string().trim().min(1).max(MAX_COMMENT_LENGTH),
+ objectId: z.string(),
+ objectType: z.enum(COMMENT_OBJECT_TYPES),
+ // Optional inline positioning (parallel arrays)
+ dataField: z.enum(COMMENT_DATA_FIELDS).nullish(),
+ path: z.array(jsonPathSchema).nullish(),
+ rangeStart: z.array(z.number().int().min(0)).nullish(),
+ rangeEnd: z.array(z.number().int().min(1)).nullish(),
+ })
+ .refine(
+ (data) => {
+ const hasDataField = data.dataField != null;
+ const hasPath = data.path != null && data.path.length > 0;
+ const hasRangeStart =
+ data.rangeStart != null && data.rangeStart.length > 0;
+ const hasRangeEnd = data.rangeEnd != null && data.rangeEnd.length > 0;
+
+ // All must be set together, or all must be null/empty
+ if (hasDataField || hasPath || hasRangeStart || hasRangeEnd) {
+ return (
+ hasDataField &&
+ hasPath &&
+ hasRangeStart &&
+ hasRangeEnd &&
+ data.path!.length === data.rangeStart!.length &&
+ data.path!.length === data.rangeEnd!.length
+ );
+ }
+ return true;
+ },
+ {
+ message:
+ "dataField, path, rangeStart, rangeEnd must all be set together with matching lengths, or all be null/empty",
+ },
+ )
+ .refine(
+ (data) => {
+ // Validate each range: start must be < end
+ if (data.rangeStart && data.rangeEnd) {
+ return data.rangeStart.every((start, i) => start < data.rangeEnd![i]);
+ }
+ return true;
+ },
+ { message: "Each rangeStart must be less than corresponding rangeEnd" },
+ );
export const DeleteCommentData = z.object({
projectId: z.string(),
@@ -22,3 +76,5 @@ export const DeleteCommentData = z.object({
objectId: z.string(),
objectType: z.enum(COMMENT_OBJECT_TYPES),
});
+
+export type CreateCommentInput = z.infer<typeof CreateCommentData>;
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index e4c4f46ea0..83ef6e28d2 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -6362,6 +6362,36 @@ components:
type: string
nullable: true
description: The id of the user who created the comment.
+ dataField:
+ type: string
+ nullable: true
+ description: >-
+ For inline comments on IO, specifies which field (input, output, or
+ metadata). Must be set together with path, rangeStart, and rangeEnd.
+ path:
+ type: array
+ items:
+ type: string
+ nullable: true
+ description: >-
+ JSON Path expressions specifying comment location within the
+ dataField. Must have same length as rangeStart and rangeEnd.
+ rangeStart:
+ type: array
+ items:
+ type: integer
+ nullable: true
+ description: >-
+ Start character offsets (inclusive, UTF-16 code units) for each path
+ entry.
+ rangeEnd:
+ type: array
+ items:
+ type: integer
+ nullable: true
+ description: >-
+ End character offsets (exclusive, UTF-16 code units) for each path
+ entry.
required:
- projectId
- objectType
@@ -7155,6 +7185,28 @@ components:
authorUserId:
type: string
nullable: true
+ dataField:
+ type: string
+ nullable: true
+ description: For inline comments, the IO field (input, output, metadata)
+ path:
+ type: array
+ items:
+ type: string
+ nullable: true
+ description: JSON Path expressions for comment location
+ rangeStart:
+ type: array
+ items:
+ type: integer
+ nullable: true
+ description: Start character offsets (inclusive, UTF-16)
+ rangeEnd:
+ type: array
+ items:
+ type: integer
+ nullable: true
+ description: End character offsets (exclusive, UTF-16)
required:
- id
- projectId
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 9cdd110faf..1050ae0a28 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -570,7 +570,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"projectId\": \"example\",\n \"objectType\": \"example\",\n \"objectId\": \"example\",\n \"content\": \"example\",\n \"authorUserId\": \"example\"\n}",
+ "raw": "{\n \"projectId\": \"example\",\n \"objectType\": \"example\",\n \"objectId\": \"example\",\n \"content\": \"example\",\n \"authorUserId\": \"example\",\n \"dataField\": \"example\",\n \"path\": [\n \"example\"\n ],\n \"rangeStart\": [\n 0\n ],\n \"rangeEnd\": [\n 0\n ]\n}",
"options": {
"raw": {
"language": "json"
diff --git a/web/src/components/trace2/components/IOPreview/IOPreview.tsx b/web/src/components/trace2/components/IOPreview/IOPreview.tsx
index 0a946a1b58..e68931b551 100644
--- a/web/src/components/trace2/components/IOPreview/IOPreview.tsx
+++ b/web/src/components/trace2/components/IOPreview/IOPreview.tsx
@@ -6,7 +6,7 @@ import usePreserveRelativeScroll from "@/src/hooks/usePreserveRelativeScroll";
import { type MediaReturnType } from "@/src/features/media/validation";
import { ViewModeToggle, type ViewMode } from "./components/ViewModeToggle";
-import { IOPreviewJSON } from "./IOPreviewJSON";
+import { IOPreviewJSON, type IOPreviewJSONProps } from "./IOPreviewJSON";
import { IOPreviewJSONSimple } from "./IOPreviewJSONSimple";
import { IOPreviewPretty } from "./IOPreviewPretty";
import { Button } from "@/src/components/ui/button";
@@ -47,6 +47,10 @@ export interface IOPreviewProps extends ExpansionStateProps {
hideInput?: boolean;
currentView?: ViewMode;
setIsPrettyViewAvailable?: (value: boolean) => void;
+ // Inline comment props (JSON Beta view only)
+ enableInlineComments?: boolean;
+ onAddInlineComment?: IOPreviewJSONProps["onAddInlineComment"];
+ commentedPathsByField?: IOPreviewJSONProps["commentedPathsByField"];
// Whether to show metadata section in pretty view (default: false)
// JSON view always shows metadata
showMetadata?: boolean;
@@ -93,6 +97,9 @@ export function IOPreview({
onInputExpansionChange,
onOutputExpansionChange,
setIsPrettyViewAvailable,
+ enableInlineComments,
+ onAddInlineComment,
+ commentedPathsByField,
showMetadata = false,
onVirtualizationChange,
observationId,
@@ -177,8 +184,8 @@ export function IOPreview({
{/*
* Conditional rendering based on view mode:
- * - JSON Beta view: IOPreviewJSON (advanced viewer with virtualization, search)
- * - JSON view: IOPreviewJSONSimple (simple react18-json-view, no virtualization)
+ * - JSON Beta view: IOPreviewJSON (advanced viewer with virtualization, search, inline comments)
+ * - JSON view: IOPreviewJSONSimple (simple react18-json-view, no virtualization, no comments)
* - Pretty view: IOPreviewPretty (with ChatML parsing, markdown, tools)
*
* Only render the active view to prevent dual DOM tree construction.
@@ -201,6 +208,9 @@ export function IOPreview({
onInputExpansionChange={onInputExpansionChange}
onOutputExpansionChange={onOutputExpansionChange}
onVirtualizationChange={onVirtualizationChange}
+ enableInlineComments={enableInlineComments}
+ onAddInlineComment={onAddInlineComment}
+ commentedPathsByField={commentedPathsByField}
observationId={observationId}
projectId={projectId}
traceId={traceId}
diff --git a/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx b/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx
index 6f025d5122..acc4b1a34a 100644
--- a/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx
+++ b/web/src/components/trace2/components/IOPreview/IOPreviewJSON.tsx
@@ -16,6 +16,14 @@ import {
HoverCardContent,
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
+import {
+ InlineCommentSelectionProvider,
+ useInlineCommentSelectionOptional,
+ type SelectionData,
+} from "@/src/features/comments/contexts/InlineCommentSelectionContext";
+import { CommentableJsonView } from "@/src/features/comments/components/CommentableJsonView";
+import { InlineCommentBubble } from "@/src/features/comments/components/InlineCommentBubble";
+import { type CommentedPathsByField } from "@/src/components/ui/AdvancedJsonViewer/utils/commentRanges";
import { type ScoreDomain } from "@langfuse/shared";
import { CorrectedOutputField } from "./components/CorrectedOutputField";
@@ -35,6 +43,11 @@ export interface IOPreviewJSONProps extends ExpansionStateProps {
media?: MediaReturnType[];
// Callback to inform parent if virtualization is being used (for scroll handling)
onVirtualizationChange?: (isVirtualized: boolean) => void;
+ // Inline comment props
+ enableInlineComments?: boolean;
+ onAddInlineComment?: (selection: SelectionData) => void;
+ commentedPathsByField?: CommentedPathsByField;
+ // Correction props
observationId?: string;
projectId: string;
traceId: string;
@@ -53,7 +66,7 @@ export interface IOPreviewJSONProps extends ExpansionStateProps {
* This component is ~150ms faster than the full IOPreview for large data
* because it skips all ChatML processing.
*/
-export function IOPreviewJSON({
+function IOPreviewJSONInner({
parsedInput,
parsedOutput,
parsedMetadata,
@@ -64,11 +77,22 @@ export function IOPreviewJSON({
hideInput = false,
media,
onVirtualizationChange,
+ enableInlineComments = false,
+ onAddInlineComment,
+ commentedPathsByField,
observationId,
projectId,
traceId,
environment = "default",
}: IOPreviewJSONProps) {
+ const selectionContext = useInlineCommentSelectionOptional();
+
+ const handleAddComment = useCallback(() => {
+ if (selectionContext?.selection && onAddInlineComment) {
+ onAddInlineComment(selectionContext.selection);
+ }
+ }, [selectionContext?.selection, onAddInlineComment]);
+
const { resolvedTheme } = useTheme();
const isDark = resolvedTheme === "dark";
@@ -104,7 +128,7 @@ export function IOPreviewJSON({
);
}, [rowCounts]);
- // Hooks for multi-section viewer (Path B) - must be called unconditionally
+ // Hooks for multi-section viewer - must be called unconditionally
const { stringWrapMode, setStringWrapMode } = useJsonViewPreferences();
const [searchQuery, setSearchQuery] = useState("");
const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");
@@ -113,7 +137,7 @@ export function IOPreviewJSON({
const scrollContainerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<MultiSectionJsonViewerHandle>(null);
- // Debounce search query (applies to both virtualized and non-virtualized modes)
+ // Debounce search query
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedSearchQuery(searchQuery);
@@ -122,8 +146,6 @@ export function IOPreviewJSON({
return () => clearTimeout(timer);
}, [searchQuery]);
- // No longer using accordion mode - MultiSectionJsonViewer shows all sections with collapsible headers
-
// Notify parent about virtualization state
useEffect(() => {
onVirtualizationChange?.(needsVirtualization);
@@ -148,7 +170,7 @@ export function IOPreviewJSON({
setCurrentMatchIndex(0);
}, []);
- // Handle string wrap mode cycling for Path B
+ // Handle string wrap mode cycling
const handleCycleWrapMode = useCallback(() => {
if (stringWrapMode === "truncate") {
setStringWrapMode("wrap");
@@ -159,7 +181,6 @@ export function IOPreviewJSON({
}
}, [stringWrapMode, setStringWrapMode]);
- // Handle copy for Path B
// Handle scrolling to a specific section
const handleScrollToSection = useCallback((sectionKey: string) => {
viewerRef.current?.scrollToSection(sectionKey);
@@ -194,7 +215,6 @@ export function IOPreviewJSON({
);
// Build sections - memoized to prevent re-creation
- // Must be defined before any conditional returns (React hooks rules)
const sections = useMemo(() => {
const result = [];
if (showInput) {
@@ -238,8 +258,6 @@ export function IOPreviewJSON({
]);
// Wait for parsing to complete before rendering to avoid flicker
- // isParsing is true when we have raw data but parsed data hasn't arrived yet
- // This check happens AFTER all hooks to comply with React hooks rules
if (isParsing) {
return (
<div className="flex min-h-0 flex-1 flex-col border-b border-t">
@@ -250,8 +268,37 @@ export function IOPreviewJSON({
);
}
+ // The viewer content - wrapped in CommentableJsonView when comments are enabled
+ const viewerContent = (
+ <MultiSectionJsonViewer
+ ref={viewerRef}
+ sections={sections}
+ virtualized={needsVirtualization}
+ showLineNumbers={true}
+ enableCopy={true}
+ stringWrapMode={stringWrapMode}
+ truncateStringsAt={stringWrapMode === "truncate" ? 100 : null}
+ searchQuery={debouncedSearchQuery}
+ currentMatchIndex={currentMatchIndex}
+ onSearchResults={setSearchMatchCount}
+ scrollContainerRef={scrollContainerRef as React.RefObject<HTMLDivElement>}
+ media={media}
+ commentedPathsByField={commentedPathsByField}
+ theme={{
+ fontSize: "0.7rem",
+ lineHeight: 14,
+ indentSize: 12,
+ }}
+ />
+ );
+
return (
<div className="flex min-h-0 flex-1 flex-col border-b border-t">
+ {/* Inline comment bubble - shows when text is selected */}
+ {enableInlineComments && (
+ <InlineCommentBubble onAddComment={handleAddComment} />
+ )}
+
{/* Header - matches LogViewToolbar styling */}
<div className="flex h-9 flex-shrink-0 items-center gap-1.5 border-b bg-background px-2">
{/* Search input - expands to fill available width */}
@@ -374,27 +421,13 @@ export function IOPreviewJSON({
{/* Body with MultiSectionJsonViewer */}
<div className="min-h-0 flex-1 overflow-auto" ref={scrollContainerRef}>
- <MultiSectionJsonViewer
- ref={viewerRef}
- sections={sections}
- virtualized={needsVirtualization}
- showLineNumbers={true}
- enableCopy={true}
- stringWrapMode={stringWrapMode}
- truncateStringsAt={stringWrapMode === "truncate" ? 100 : null}
- searchQuery={debouncedSearchQuery}
- currentMatchIndex={currentMatchIndex}
- onSearchResults={setSearchMatchCount}
- scrollContainerRef={
- scrollContainerRef as React.RefObject<HTMLDivElement>
- }
- media={media}
- theme={{
- fontSize: "0.7rem",
- lineHeight: 14,
- indentSize: 12,
- }}
- />
+ {enableInlineComments ? (
+ <CommentableJsonView enabled={enableInlineComments}>
+ {viewerContent}
+ </CommentableJsonView>
+ ) : (
+ viewerContent
+ )}
<CorrectedOutputField
actualOutput={parsedOutput}
existingCorrection={outputCorrection}
@@ -407,3 +440,18 @@ export function IOPreviewJSON({
</div>
);
}
+
+/**
+ * IOPreviewJSON - Wrapper that conditionally adds InlineCommentSelectionProvider.
+ */
+export function IOPreviewJSON(props: IOPreviewJSONProps) {
+ // Wrap with selection provider if inline comments are enabled
+ if (props.enableInlineComments) {
+ return (
+ <InlineCommentSelectionProvider>
+ <IOPreviewJSONInner {...props} />
+ </InlineCommentSelectionProvider>
+ );
+ }
+ return <IOPreviewJSONInner {...props} />;
+}
diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
index 76eccd6fc7..fbb220955c 100644
--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx
@@ -25,7 +25,8 @@ import {
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
+import { type SelectionData } from "@/src/features/comments/contexts/InlineCommentSelectionContext";
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";
@@ -37,6 +38,8 @@ import { useViewPreferences } from "@/src/components/trace2/contexts/ViewPrefere
// Contexts and hooks
import { useTraceData } from "@/src/components/trace2/contexts/TraceDataContext";
import { useParsedObservation } from "@/src/hooks/useParsedObservation";
+import { useCommentedPaths } from "@/src/features/comments/hooks/useCommentedPaths";
+import { api } from "@/src/utils/api";
// Extracted components
import { ObservationDetailViewHeader } from "./ObservationDetailViewHeader";
@@ -75,7 +78,23 @@ export function ObservationDetailView({
const currentView = jsonViewPreference;
const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);
- const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false); // Get comments, scores, corrections, and expansion state from contexts
+ const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false);
+
+ // states for the inline comments
+ const [pendingSelection, setPendingSelection] =
+ useState<SelectionData | null>(null);
+ const [isCommentDrawerOpen, setIsCommentDrawerOpen] = useState(false);
+
+ const handleAddInlineComment = useCallback((selection: SelectionData) => {
+ setPendingSelection(selection);
+ setIsCommentDrawerOpen(true);
+ }, []);
+
+ const handleSelectionUsed = useCallback(() => {
+ setPendingSelection(null);
+ }, []);
+
+ // Get comments, scores, corrections, and expansion state from contexts
const { comments, serverScores: scores, corrections } = useTraceData();
const { expansionState, setFieldExpansion } = useJsonExpansion();
const observationScores = useMemo(
@@ -118,6 +137,19 @@ export function ObservationDetailView({
observationId: observation.id,
});
+ const observationComments = api.comments.getByObjectId.useQuery(
+ {
+ projectId,
+ objectId: observation.id,
+ objectType: "OBSERVATION",
+ },
+ {
+ refetchOnMount: false,
+ },
+ );
+
+ const commentedPathsByField = useCommentedPaths(observationComments.data);
+
// Calculate latency in seconds if not provided
const latencySeconds = useMemo(() => {
if (observation.latency) {
@@ -142,6 +174,10 @@ export function ObservationDetailView({
latencySeconds={latencySeconds}
observationScores={observationScores}
commentCount={comments.get(observation.id)}
+ pendingSelection={pendingSelection}
+ onSelectionUsed={handleSelectionUsed}
+ isCommentDrawerOpen={isCommentDrawerOpen}
+ onCommentDrawerOpenChange={setIsCommentDrawerOpen}
/>
{/* Tabs section */}
@@ -211,6 +247,9 @@ export function ObservationDetailView({
onOutputExpansionChange={(exp) =>
setFieldExpansion("output", exp)
}
+ enableInlineComments={true}
+ onAddInlineComment={handleAddInlineComment}
+ commentedPathsByField={commentedPathsByField}
showMetadata
observationId={observation.id}
onVirtualizationChange={setIsJSONBetaVirtualized}
diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx
index 5a7d4f94c9..3cd5131383 100644
--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx
+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailViewHeader.tsx
@@ -15,6 +15,7 @@ import {
AnnotationQueueObjectType,
isGenerationLike,
} from "@langfuse/shared";
+import { type SelectionData } from "@/src/features/comments/contexts/InlineCommentSelectionContext";
import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
import { ItemBadge } from "@/src/components/ItemBadge";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
@@ -57,6 +58,11 @@ export interface ObservationDetailViewHeaderProps {
latencySeconds: number | null;
observationScores: WithStringifiedMetadata<ScoreDomain>[];
commentCount: number | undefined;
+ // Inline comment props
+ pendingSelection?: SelectionData | null;
+ onSelectionUsed?: () => void;
+ isCommentDrawerOpen?: boolean;
+ onCommentDrawerOpenChange?: (open: boolean) => void;
}
export const ObservationDetailViewHeader = memo(
@@ -68,6 +74,10 @@ export const ObservationDetailViewHeader = memo(
latencySeconds,
observationScores,
commentCount,
+ pendingSelection,
+ onSelectionUsed,
+ isCommentDrawerOpen,
+ onCommentDrawerOpenChange,
}: ObservationDetailViewHeaderProps) {
// Format cost and usage values
const totalCost = observation.totalCost;
@@ -144,6 +154,10 @@ export const ObservationDetailViewHeader = memo(
objectType="OBSERVATION"
count={commentCount}
size="sm"
+ pendingSelection={pendingSelection}
+ onSelectionUsed={onSelectionUsed}
+ isOpen={isCommentDrawerOpen}
+ onOpenChange={onCommentDrawerOpenChange}
/>
</div>
</div>
diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx
index 4e8bfea68b..642ffb83ee 100644
--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx
+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx
@@ -12,7 +12,9 @@ import {
TabsBarTrigger,
} from "@/src/components/ui/tabs-bar";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
+import { type SelectionData } from "@/src/features/comments/contexts/InlineCommentSelectionContext";
+import { api } from "@/src/utils/api";
import {
Tooltip,
TooltipContent,
@@ -37,6 +39,8 @@ import { useTraceData } from "@/src/components/trace2/contexts/TraceDataContext"
import { useViewPreferences } from "@/src/components/trace2/contexts/ViewPreferencesContext";
import { useSelection } from "@/src/components/trace2/contexts/SelectionContext";
import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";
+import { useCommentedPaths } from "@/src/features/comments/hooks/useCommentedPaths";
+
// Extracted components
import { TraceDetailViewHeader } from "./TraceDetailViewHeader";
import { TraceLogView } from "../TraceLogView/TraceLogView";
@@ -68,6 +72,20 @@ export function TraceDetailView({
const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);
const [isJSONBetaVirtualized, setIsJSONBetaVirtualized] = useState(false);
+ // Inline comment state
+ const [pendingSelection, setPendingSelection] =
+ useState<SelectionData | null>(null);
+ const [isCommentDrawerOpen, setIsCommentDrawerOpen] = useState(false);
+
+ const handleAddInlineComment = useCallback((selection: SelectionData) => {
+ setPendingSelection(selection);
+ setIsCommentDrawerOpen(true);
+ }, []);
+
+ const handleSelectionUsed = useCallback(() => {
+ setPendingSelection(null);
+ }, []);
+
// Get jsonViewPreference directly from ViewPreferencesContext for "json-beta" support
const { jsonViewPreference, setJsonViewPreference } = useViewPreferences();
@@ -90,6 +108,20 @@ export function TraceDetailView({
metadata: trace.metadata,
});
+ // Fetch comments for this trace (for inline comment highlighting)
+ const traceComments = api.comments.getByObjectId.useQuery(
+ {
+ projectId,
+ objectId: trace.id,
+ objectType: "TRACE",
+ },
+ {
+ refetchOnMount: false,
+ },
+ );
+
+ const commentedPathsByField = useCommentedPaths(traceComments.data);
+
// Derived state
const traceScores = useMemo(
() => scores.filter((s) => !s.observationId),
@@ -128,6 +160,10 @@ export function TraceDetailView({
projectId={projectId}
traceScores={traceScores}
commentCount={comments.get(trace.id)}
+ pendingSelection={pendingSelection}
+ onSelectionUsed={handleSelectionUsed}
+ isCommentDrawerOpen={isCommentDrawerOpen}
+ onCommentDrawerOpenChange={setIsCommentDrawerOpen}
/>
{/* Tabs section */}
@@ -301,6 +337,9 @@ export function TraceDetailView({
onOutputExpansionChange={(exp) =>
setFieldExpansion("output", exp)
}
+ enableInlineComments={true}
+ onAddInlineComment={handleAddInlineComment}
+ commentedPathsByField={commentedPathsByField}
showMetadata
onVirtualizationChange={setIsJSONBetaVirtualized}
projectId={projectId}
diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx
index fec88e8e4a..98380e7fff 100644
--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx
+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx
@@ -15,6 +15,7 @@ import {
type ScoreDomain,
AnnotationQueueObjectType,
} from "@langfuse/shared";
+import { type SelectionData } from "@/src/features/comments/contexts/InlineCommentSelectionContext";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
import { ItemBadge } from "@/src/components/ItemBadge";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
@@ -40,6 +41,11 @@ export interface TraceDetailViewHeaderProps {
projectId: string;
traceScores: WithStringifiedMetadata<ScoreDomain>[];
commentCount: number | undefined;
+ // Inline comment props
+ pendingSelection?: SelectionData | null;
+ onSelectionUsed?: () => void;
+ isCommentDrawerOpen?: boolean;
+ onCommentDrawerOpenChange?: (open: boolean) => void;
}
export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
@@ -47,6 +53,10 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
projectId,
traceScores,
commentCount,
+ pendingSelection,
+ onSelectionUsed,
+ isCommentDrawerOpen,
+ onCommentDrawerOpenChange,
}: TraceDetailViewHeaderProps) {
return (
<div className="flex-shrink-0 space-y-2 border-b p-2 @container">
@@ -100,6 +110,10 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
objectType="TRACE"
count={commentCount}
size="sm"
+ pendingSelection={pendingSelection}
+ onSelectionUsed={onSelectionUsed}
+ isOpen={isCommentDrawerOpen}
+ onOpenChange={onCommentDrawerOpenChange}
/>
</div>
</div>
diff --git a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx b/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx
index fe04aad394..4ad804fcae 100644
--- a/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx
+++ b/web/src/components/ui/AdvancedJsonSection/AdvancedJsonSection.tsx
@@ -83,6 +83,8 @@ export interface AdvancedJsonSectionProps {
/** Additional control buttons in header */
controlButtons?: React.ReactNode;
+ commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
+
/** Force virtualization on/off (overrides auto-detection) */
virtualized?: boolean;
}
@@ -106,6 +108,7 @@ export function AdvancedJsonSection({
isLoading = false,
media: _media, // TODO: Implement media attachment support
controlButtons,
+ commentedPaths,
virtualized,
}: AdvancedJsonSectionProps) {
// String wrap mode state (persisted in localStorage)
@@ -441,8 +444,9 @@ export function AdvancedJsonSection({
truncateStringsAt={truncateStringsAt}
isLoading={isLoading}
scrollContainerRef={scrollContainerRef}
- virtualized={virtualized} // Pass through virtualized prop
+ virtualized={virtualized}
className={virtualized !== false ? "h-full" : ""}
+ commentedPaths={commentedPaths}
/>
)}
</div>
diff --git a/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx
index 25aba207a5..b437a0604a 100644
--- a/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/AdvancedJsonViewer.tsx
@@ -51,6 +51,7 @@ export function AdvancedJsonViewer({
isLoading = false,
error,
scrollContainerRef,
+ commentedPaths,
}: AdvancedJsonViewerProps) {
debugLog("[AdvancedJsonViewer] RENDER");
// Resolve theme
@@ -202,6 +203,7 @@ export function AdvancedJsonViewer({
scrollToIndex,
scrollContainerRef,
totalLineCount: tree?.totalNodeCount,
+ commentedPaths,
};
}, [
tree,
@@ -217,6 +219,7 @@ export function AdvancedJsonViewer({
handleToggleExpansion,
scrollToIndex,
scrollContainerRef,
+ commentedPaths,
]);
// Early returns for special states
diff --git a/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsx
index c12bec71b6..dc0e1c5ebd 100644
--- a/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/MultiSectionJsonViewer.tsx
@@ -25,6 +25,7 @@ import {
import { SectionContextProvider } from "./contexts/SectionContext";
import { searchInTree, getMatchCountsPerNode } from "./utils/searchJson";
import { type MediaReturnType } from "@/src/features/media/validation";
+import { type CommentedPathsByField } from "./utils/commentRanges";
export interface MultiSectionJsonViewerHandle {
scrollToSection: (sectionKey: string) => void;
@@ -66,6 +67,9 @@ export interface MultiSectionJsonViewerProps {
/** Media attachments (will be filtered by section field) */
media?: MediaReturnType[];
+
+ /** Comment highlight ranges per field (for inline comments feature) */
+ commentedPathsByField?: CommentedPathsByField;
}
/**
@@ -100,6 +104,7 @@ export const MultiSectionJsonViewer = forwardRef<
className,
scrollContainerRef,
media,
+ commentedPathsByField,
},
ref,
) {
@@ -191,6 +196,7 @@ export const MultiSectionJsonViewer = forwardRef<
onToggleExpansion: handleToggleExpansion,
scrollContainerRef,
media,
+ commentedPathsByField,
}),
[
tree,
@@ -208,6 +214,7 @@ export const MultiSectionJsonViewer = forwardRef<
handleToggleExpansion,
scrollContainerRef,
media,
+ commentedPathsByField,
],
);
diff --git a/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx
index 088fdce030..c1cc37f131 100644
--- a/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/SimpleJsonViewer.tsx
@@ -13,6 +13,7 @@ import { JsonRowFixed } from "./components/JsonRowFixed";
import { JsonRowScrollable } from "./components/JsonRowScrollable";
import { useJsonSearch } from "./hooks/useJsonSearch";
import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";
+import { pathArrayToJsonPath } from "./utils/pathUtils";
import { debugLog } from "./utils/debug";
interface SimpleJsonViewerProps {
@@ -31,6 +32,7 @@ interface SimpleJsonViewerProps {
scrollToIndex?: number; // For search navigation
scrollContainerRef?: RefObject<HTMLDivElement | null>; // Parent scroll container
totalLineCount?: number; // Total number of lines when fully expanded (for line number width calculation)
+ commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
}
export const SimpleJsonViewer = memo(function SimpleJsonViewer({
@@ -49,6 +51,7 @@ export const SimpleJsonViewer = memo(function SimpleJsonViewer({
scrollToIndex,
scrollContainerRef: _scrollContainerRef,
totalLineCount,
+ commentedPaths,
}: SimpleJsonViewerProps) {
debugLog("[SimpleJsonViewer] RENDER");
@@ -125,6 +128,8 @@ export const SimpleJsonViewer = memo(function SimpleJsonViewer({
const searchMatch = matchMap.get(row.id);
const isCurrentMatch = currentMatch?.rowId === row.id;
const matchCount = matchCounts?.get(row.id);
+ const rowJsonPath = pathArrayToJsonPath(row.pathArray);
+ const commentRanges = commentedPaths?.get(rowJsonPath);
return (
<div
@@ -189,6 +194,8 @@ export const SimpleJsonViewer = memo(function SimpleJsonViewer({
enableCopy={enableCopy}
searchMatch={searchMatch}
isCurrentMatch={isCurrentMatch}
+ jsonPath={rowJsonPath}
+ commentRanges={commentRanges}
/>
</div>
</div>
diff --git a/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx
index cd328dacf2..915433740b 100644
--- a/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/SimpleMultiSectionViewer.tsx
@@ -23,6 +23,12 @@ import { JsonRowScrollable } from "./components/JsonRowScrollable";
import { useJsonSearch } from "./hooks/useJsonSearch";
import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";
import { searchInTree } from "./utils/searchJson";
+import {
+ getCommentRangesForRow,
+ getCommentCountForSection,
+ type CommentedPathsByField,
+} from "./utils/commentRanges";
+import { pathArrayToJsonPath } from "./utils/pathUtils";
import { type MediaReturnType } from "@/src/features/media/validation";
export interface SimpleMultiSectionViewerHandle {
@@ -47,6 +53,7 @@ export interface SimpleMultiSectionViewerProps {
onToggleExpansion?: (nodeId: string) => void;
scrollContainerRef?: RefObject<HTMLDivElement>;
media?: MediaReturnType[];
+ commentedPathsByField?: CommentedPathsByField;
}
export const SimpleMultiSectionViewer = memo(
@@ -68,6 +75,7 @@ export const SimpleMultiSectionViewer = memo(
onToggleExpansion,
scrollContainerRef,
media,
+ commentedPathsByField,
},
ref,
) {
@@ -219,6 +227,14 @@ export const SimpleMultiSectionViewer = memo(
const row = treeNodeToFlatRow(node, index);
const matchCount = matchCounts?.get(node.id);
+ // Get comment ranges for this row
+ const commentRanges = getCommentRangesForRow(
+ row,
+ node.sectionKey,
+ commentedPathsByField,
+ );
+ const rowJsonPath = pathArrayToJsonPath(row.pathArray);
+
return (
<div
key={node.id}
@@ -282,6 +298,9 @@ export const SimpleMultiSectionViewer = memo(
enableCopy={enableCopy}
stringWrapMode={stringWrapMode}
truncateStringsAt={truncateStringsAt}
+ jsonPath={rowJsonPath}
+ commentRanges={commentRanges}
+ sectionKey={node.sectionKey}
/>
</div>
</div>
@@ -331,6 +350,12 @@ export const SimpleMultiSectionViewer = memo(
// Filter media for this section
const sectionMedia = media?.filter((m) => m.field === sectionKey);
+ // Get comment count for this section
+ const sectionCommentCount = getCommentCountForSection(
+ sectionKey,
+ commentedPathsByField,
+ );
+
// Render header with fallback chain
let headerContent;
if (jsonSection?.renderHeader) {
@@ -346,6 +371,7 @@ export const SimpleMultiSectionViewer = memo(
title={title}
context={sectionContext}
media={sectionMedia}
+ commentCount={sectionCommentCount}
/>
);
}
diff --git a/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx
index 38fc31bc4f..be0f7161dc 100644
--- a/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/VirtualizedJsonViewer.tsx
@@ -14,6 +14,7 @@ import { JsonRowFixed } from "./components/JsonRowFixed";
import { JsonRowScrollable } from "./components/JsonRowScrollable";
import { useJsonSearch } from "./hooks/useJsonSearch";
import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";
+import { pathArrayToJsonPath } from "./utils/pathUtils";
import { useMonospaceCharWidth } from "./hooks/useMonospaceCharWidth";
interface VirtualizedJsonViewerProps {
@@ -32,6 +33,7 @@ interface VirtualizedJsonViewerProps {
scrollToIndex?: number; // For search navigation
scrollContainerRef?: RefObject<HTMLDivElement | null>; // Parent scroll container
totalLineCount?: number; // Total number of lines when fully expanded (for line number width calculation)
+ commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
}
export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({
@@ -50,6 +52,7 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({
scrollToIndex,
scrollContainerRef,
totalLineCount,
+ commentedPaths,
}: VirtualizedJsonViewerProps) {
const parentRef = useRef<HTMLDivElement>(null);
@@ -171,6 +174,8 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({
const searchMatch = matchMap.get(row.id);
const isCurrentMatch = currentMatch?.rowId === row.id;
const matchCount = matchCounts?.get(row.id);
+ const rowJsonPath = pathArrayToJsonPath(row.pathArray);
+ const commentRanges = commentedPaths?.get(rowJsonPath);
return (
<div
@@ -234,6 +239,8 @@ export const VirtualizedJsonViewer = memo(function VirtualizedJsonViewer({
enableCopy={enableCopy}
searchMatch={searchMatch}
isCurrentMatch={isCurrentMatch}
+ jsonPath={rowJsonPath}
+ commentRanges={commentRanges}
/>
</div>
</div>
diff --git a/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsx b/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsx
index edf3b40bb6..b640745c11 100644
--- a/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/VirtualizedMultiSectionViewer.tsx
@@ -30,6 +30,12 @@ import { useJsonSearch } from "./hooks/useJsonSearch";
import { useJsonViewerLayout } from "./hooks/useJsonViewerLayout";
import { searchInTree } from "./utils/searchJson";
import { useMonospaceCharWidth } from "./hooks/useMonospaceCharWidth";
+import {
+ getCommentRangesForRow,
+ getCommentCountForSection,
+ type CommentedPathsByField,
+} from "./utils/commentRanges";
+import { pathArrayToJsonPath } from "./utils/pathUtils";
import { type MediaReturnType } from "@/src/features/media/validation";
export interface VirtualizedMultiSectionViewerHandle {
@@ -54,6 +60,7 @@ export interface VirtualizedMultiSectionViewerProps {
onToggleExpansion?: (nodeId: string) => void;
scrollContainerRef?: RefObject<HTMLDivElement>;
media?: MediaReturnType[];
+ commentedPathsByField?: CommentedPathsByField;
}
export const VirtualizedMultiSectionViewer = memo(
@@ -77,6 +84,7 @@ export const VirtualizedMultiSectionViewer = memo(
onToggleExpansion,
scrollContainerRef,
media,
+ commentedPathsByField,
},
ref,
) {
@@ -300,6 +308,12 @@ export const VirtualizedMultiSectionViewer = memo(
(m) => m.field === node.sectionKey,
);
+ // Get comment count for this section
+ const sectionCommentCount = getCommentCountForSection(
+ node.sectionKey,
+ commentedPathsByField,
+ );
+
// Render header with fallback chain
let headerContent;
if (jsonSection?.renderHeader) {
@@ -315,6 +329,7 @@ export const VirtualizedMultiSectionViewer = memo(
title={title}
context={sectionContext}
media={sectionMedia}
+ commentCount={sectionCommentCount}
/>
);
}
@@ -412,6 +427,14 @@ export const VirtualizedMultiSectionViewer = memo(
const row = treeNodeToFlatRow(node, virtualRow.index);
const matchCount = matchCounts?.get(row.id);
+ // Get comment ranges for this row
+ const commentRanges = getCommentRangesForRow(
+ row,
+ node.sectionKey,
+ commentedPathsByField,
+ );
+ const rowJsonPath = pathArrayToJsonPath(row.pathArray);
+
return (
<div
key={virtualRow.key}
@@ -480,6 +503,9 @@ export const VirtualizedMultiSectionViewer = memo(
enableCopy={enableCopy}
stringWrapMode={stringWrapMode}
truncateStringsAt={truncateStringsAt}
+ jsonPath={rowJsonPath}
+ commentRanges={commentRanges}
+ sectionKey={node.sectionKey}
/>
</div>
</div>
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonKey.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonKey.tsx
index 5ab08267d2..849b61124e 100644
--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonKey.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonKey.tsx
@@ -6,7 +6,15 @@
import { type JsonKeyProps } from "../types";
import { isArrayIndex } from "../utils/jsonTypes";
-import { highlightText } from "../utils/searchJson";
+import {
+ highlightTextWithComments,
+ COMMENT_HIGHLIGHT_COLOR,
+} from "../utils/highlightText";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
export function JsonKey({
keyName,
@@ -14,13 +22,29 @@ export function JsonKey({
isArrayIndex: isArrayIndexProp,
highlightStart,
highlightEnd,
+ commentRanges,
className,
}: JsonKeyProps) {
const isIndex = isArrayIndexProp ?? isArrayIndex(keyName);
const keyString = String(keyName);
- // Apply search highlighting if present
- const segments = highlightText(keyString, highlightStart, highlightEnd);
+ // Filter comment ranges to only those that overlap with the key
+ // Key starts at offset 0, so we filter ranges where start < keyLength
+ const keyCommentRanges = commentRanges
+ ?.map((range) => ({
+ start: Math.max(0, range.start),
+ end: Math.min(keyString.length, range.end),
+ preview: range.preview,
+ }))
+ .filter((range) => range.end > 0 && range.start < range.end);
+
+ // Apply search and comment highlighting
+ const segments = highlightTextWithComments(
+ keyString,
+ highlightStart,
+ highlightEnd,
+ keyCommentRanges,
+ );
return (
<span
@@ -33,18 +57,38 @@ export function JsonKey({
whiteSpace: "nowrap", // Keep key on single line
}}
>
- {segments.map((segment, index) => (
- <span
- key={index}
- style={{
- backgroundColor: segment.isHighlight
- ? theme.searchMatchBackground
- : "transparent",
- }}
- >
- {segment.text}
- </span>
- ))}
+ {segments.map((segment, index) => {
+ const backgroundColor =
+ segment.type === "search"
+ ? theme.searchMatchBackground
+ : segment.type === "comment"
+ ? COMMENT_HIGHLIGHT_COLOR
+ : "transparent";
+
+ const highlightedSpan = (
+ <span key={index} style={{ backgroundColor }}>
+ {segment.text}
+ </span>
+ );
+
+ // Wrap comment highlights in tooltip if preview exists
+ if (segment.type === "comment" && segment.preview) {
+ return (
+ <Tooltip key={index}>
+ <TooltipTrigger asChild>{highlightedSpan}</TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="max-w-xs px-2 py-1 text-xs"
+ >
+ {segment.preview}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return highlightedSpan;
+ })}
</span>
);
}
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx
index a69e81a0fc..e57afdc17c 100644
--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonRowScrollable.tsx
@@ -9,6 +9,7 @@ import type { FlatJSONRow, JSONTheme, SearchMatch } from "../types";
import { JsonKey } from "./JsonKey";
import { JsonValue } from "./JsonValue";
import { CopyButton } from "./CopyButton";
+import { type CommentRange } from "../utils/commentRanges";
export interface JsonRowScrollableProps {
row: FlatJSONRow;
@@ -19,6 +20,9 @@ export interface JsonRowScrollableProps {
searchMatch?: SearchMatch;
isCurrentMatch?: boolean;
className?: string;
+ jsonPath?: string;
+ commentRanges?: CommentRange[];
+ sectionKey?: string; // For inline comments - identifies which section (input/output/metadata) this row belongs to
}
export function JsonRowScrollable({
@@ -30,11 +34,22 @@ export function JsonRowScrollable({
searchMatch,
isCurrentMatch = false,
className,
+ jsonPath,
+ commentRanges,
+ sectionKey,
}: JsonRowScrollableProps) {
const isKey = searchMatch?.matchType === "key";
const isValue = searchMatch?.matchType === "value";
- // Calculate background based on search match
+ // Calculate value offset within the row for adjusting comment ranges
+ // Row renders as: key:"value" for strings, key:value for others
+ // commentRanges are row-relative, need to adjust for value-only highlighting
+ const keyLength = String(row.key).length;
+ const colonLength = 1;
+ const quoteLength = row.type === "string" ? 1 : 0; // only strings have opening quote
+ const valueOffset = keyLength + colonLength + quoteLength;
+
+ // Calculate background based on search match only (comment highlighting is now character-level)
const backgroundColor = isCurrentMatch
? theme.searchCurrentBackground
: searchMatch
@@ -44,6 +59,9 @@ export function JsonRowScrollable({
return (
<div
className={className}
+ data-json-path={jsonPath}
+ data-section-key={sectionKey}
+ data-json-key-value="true"
style={{
display: "flex",
alignItems: "start",
@@ -64,6 +82,7 @@ export function JsonRowScrollable({
theme={theme}
highlightStart={isKey ? searchMatch.highlightStart : undefined}
highlightEnd={isKey ? searchMatch.highlightEnd : undefined}
+ commentRanges={commentRanges}
/>
{/* Colon separator */}
@@ -89,6 +108,8 @@ export function JsonRowScrollable({
truncateStringsAt={truncateStringsAt}
highlightStart={isValue ? searchMatch?.highlightStart : undefined}
highlightEnd={isValue ? searchMatch?.highlightEnd : undefined}
+ commentRanges={commentRanges}
+ valueOffset={valueOffset}
/>
{/* Copy button (optional, on hover) */}
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx
index f24a720d01..1a8ce4ce41 100644
--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx
@@ -7,8 +7,16 @@
import { type JsonValueProps } from "../types";
import { formatValuePreview } from "../utils/jsonTypes";
-import { highlightText } from "../utils/searchJson";
+import {
+ highlightTextWithComments,
+ COMMENT_HIGHLIGHT_COLOR,
+} from "../utils/highlightText";
import { TruncatedString } from "./TruncatedString";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
export function JsonValue({
value,
@@ -20,8 +28,18 @@ export function JsonValue({
truncateStringsAt = null,
highlightStart,
highlightEnd,
+ commentRanges,
+ valueOffset = 0,
className,
}: JsonValueProps) {
+ // Adjust comment ranges from row-relative to value-relative
+ const adjustedCommentRanges = commentRanges
+ ?.map((range) => ({
+ start: Math.max(0, range.start - valueOffset),
+ end: Math.max(0, range.end - valueOffset),
+ preview: range.preview,
+ }))
+ .filter((range) => range.end > 0 && range.start < range.end);
// For expandable values, show preview text
if (isExpandable) {
const preview = formatValuePreview(value);
@@ -77,13 +95,19 @@ export function JsonValue({
theme={theme}
highlightStart={highlightStart}
highlightEnd={highlightEnd}
+ commentRanges={adjustedCommentRanges}
/>
);
}
}
// Mode 2: "nowrap" or Mode 3: "wrap" - render with appropriate whiteSpace
- const segments = highlightText(str, highlightStart, highlightEnd);
+ const segments = highlightTextWithComments(
+ str,
+ highlightStart,
+ highlightEnd,
+ adjustedCommentRanges,
+ );
return (
<span
@@ -99,18 +123,37 @@ export function JsonValue({
}}
>
&quot;
- {segments.map((segment, index) => (
- <span
- key={index}
- style={{
- backgroundColor: segment.isHighlight
- ? theme.searchMatchBackground
- : "transparent",
- }}
- >
- {segment.text}
- </span>
- ))}
+ {segments.map((segment, index) => {
+ const backgroundColor =
+ segment.type === "search"
+ ? theme.searchMatchBackground
+ : segment.type === "comment"
+ ? COMMENT_HIGHLIGHT_COLOR
+ : "transparent";
+
+ const highlightedSpan = (
+ <span key={index} style={{ backgroundColor }}>
+ {segment.text}
+ </span>
+ );
+
+ if (segment.type === "comment" && segment.preview) {
+ return (
+ <Tooltip key={index}>
+ <TooltipTrigger asChild>{highlightedSpan}</TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="max-w-xs px-2 py-1 text-xs"
+ >
+ {segment.preview}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return highlightedSpan;
+ })}
&quot;
</span>
);
@@ -132,8 +175,13 @@ export function JsonValue({
}
})();
- // Apply search highlighting
- const segments = highlightText(displayValue, highlightStart, highlightEnd);
+ // Apply search and comment highlighting
+ const segments = highlightTextWithComments(
+ displayValue,
+ highlightStart,
+ highlightEnd,
+ adjustedCommentRanges,
+ );
return (
<span
@@ -143,18 +191,37 @@ export function JsonValue({
fontFamily: "monospace",
}}
>
- {segments.map((segment, index) => (
- <span
- key={index}
- style={{
- backgroundColor: segment.isHighlight
- ? theme.searchMatchBackground
- : "transparent",
- }}
- >
- {segment.text}
- </span>
- ))}
+ {segments.map((segment, index) => {
+ const backgroundColor =
+ segment.type === "search"
+ ? theme.searchMatchBackground
+ : segment.type === "comment"
+ ? COMMENT_HIGHLIGHT_COLOR
+ : "transparent";
+
+ const highlightedSpan = (
+ <span key={index} style={{ backgroundColor }}>
+ {segment.text}
+ </span>
+ );
+
+ if (segment.type === "comment" && segment.preview) {
+ return (
+ <Tooltip key={index}>
+ <TooltipTrigger asChild>{highlightedSpan}</TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="max-w-xs px-2 py-1 text-xs"
+ >
+ {segment.preview}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return highlightedSpan;
+ })}
</span>
);
}
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsx b/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsx
index 63071afbe9..919fdd7c08 100644
--- a/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/components/MultiSectionJsonViewerHeader.tsx
@@ -1,4 +1,4 @@
-import { ChevronRight, ChevronDown } from "lucide-react";
+import { ChevronRight, ChevronDown, MessageSquare } from "lucide-react";
import type { SectionContext } from "../types";
import { type MediaReturnType } from "@/src/features/media/validation";
import { MediaButtonGroup } from "./MediaButtonGroup";
@@ -10,6 +10,8 @@ export interface MultiSectionJsonViewerHeaderProps {
context: SectionContext;
/** Media attachments for this section (optional) */
media?: MediaReturnType[];
+ /** Number of comments in this section (optional) */
+ commentCount?: number;
}
/**
@@ -23,6 +25,7 @@ export function MultiSectionJsonViewerHeader({
title,
context,
media,
+ commentCount,
}: MultiSectionJsonViewerHeaderProps) {
return (
<div
@@ -63,6 +66,21 @@ export function MultiSectionJsonViewerHeader({
>
{context.rowCount.toLocaleString()} keys
</span>
+ {commentCount !== undefined && commentCount > 0 && (
+ <span
+ className="text-muted-foreground"
+ style={{
+ marginLeft: "8px",
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "3px",
+ fontSize: "0.65rem",
+ }}
+ >
+ <MessageSquare size={10} />
+ {commentCount}
+ </span>
+ )}
<div style={{ marginLeft: "auto" }}>
{media && media.length > 0 && <MediaButtonGroup media={media} />}
</div>
diff --git a/web/src/components/ui/AdvancedJsonViewer/components/TruncatedString.tsx b/web/src/components/ui/AdvancedJsonViewer/components/TruncatedString.tsx
index b8ae445cac..8817a2c244 100644
--- a/web/src/components/ui/AdvancedJsonViewer/components/TruncatedString.tsx
+++ b/web/src/components/ui/AdvancedJsonViewer/components/TruncatedString.tsx
@@ -11,8 +11,17 @@ import {
HoverCardContent,
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
import { type JSONTheme } from "../types";
-import { highlightText } from "../utils/searchJson";
+import {
+ highlightTextWithComments,
+ COMMENT_HIGHLIGHT_COLOR,
+} from "../utils/highlightText";
+import { type CommentRange } from "../utils/commentRanges";
interface TruncatedStringProps {
value: string;
@@ -20,6 +29,7 @@ interface TruncatedStringProps {
theme: JSONTheme;
highlightStart?: number;
highlightEnd?: number;
+ commentRanges?: CommentRange[];
}
export function TruncatedString({
@@ -28,6 +38,7 @@ export function TruncatedString({
theme,
highlightStart,
highlightEnd,
+ commentRanges,
}: TruncatedStringProps) {
const isTruncated = value.length > maxLength;
// Still slice for performance (avoid rendering massive strings in DOM)
@@ -46,7 +57,12 @@ export function TruncatedString({
}, [isTruncated]);
// Apply highlighting to display value
- const segments = highlightText(displayValue, highlightStart, highlightEnd);
+ const segments = highlightTextWithComments(
+ displayValue,
+ highlightStart,
+ highlightEnd,
+ commentRanges,
+ );
if (!isTruncated) {
// No truncation needed, just render normally
@@ -58,18 +74,37 @@ export function TruncatedString({
}}
>
&quot;
- {segments.map((segment, index) => (
- <span
- key={index}
- style={{
- backgroundColor: segment.isHighlight
- ? theme.searchMatchBackground
- : "transparent",
- }}
- >
- {segment.text}
- </span>
- ))}
+ {segments.map((segment, index) => {
+ const backgroundColor =
+ segment.type === "search"
+ ? theme.searchMatchBackground
+ : segment.type === "comment"
+ ? COMMENT_HIGHLIGHT_COLOR
+ : "transparent";
+
+ const highlightedSpan = (
+ <span key={index} style={{ backgroundColor }}>
+ {segment.text}
+ </span>
+ );
+
+ if (segment.type === "comment" && segment.preview) {
+ return (
+ <Tooltip key={index}>
+ <TooltipTrigger asChild>{highlightedSpan}</TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="max-w-xs px-2 py-1 text-xs"
+ >
+ {segment.preview}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return highlightedSpan;
+ })}
&quot;
</span>
);
@@ -94,18 +129,20 @@ export function TruncatedString({
}}
>
<span>&quot;</span>
- {segments.map((segment, index) => (
- <span
- key={index}
- style={{
- backgroundColor: segment.isHighlight
- ? theme.searchMatchBackground
- : "transparent",
- }}
- >
- {segment.text}
- </span>
- ))}
+ {segments.map((segment, index) => {
+ const backgroundColor =
+ segment.type === "search"
+ ? theme.searchMatchBackground
+ : segment.type === "comment"
+ ? COMMENT_HIGHLIGHT_COLOR
+ : "transparent";
+
+ return (
+ <span key={index} style={{ backgroundColor }}>
+ {segment.text}
+ </span>
+ );
+ })}
<span>&quot;</span>
</span>
</HoverCardTrigger>
diff --git a/web/src/components/ui/AdvancedJsonViewer/types.ts b/web/src/components/ui/AdvancedJsonViewer/types.ts
index 740ac0152a..48090477bf 100644
--- a/web/src/components/ui/AdvancedJsonViewer/types.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/types.ts
@@ -2,10 +2,10 @@
* Type definitions for AdvancedJsonViewer
*
* All TypeScript interfaces and types used throughout the component.
- * Self-contained with no external dependencies.
*/
import type { RefObject } from "react";
+import type { CommentRange } from "./utils/commentRanges";
// ============================================================================
// JSON Value Types
@@ -255,6 +255,8 @@ export interface AdvancedJsonViewerProps {
/** Ref to the scroll container (for proper scroll-to behavior) */
scrollContainerRef?: RefObject<HTMLDivElement | null>;
+
+ commentedPaths?: Map<string, Array<{ start: number; end: number }>>;
}
/**
@@ -333,6 +335,11 @@ export interface JsonValueProps {
highlightStart?: number;
highlightEnd?: number;
+ commentRanges?: CommentRange[];
+
+ /** Offset of value within the row (for adjusting row-relative commentRanges to value-relative) */
+ valueOffset?: number;
+
/** Custom CSS class */
className?: string;
}
@@ -354,6 +361,9 @@ export interface JsonKeyProps {
highlightStart?: number;
highlightEnd?: number;
+ /** Comment ranges (row-relative offsets, will be clipped to key boundaries) */
+ commentRanges?: CommentRange[];
+
/** Custom CSS class */
className?: string;
}
diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/commentRanges.ts b/web/src/components/ui/AdvancedJsonViewer/utils/commentRanges.ts
new file mode 100644
index 0000000000..c6a5433a84
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/utils/commentRanges.ts
@@ -0,0 +1,69 @@
+/**
+ * Utilities for handling inline comment ranges in JSON viewer
+ */
+
+import { pathArrayToJsonPath } from "./pathUtils";
+import type { FlatJSONRow } from "../types";
+
+/**
+ * A single comment range with optional preview text
+ */
+export type CommentRange = {
+ start: number;
+ end: number;
+ preview?: string; // First 150 chars of comment content for tool tip
+};
+
+/**
+ * Type for comment ranges organized by field (input/output/metadata)
+ */
+export type CommentedPathsByField = {
+ input?: Map<string, CommentRange[]>;
+ output?: Map<string, CommentRange[]>;
+ metadata?: Map<string, CommentRange[]>;
+};
+
+/**
+ * Gets the number of unique paths with comments for a section.
+ */
+export function getCommentCountForSection(
+ sectionKey: string | undefined,
+ commentedPathsByField: CommentedPathsByField | undefined,
+): number {
+ if (!sectionKey || !commentedPathsByField) return 0;
+
+ if (
+ sectionKey !== "input" &&
+ sectionKey !== "output" &&
+ sectionKey !== "metadata"
+ ) {
+ return 0;
+ }
+
+ return commentedPathsByField[sectionKey]?.size ?? 0;
+}
+
+/**
+ * Gets comment ranges for a specific JSON row.
+ * Used by multi-section viewers to pass comment highlighting data to row components.
+ */
+export function getCommentRangesForRow(
+ row: FlatJSONRow,
+ sectionKey: string | undefined,
+ commentedPathsByField: CommentedPathsByField | undefined,
+): CommentRange[] | undefined {
+ if (!sectionKey || !commentedPathsByField) return undefined;
+
+ // Type-safe check for valid section keys
+ if (
+ sectionKey !== "input" &&
+ sectionKey !== "output" &&
+ sectionKey !== "metadata"
+ ) {
+ return undefined;
+ }
+
+ const rowJsonPath = pathArrayToJsonPath(row.pathArray);
+ const commentedPaths = commentedPathsByField[sectionKey];
+ return commentedPaths?.get(rowJsonPath);
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/highlightText.ts b/web/src/components/ui/AdvancedJsonViewer/utils/highlightText.ts
new file mode 100644
index 0000000000..40bfec1b7f
--- /dev/null
+++ b/web/src/components/ui/AdvancedJsonViewer/utils/highlightText.ts
@@ -0,0 +1,102 @@
+/**
+ * Highlight text utilities for rendering search and comment highlights
+ */
+
+import { type CommentRange } from "./commentRanges";
+
+/**
+ * Color for comment highlights (purple with medium opacity)
+ */
+export const COMMENT_HIGHLIGHT_COLOR = "rgba(147, 112, 219, 0.3)";
+
+/**
+ * Creates text segments with both search and comment highlights.
+ * Merges multiple highlight ranges and assigns types for different styling.
+ *
+ * @param text - The text to segment
+ * @param searchStart - Start position of search highlight (optional)
+ * @param searchEnd - End position of search highlight (optional)
+ * @param commentRanges - Array of comment ranges to highlight (optional)
+ * @returns Array of segments with highlight type information and optional preview
+ */
+export function highlightTextWithComments(
+ text: string,
+ searchStart?: number,
+ searchEnd?: number,
+ commentRanges?: CommentRange[],
+): Array<{
+ text: string;
+ type: "search" | "comment" | null;
+ preview?: string;
+}> {
+ if (
+ !commentRanges?.length &&
+ (searchStart === undefined || searchEnd === undefined)
+ ) {
+ return [{ text, type: null }];
+ }
+
+ const ranges: Array<{
+ start: number;
+ end: number;
+ type: "search" | "comment";
+ preview?: string;
+ }> = [];
+
+ if (searchStart !== undefined && searchEnd !== undefined) {
+ ranges.push({ start: searchStart, end: searchEnd, type: "search" });
+ }
+
+ if (commentRanges) {
+ commentRanges.forEach((range) => {
+ ranges.push({
+ start: range.start,
+ end: range.end,
+ type: "comment",
+ preview: range.preview,
+ });
+ });
+ }
+
+ ranges.sort((a, b) => a.start - b.start);
+
+ const segments: Array<{
+ text: string;
+ type: "search" | "comment" | null;
+ preview?: string;
+ }> = [];
+ let currentPos = 0;
+
+ ranges.forEach((range) => {
+ // Add text before this range
+ if (range.start > currentPos) {
+ segments.push({
+ text: text.slice(currentPos, range.start),
+ type: null,
+ });
+ }
+
+ // Add highlighted text (search takes priority over comment if overlapping)
+ const segmentStart = Math.max(range.start, currentPos);
+ const segmentEnd = range.end;
+
+ if (segmentEnd > segmentStart) {
+ segments.push({
+ text: text.slice(segmentStart, segmentEnd),
+ type: range.type,
+ preview: range.preview,
+ });
+ currentPos = Math.max(currentPos, segmentEnd);
+ }
+ });
+
+ // Add remaining text
+ if (currentPos < text.length) {
+ segments.push({
+ text: text.slice(currentPos),
+ type: null,
+ });
+ }
+
+ return segments;
+}
diff --git a/web/src/components/ui/AdvancedJsonViewer/utils/pathUtils.ts b/web/src/components/ui/AdvancedJsonViewer/utils/pathUtils.ts
index 4aa825c0cb..955e51714c 100644
--- a/web/src/components/ui/AdvancedJsonViewer/utils/pathUtils.ts
+++ b/web/src/components/ui/AdvancedJsonViewer/utils/pathUtils.ts
@@ -201,3 +201,36 @@ export function hasCollapsedAncestor(
return false;
}
+
+/**
+ * Convert a path array to JSON Path format
+ * The first element (rootKey) is ignored as JSON Path starts with $
+ *
+ * @example pathArrayToJsonPath(['root', 'users', 0, 'name']) => "$.users[0].name"
+ * @example pathArrayToJsonPath(['root']) => "$"
+ * @example pathArrayToJsonPath(['root', 'key-with-dash']) => "$['key-with-dash']"
+ */
+export function pathArrayToJsonPath(pathArray: (string | number)[]): string {
+ if (pathArray.length === 0) return "$";
+ if (pathArray.length === 1) return "$"; // Root only
+
+ // Skip the root key (first element)
+ const parts = pathArray.slice(1);
+
+ let jsonPath = "$";
+ for (const part of parts) {
+ if (typeof part === "number") {
+ // Array index
+ jsonPath += `[${part}]`;
+ } else if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(part)) {
+ // Simple key (valid identifier)
+ jsonPath += `.${part}`;
+ } else {
+ // Key with special characters - use bracket notation
+ // Escape backslashes first, then quotes (order matters for correctness)
+ jsonPath += `['${part.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}']`;
+ }
+ }
+
+ return jsonPath;
+}
diff --git a/web/src/features/comments/CommentDrawerButton.tsx b/web/src/features/comments/CommentDrawerButton.tsx
index c7ea0d91ad..e41f739fda 100644
--- a/web/src/features/comments/CommentDrawerButton.tsx
+++ b/web/src/features/comments/CommentDrawerButton.tsx
@@ -13,6 +13,7 @@ import { type CommentObjectType } from "@langfuse/shared";
import { MessageCircleIcon, MessageCircleOff } from "lucide-react";
import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/router";
+import { type SelectionData } from "./contexts/InlineCommentSelectionContext";
export function CommentDrawerButton({
projectId,
@@ -22,6 +23,10 @@ export function CommentDrawerButton({
variant = "secondary",
className,
size = "default",
+ pendingSelection,
+ onSelectionUsed,
+ isOpen: controlledIsOpen,
+ onOpenChange: controlledOnOpenChange,
}: {
projectId: string;
objectId: string;
@@ -30,11 +35,18 @@ export function CommentDrawerButton({
variant?: "secondary" | "outline";
className?: string;
size?: "default" | "sm" | "xs" | "lg" | "icon" | "icon-xs" | "icon-sm";
+ pendingSelection?: SelectionData | null;
+ onSelectionUsed?: () => void;
+ isOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
}) {
const router = useRouter();
const [isMentionDropdownOpen, setIsMentionDropdownOpen] = useState(false);
- const [isDrawerOpen, setIsDrawerOpen] = useState(false); // Note: We manually control to keep the drawer open on ESC press when the mention dropdown is open
+ const [internalIsDrawerOpen, setInternalIsDrawerOpen] = useState(false);
const hasAutoOpenedRef = useRef(false); // Track if we've already auto-opened for current deep link
+
+ const isDrawerOpen = controlledIsOpen ?? internalIsDrawerOpen;
+ const setIsDrawerOpen = controlledOnOpenChange ?? setInternalIsDrawerOpen;
const hasFocusedRef = useRef(false); // Track if we've already focused the drawer
const hasReadAccess = useHasProjectAccess({
@@ -87,6 +99,7 @@ export function CommentDrawerButton({
objectType,
objectId,
isDrawerOpen,
+ setIsDrawerOpen,
]);
if (!hasReadAccess || (!hasWriteAccess && !count))
@@ -191,6 +204,8 @@ export function CommentDrawerButton({
objectType={objectType}
onMentionDropdownChange={setIsMentionDropdownOpen}
isDrawerOpen={isDrawerOpen}
+ pendingSelection={pendingSelection}
+ onSelectionUsed={onSelectionUsed}
/>
</div>
</div>
diff --git a/web/src/features/comments/CommentList.tsx b/web/src/features/comments/CommentList.tsx
index 31960cee01..0282bd2724 100644
--- a/web/src/features/comments/CommentList.tsx
+++ b/web/src/features/comments/CommentList.tsx
@@ -16,6 +16,11 @@ import {
HoverCardContent,
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
import { MarkdownView } from "@/src/components/ui/MarkdownViewer";
import { Textarea } from "@/src/components/ui/textarea";
import { Input } from "@/src/components/ui/input";
@@ -43,6 +48,31 @@ import { ReactionPicker } from "@/src/features/comments/ReactionPicker";
import { ReactionBar } from "@/src/features/comments/ReactionBar";
import { stripMarkdown } from "@/src/utils/markdown";
import { MENTION_USER_PREFIX } from "@/src/features/comments/lib/mentionParser";
+import { type SelectionData } from "./contexts/InlineCommentSelectionContext";
+import { Badge } from "@/src/components/ui/badge";
+import { useTheme } from "next-themes";
+
+// IO field background colors - same as IOPreviewJSON.tsx
+const IO_FIELD_COLORS = {
+ input: { light: "rgb(249, 252, 255)", dark: "rgb(15, 23, 42)" },
+ output: { light: "rgb(248, 253, 250)", dark: "rgb(20, 30, 41)" },
+ metadata: { light: "rgb(253, 251, 254)", dark: "rgb(30, 20, 40)" },
+} as const;
+
+/**
+ * Convert JSON path to human-readable format
+ * $.messages[1].text → messages › 1 › text
+ * $ → (root)
+ */
+function humanizeJsonPath(path: string): string {
+ if (path === "$") return "(root)";
+ return path
+ .replace(/^\$\.?/, "") // remove leading $. or $
+ .replace(/\[(\d+)\]/g, ".$1") // [0] → .0
+ .split(".")
+ .filter(Boolean)
+ .join(" › ");
+}
const useIsomorphicLayoutEffect =
typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
@@ -56,6 +86,8 @@ export function CommentList({
onDraftChange,
onMentionDropdownChange,
isDrawerOpen = false,
+ pendingSelection,
+ onSelectionUsed,
}: {
projectId: string;
objectId: string;
@@ -65,9 +97,13 @@ export function CommentList({
onDraftChange?: (hasDraft: boolean) => void;
onMentionDropdownChange?: (isOpen: boolean) => void;
isDrawerOpen?: boolean;
+ pendingSelection?: SelectionData | null;
+ onSelectionUsed?: () => void;
}) {
const session = useSession();
const router = useRouter();
+ const { resolvedTheme } = useTheme();
+ const isDark = resolvedTheme === "dark";
const [cursorPosition, setCursorPosition] = useState(0);
const [searchQuery, setSearchQuery] = useState("");
const commentsContainerRef = useRef<HTMLDivElement>(null);
@@ -217,6 +253,16 @@ export function CommentList({
}
}, [comments.data, highlightedCommentId]);
+ // Focus textarea when pendingSelection changes (user clicked comment button)
+ useEffect(() => {
+ if (pendingSelection && textareaRef.current) {
+ // Delay to allow drawer animation to complete
+ setTimeout(() => {
+ textareaRef.current?.focus();
+ }, 150);
+ }
+ }, [pendingSelection]);
+
// CMD+F keyboard shortcut to focus search (only when drawer is open)
useEffect(() => {
if (!isDrawerOpen) return; // Only capture when drawer is open
@@ -253,6 +299,9 @@ export function CommentList({
await Promise.all([utils.comments.invalidate()]);
form.reset();
+ // Clear pending selection after successful comment creation
+ onSelectionUsed?.();
+
// Reset textarea height
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
@@ -364,6 +413,10 @@ export function CommentList({
function onSubmit(values: z.infer<typeof CreateCommentData>) {
createCommentMutation.mutateAsync({
...values,
+ dataField: pendingSelection?.dataField,
+ path: pendingSelection?.path,
+ rangeStart: pendingSelection?.rangeStart,
+ rangeEnd: pendingSelection?.rangeEnd,
});
}
@@ -538,6 +591,41 @@ export function CommentList({
className="border-none p-0 py-1 text-xs [&_h1]:text-[0.9rem] [&_h1]:font-semibold [&_h2]:text-[0.85rem] [&_h2]:font-semibold [&_h3]:text-[0.8rem] [&_h3]:font-semibold [&_h4]:text-xs [&_h4]:font-medium [&_h5]:text-xs [&_h5]:font-medium [&_h6]:text-xs [&_h6]:font-medium [&_li]:text-xs [&_ol]:text-xs [&_p]:text-xs [&_ul]:text-xs"
/>
+ {/* Inline comment position indicator */}
+ {"dataField" in comment &&
+ comment.dataField &&
+ "path" in comment &&
+ Array.isArray(comment.path) &&
+ comment.path.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="mt-1 flex w-fit items-center gap-1.5 text-xs">
+ <Badge
+ className="pointer-events-none px-1.5 py-0 text-[10px] font-medium text-foreground"
+ style={{
+ backgroundColor:
+ IO_FIELD_COLORS[
+ comment.dataField as keyof typeof IO_FIELD_COLORS
+ ]?.[isDark ? "dark" : "light"],
+ }}
+ >
+ {comment.dataField.toUpperCase()}
+ </Badge>
+ <span className="text-muted-foreground">
+ {humanizeJsonPath(comment.path[0])}
+ </span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent
+ side="top"
+ align="start"
+ className="px-2 py-1 text-xs"
+ >
+ The location of the text commented on
+ </TooltipContent>
+ </Tooltip>
+ )}
+
{/* Reactions */}
<div className="mt-2 flex flex-wrap items-center gap-1.5">
<ReactionBar
diff --git a/web/src/features/comments/components/CommentableJsonView.tsx b/web/src/features/comments/components/CommentableJsonView.tsx
new file mode 100644
index 0000000000..b1a113d412
--- /dev/null
+++ b/web/src/features/comments/components/CommentableJsonView.tsx
@@ -0,0 +1,31 @@
+/**
+ * CommentableJsonView - Wrapper component that enables text selection for inline comments
+ *
+ * Wraps JSON viewer content and tracks text selection to enable inline comments.
+ */
+
+import { useRef, type ReactNode } from "react";
+import { useTextSelection } from "../hooks/useTextSelection";
+
+interface CommentableJsonViewProps {
+ children: ReactNode;
+ dataField?: "input" | "output" | "metadata"; // Optional - auto-detected from [data-section-key] in DOM if not provided
+ enabled?: boolean;
+ className?: string;
+}
+
+export function CommentableJsonView({
+ children,
+ dataField,
+ enabled = true,
+ className,
+}: CommentableJsonViewProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ useTextSelection({ containerRef, dataField, enabled });
+
+ return (
+ <div ref={containerRef} className={className}>
+ {children}
+ </div>
+ );
+}
diff --git a/web/src/features/comments/components/InlineCommentBubble.tsx b/web/src/features/comments/components/InlineCommentBubble.tsx
new file mode 100644
index 0000000000..86e1b1b010
--- /dev/null
+++ b/web/src/features/comments/components/InlineCommentBubble.tsx
@@ -0,0 +1,69 @@
+/**
+ * InlineCommentBubble - floating button shown when text is selected in JSON view
+ *
+ * Appears near the selection and allows user to add an inline comment.
+ */
+
+import { Button } from "@/src/components/ui/button";
+import { useInlineCommentSelectionOptional } from "../contexts/InlineCommentSelectionContext";
+import { MessageSquarePlus } from "lucide-react";
+import { useEffect, useState } from "react";
+
+interface InlineCommentBubbleProps {
+ onAddComment: () => void;
+}
+
+export function InlineCommentBubble({
+ onAddComment,
+}: InlineCommentBubbleProps) {
+ const context = useInlineCommentSelectionOptional();
+ const [position, setPosition] = useState<{
+ top: number;
+ left: number;
+ } | null>(null);
+
+ useEffect(() => {
+ const selection = context?.selection;
+ if (!selection?.anchorRect) {
+ setPosition(null);
+ return;
+ }
+
+ // Use startRect if available (position of selection start), fallback to anchorRect
+ const posRect = selection.startRect ?? selection.anchorRect;
+ // Position just above where the selection starts
+ setPosition({
+ top: posRect.top - 6,
+ left: posRect.left,
+ });
+ }, [context?.selection]);
+
+ if (!context?.selection || !position) return null;
+
+ const handleClick = () => {
+ onAddComment();
+ };
+
+ return (
+ <div
+ style={{
+ position: "fixed",
+ top: position.top,
+ left: position.left,
+ transform: "translateY(-100%)",
+ zIndex: 50,
+ }}
+ className="duration-100 animate-in fade-in-0 zoom-in-95"
+ >
+ <Button
+ size="xs"
+ variant="secondary"
+ onClick={handleClick}
+ className="border border-border bg-background px-3 py-2.5 text-muted-foreground shadow-md hover:bg-muted hover:text-foreground"
+ >
+ <MessageSquarePlus className="h-3 w-3" />
+ <span className="ml-1">Comment</span>
+ </Button>
+ </div>
+ );
+}
diff --git a/web/src/features/comments/contexts/InlineCommentSelectionContext.tsx b/web/src/features/comments/contexts/InlineCommentSelectionContext.tsx
new file mode 100644
index 0000000000..f8d3198e4c
--- /dev/null
+++ b/web/src/features/comments/contexts/InlineCommentSelectionContext.tsx
@@ -0,0 +1,71 @@
+import {
+ createContext,
+ useContext,
+ useState,
+ useCallback,
+ type ReactNode,
+} from "react";
+
+export interface SelectionData {
+ dataField: "input" | "output" | "metadata";
+ path: string[];
+ rangeStart: number[];
+ rangeEnd: number[];
+ selectedText: string;
+ anchorRect: DOMRect | null;
+ startRect?: DOMRect; // Position of selection start (for bubble positioning)
+}
+
+interface InlineCommentSelectionContextType {
+ selection: SelectionData | null;
+ setSelection: (selection: SelectionData | null) => void;
+ clearSelection: () => void;
+ isSelecting: boolean;
+}
+
+const InlineCommentSelectionContext =
+ createContext<InlineCommentSelectionContextType | null>(null);
+
+export function InlineCommentSelectionProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const [selection, setSelection] = useState<SelectionData | null>(null);
+
+ const clearSelection = useCallback(() => {
+ setSelection(null);
+ window.getSelection()?.removeAllRanges();
+ }, []);
+
+ return (
+ <InlineCommentSelectionContext.Provider
+ value={{
+ selection,
+ setSelection,
+ clearSelection,
+ isSelecting: selection !== null,
+ }}
+ >
+ {children}
+ </InlineCommentSelectionContext.Provider>
+ );
+}
+
+export function useInlineCommentSelection() {
+ const context = useContext(InlineCommentSelectionContext);
+ if (!context) {
+ throw new Error(
+ "useInlineCommentSelection must be used within InlineCommentSelectionProvider",
+ );
+ }
+ return context;
+}
+
+/**
+ * Optional hook that doesn't throw if context is missing.
+ * Useful for components that may or may not be inside the provider.
+ */
+export function useInlineCommentSelectionOptional() {
+ return useContext(InlineCommentSelectionContext);
+}
diff --git a/web/src/features/comments/hooks/useCommentedPaths.ts b/web/src/features/comments/hooks/useCommentedPaths.ts
new file mode 100644
index 0000000000..cb2f32a238
--- /dev/null
+++ b/web/src/features/comments/hooks/useCommentedPaths.ts
@@ -0,0 +1,69 @@
+import { useMemo } from "react";
+import {
+ type CommentRange,
+ type CommentedPathsByField,
+} from "@/src/components/ui/AdvancedJsonViewer/utils/commentRanges";
+
+interface CommentWithPosition {
+ content: string;
+ dataField: string | null;
+ path: string[];
+ rangeStart: number[];
+ rangeEnd: number[];
+}
+
+/**
+ * Builds Maps of JSON paths to comment ranges, keyed by field (input/output/metadata).
+ * Used to highlight commented text in the JSON viewer.
+ */
+export function useCommentedPaths(
+ comments: CommentWithPosition[] | undefined,
+): CommentedPathsByField | undefined {
+ return useMemo(() => {
+ if (!comments) return undefined;
+
+ const inputMap = new Map<string, Array<CommentRange>>();
+ const outputMap = new Map<string, Array<CommentRange>>();
+ const metadataMap = new Map<string, Array<CommentRange>>();
+
+ for (const comment of comments) {
+ // Only process comments with position data (inline comments)
+ if (
+ comment.dataField &&
+ comment.path &&
+ comment.path.length > 0 &&
+ comment.rangeStart &&
+ comment.rangeStart.length > 0 &&
+ comment.rangeEnd &&
+ comment.rangeEnd.length > 0
+ ) {
+ // Each path[i] gets its corresponding range from rangeStart[i]/rangeEnd[i]
+ comment.path.forEach((jsonPath, i) => {
+ const range: CommentRange = {
+ start: comment.rangeStart[i]!,
+ end: comment.rangeEnd[i]!,
+ preview:
+ comment.content.length > 150
+ ? comment.content.slice(0, 150) + "..."
+ : comment.content,
+ };
+
+ let targetMap;
+ if (comment.dataField === "input") targetMap = inputMap;
+ else if (comment.dataField === "output") targetMap = outputMap;
+ else if (comment.dataField === "metadata") targetMap = metadataMap;
+ else return;
+
+ const existing = targetMap.get(jsonPath) || [];
+ targetMap.set(jsonPath, [...existing, range]);
+ });
+ }
+ }
+
+ return {
+ input: inputMap.size > 0 ? inputMap : undefined,
+ output: outputMap.size > 0 ? outputMap : undefined,
+ metadata: metadataMap.size > 0 ? metadataMap : undefined,
+ };
+ }, [comments]);
+}
diff --git a/web/src/features/comments/hooks/useTextSelection.ts b/web/src/features/comments/hooks/useTextSelection.ts
new file mode 100644
index 0000000000..76ae7d4a85
--- /dev/null
+++ b/web/src/features/comments/hooks/useTextSelection.ts
@@ -0,0 +1,100 @@
+import { useEffect, useCallback, useRef } from "react";
+import { useInlineCommentSelectionOptional } from "../contexts/InlineCommentSelectionContext";
+import { selectionToPath } from "../lib/selectionToPath";
+
+interface UseTextSelectionOptions {
+ containerRef: React.RefObject<HTMLElement | null>;
+ dataField?: "input" | "output" | "metadata"; // Optional - auto-detected from [data-section-key] if not provided
+ enabled?: boolean;
+}
+
+/**
+ * Finds the section key (input/output/metadata) from the DOM by looking for
+ * the closest ancestor with [data-section-key] attribute.
+ */
+function detectSectionFromDOM(
+ node: Node,
+): "input" | "output" | "metadata" | null {
+ let current: Node | null = node;
+ while (current && current !== document.body) {
+ if (current instanceof HTMLElement && current.dataset.sectionKey) {
+ const key = current.dataset.sectionKey;
+ if (key === "input" || key === "output" || key === "metadata") {
+ return key;
+ }
+ }
+ current = current.parentNode;
+ }
+ return null;
+}
+
+export function useTextSelection({
+ containerRef,
+ dataField,
+ enabled = true,
+}: UseTextSelectionOptions) {
+ const context = useInlineCommentSelectionOptional();
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const handleSelectionChange = useCallback(() => {
+ if (!enabled || !containerRef.current || !context) return;
+
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+
+ debounceRef.current = setTimeout(() => {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed) {
+ // Only clear if the interaction was INSIDE our container
+ // If user clicked elsewhere (like comment textarea), keep the pending selection
+ const focusNode = selection?.focusNode;
+ if (focusNode && containerRef.current?.contains(focusNode)) {
+ context.clearSelection();
+ }
+ // Otherwise, don't clear - user might be interacting with comment UI
+ return;
+ }
+
+ const range = selection.getRangeAt(0);
+ if (!containerRef.current?.contains(range.commonAncestorContainer)) {
+ return; // Selection outside our container
+ }
+
+ // Determine dataField - use prop if provided, otherwise detect from DOM
+ const effectiveDataField =
+ dataField ?? detectSectionFromDOM(range.startContainer);
+ if (!effectiveDataField) {
+ return;
+ }
+
+ const result = selectionToPath(
+ selection,
+ containerRef.current,
+ effectiveDataField,
+ );
+ if (result) {
+ // Get the position of the selection START (not the full bounding box)
+ // This gives us where to position the comment bubble
+ const startRange = range.cloneRange();
+ startRange.collapse(true); // Collapse to start
+ const startRect = startRange.getBoundingClientRect();
+
+ context.setSelection({
+ ...result,
+ anchorRect: range.getBoundingClientRect(),
+ startRect,
+ });
+ }
+ }, 150);
+ }, [enabled, containerRef, dataField, context]);
+
+ useEffect(() => {
+ if (!enabled || !context) return;
+ document.addEventListener("selectionchange", handleSelectionChange);
+ return () => {
+ document.removeEventListener("selectionchange", handleSelectionChange);
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ };
+ }, [enabled, handleSelectionChange, context]);
+
+ return { clearSelection: context?.clearSelection };
+}
diff --git a/web/src/features/comments/lib/selectionToPath.ts b/web/src/features/comments/lib/selectionToPath.ts
new file mode 100644
index 0000000000..54a696fcfc
--- /dev/null
+++ b/web/src/features/comments/lib/selectionToPath.ts
@@ -0,0 +1,217 @@
+/**
+ * Converts a DOM Selection to JSON path and character range.
+ *
+ * Relies on data-json-path and data-json-key-value attributes
+ * added to AdvancedJsonViewer DOM elements.
+ */
+
+interface SelectionPathResult {
+ dataField: "input" | "output" | "metadata";
+ path: string[];
+ rangeStart: number[];
+ rangeEnd: number[];
+ selectedText: string;
+}
+
+export function selectionToPath(
+ selection: Selection,
+ containerElement: HTMLElement,
+ dataField: "input" | "output" | "metadata",
+): SelectionPathResult | null {
+ if (selection.rangeCount === 0 || selection.isCollapsed) {
+ return null;
+ }
+
+ const range = selection.getRangeAt(0);
+ const selectedText = range.toString();
+
+ if (!selectedText.trim()) {
+ return null;
+ }
+
+ // Find JSON path and key-value element for start
+ const startPath = findJsonPath(range.startContainer);
+ const startKeyValue = findKeyValueElement(range.startContainer);
+
+ // Find JSON path and key-value element for end
+ const endPath = findJsonPath(range.endContainer);
+ const endKeyValue = findKeyValueElement(range.endContainer);
+
+ if (!startPath || !startKeyValue) {
+ return null;
+ }
+
+ if (!endPath || !endKeyValue) {
+ return null;
+ }
+
+ // Single row case: start and end in same key-value element
+ if (startKeyValue === endKeyValue) {
+ let startOffset = calculateOffset(
+ range.startContainer,
+ range.startOffset,
+ startKeyValue,
+ );
+ let endOffset = calculateOffset(
+ range.endContainer,
+ range.endOffset,
+ startKeyValue,
+ );
+
+ // Normalize: ensure start <= end (handle backwards selection)
+ if (startOffset > endOffset) {
+ [startOffset, endOffset] = [endOffset, startOffset];
+ }
+
+ return {
+ dataField,
+ path: [startPath],
+ rangeStart: [startOffset],
+ rangeEnd: [endOffset],
+ selectedText,
+ };
+ }
+
+ // Multi-row case: selection spans multiple key-value elements
+ const rows = collectRowsBetween(startKeyValue, endKeyValue, containerElement);
+ if (rows.length === 0) {
+ return null;
+ }
+
+ // Determine if selection is backwards (user dragged up)
+ const isBackwards = rows[0] !== startKeyValue;
+ const [firstContainer, firstOffset] = isBackwards
+ ? [range.endContainer, range.endOffset]
+ : [range.startContainer, range.startOffset];
+ const [lastContainer, lastOffset] = isBackwards
+ ? [range.startContainer, range.startOffset]
+ : [range.endContainer, range.endOffset];
+
+ const paths: string[] = [];
+ const rangeStarts: number[] = [];
+ const rangeEnds: number[] = [];
+
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i];
+ const rowPath = row.dataset.jsonPath;
+ if (!rowPath) continue; // Skip structural elements without path
+
+ if (i === 0) {
+ // First row: from selection start to end of row
+ paths.push(rowPath);
+ rangeStarts.push(calculateOffset(firstContainer, firstOffset, row));
+ rangeEnds.push(getRowTextLength(row));
+ } else if (i === rows.length - 1) {
+ // Last row: from 0 to selection end
+ paths.push(rowPath);
+ rangeStarts.push(0);
+ rangeEnds.push(calculateOffset(lastContainer, lastOffset, row));
+ } else {
+ // Middle rows: entire row (0 → end)
+ paths.push(rowPath);
+ rangeStarts.push(0);
+ rangeEnds.push(getRowTextLength(row));
+ }
+ }
+
+ if (paths.length === 0) {
+ return null;
+ }
+
+ return {
+ dataField,
+ path: paths,
+ rangeStart: rangeStarts,
+ rangeEnd: rangeEnds,
+ selectedText,
+ };
+}
+
+function findJsonPath(node: Node): string | null {
+ let current: Node | null = node;
+ while (current && current !== document.body) {
+ if (current instanceof HTMLElement && current.dataset.jsonPath) {
+ return current.dataset.jsonPath;
+ }
+ current = current.parentNode;
+ }
+ return null;
+}
+
+function findKeyValueElement(node: Node): HTMLElement | null {
+ let current: Node | null = node;
+ while (current && current !== document.body) {
+ if (current instanceof HTMLElement && current.dataset.jsonKeyValue) {
+ return current;
+ }
+ current = current.parentNode;
+ }
+ return null;
+}
+
+function calculateOffset(
+ container: Node,
+ offset: number,
+ keyValueElement: HTMLElement,
+): number {
+ const walker = document.createTreeWalker(
+ keyValueElement,
+ NodeFilter.SHOW_TEXT,
+ null,
+ );
+ let charCount = 0;
+ let node = walker.nextNode();
+
+ while (node) {
+ if (node === container) {
+ return charCount + offset;
+ }
+ charCount += node.textContent?.length || 0;
+ node = walker.nextNode();
+ }
+
+ return charCount + offset;
+}
+
+/**
+ * Gets total text length of a key-value row element.
+ */
+function getRowTextLength(keyValueElement: HTMLElement): number {
+ let length = 0;
+ const walker = document.createTreeWalker(
+ keyValueElement,
+ NodeFilter.SHOW_TEXT,
+ null,
+ );
+ let node = walker.nextNode();
+ while (node) {
+ length += node.textContent?.length || 0;
+ node = walker.nextNode();
+ }
+ return length;
+}
+
+/**
+ * Collects all row elements between startRow and endRow (inclusive).
+ * Handles both forward and backward selections.
+ */
+function collectRowsBetween(
+ startRow: HTMLElement,
+ endRow: HTMLElement,
+ container: HTMLElement,
+): HTMLElement[] {
+ const allRows = Array.from(
+ container.querySelectorAll<HTMLElement>("[data-json-key-value]"),
+ );
+
+ const startIdx = allRows.indexOf(startRow);
+ const endIdx = allRows.indexOf(endRow);
+
+ if (startIdx === -1 || endIdx === -1) return [];
+
+ // Handle backwards selection
+ const [minIdx, maxIdx] =
+ startIdx <= endIdx ? [startIdx, endIdx] : [endIdx, startIdx];
+
+ return allRows.slice(minIdx, maxIdx + 1);
+}
diff --git a/web/src/features/public-api/types/comments.ts b/web/src/features/public-api/types/comments.ts
index 15eac72525..831c3a80b8 100644
--- a/web/src/features/public-api/types/comments.ts
+++ b/web/src/features/public-api/types/comments.ts
@@ -3,6 +3,7 @@ import {
CreateCommentData,
paginationMetaResponseZod,
publicApiPaginationZod,
+ COMMENT_DATA_FIELDS,
} from "@langfuse/shared";
import { z } from "zod/v4";
@@ -20,6 +21,10 @@ const APIComment = z
objectId: z.string(),
content: z.string().min(1).max(5000),
authorUserId: z.string().nullish(),
+ dataField: z.enum(COMMENT_DATA_FIELDS).nullish(),
+ path: z.array(z.string()).nullish(),
+ rangeStart: z.array(z.number()).nullish(),
+ rangeEnd: z.array(z.number()).nullish(),
})
.strict();
diff --git a/web/src/pages/api/public/comments/[commentId].ts b/web/src/pages/api/public/comments/[commentId].ts
index 1ebc372ff7..a6a81f3d42 100644
--- a/web/src/pages/api/public/comments/[commentId].ts
+++ b/web/src/pages/api/public/comments/[commentId].ts
@@ -1,7 +1,10 @@
import { prisma } from "@langfuse/shared/src/db";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
-import { LangfuseNotFoundError } from "@langfuse/shared";
+import {
+ LangfuseNotFoundError,
+ type COMMENT_DATA_FIELDS,
+} from "@langfuse/shared";
import {
GetCommentV1Query,
GetCommentV1Response,
@@ -28,7 +31,13 @@ export default withMiddlewares({
);
}
- return comment;
+ // cast dataField to expected enum type, Prisma just returns string | null
+ return {
+ ...comment,
+ dataField: comment.dataField as
+ | (typeof COMMENT_DATA_FIELDS)[number]
+ | null,
+ };
},
}),
});
diff --git a/web/src/pages/api/public/comments/index.ts b/web/src/pages/api/public/comments/index.ts
index 50f0028d55..473e20aad1 100644
--- a/web/src/pages/api/public/comments/index.ts
+++ b/web/src/pages/api/public/comments/index.ts
@@ -9,7 +9,10 @@ import {
import { prisma } from "@langfuse/shared/src/db";
import { v4 } from "uuid";
import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";
-import { LangfuseNotFoundError } from "@langfuse/shared";
+import {
+ LangfuseNotFoundError,
+ type COMMENT_DATA_FIELDS,
+} from "@langfuse/shared";
import { auditLog } from "@/src/features/audit-logs/auditLog";
export default withMiddlewares({
@@ -20,7 +23,10 @@ export default withMiddlewares({
fn: async ({ body, auth }) => {
const result = await validateCommentReferenceObject({
ctx: { prisma, auth },
- input: body,
+ input: {
+ ...body,
+ projectId: auth.scope.projectId,
+ },
});
if (result.errorMessage) {
@@ -36,6 +42,10 @@ export default withMiddlewares({
authorUserId: body.authorUserId,
id: v4(),
projectId: auth.scope.projectId,
+ dataField: body.dataField ?? null,
+ path: body.path ?? [],
+ rangeStart: body.rangeStart ?? [],
+ rangeEnd: body.rangeEnd ?? [],
},
});
@@ -80,7 +90,13 @@ export default withMiddlewares({
});
return {
- data: comments,
+ data: comments.map((comment) => ({
+ ...comment,
+ // cast dataField to expected enum type, Prisma just returns string | null
+ dataField: comment.dataField as
+ | (typeof COMMENT_DATA_FIELDS)[number]
+ | null,
+ })),
meta: {
page: query.page,
limit: query.limit,
diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.ts
index aca3c44440..79fbb6d73b 100644
--- a/web/src/server/api/routers/comments.ts
+++ b/web/src/server/api/routers/comments.ts
@@ -94,6 +94,10 @@ export const commentsRouter = createTRPCRouter({
objectId: input.objectId,
objectType: input.objectType,
authorUserId: ctx.session.user.id,
+ dataField: input.dataField ?? null,
+ path: input.path ?? [],
+ rangeStart: input.rangeStart ?? [],
+ rangeEnd: input.rangeEnd ?? [],
},
});
@@ -201,9 +205,14 @@ export const commentsRouter = createTRPCRouter({
id: string;
content: string;
createdAt: Date;
+ updatedAt: Date;
authorUserId: string | null;
authorUserImage: string | null;
authorUserName: string | null;
+ dataField: string | null;
+ path: string[];
+ rangeStart: number[];
+ rangeEnd: number[];
}>
>(
Prisma.sql`
@@ -211,6 +220,11 @@ export const commentsRouter = createTRPCRouter({
c.id,
c.content,
c.created_at AS "createdAt",
+ c.updated_at AS "updatedAt",
+ c.data_field AS "dataField",
+ c.path,
+ c.range_start AS "rangeStart",
+ c.range_end AS "rangeEnd",
u.id AS "authorUserId",
u.image AS "authorUserImage",
u.name AS "authorUserName"
@@ -398,9 +412,14 @@ export const commentsRouter = createTRPCRouter({
objectId: string;
content: string;
createdAt: Date;
+ updatedAt: Date;
authorUserId: string | null;
authorUserImage: string | null;
authorUserName: string | null;
+ dataField: string | null;
+ path: string[];
+ rangeStart: number[];
+ rangeEnd: number[];
}>
>(
Prisma.sql`
@@ -409,6 +428,11 @@ export const commentsRouter = createTRPCRouter({
c.object_id AS "objectId",
c.content,
c.created_at AS "createdAt",
+ c.updated_at AS "updatedAt",
+ c.data_field AS "dataField",
+ c.path,
+ c.range_start AS "rangeStart",
+ c.range_end AS "rangeEnd",
u.id AS "authorUserId",
u.image AS "authorUserImage",
u.name AS "authorUserName"