🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(comments): refresh conversations and stabilize overlay state (#17744)
Nikita Kabardin5f4c6494a8cb
diff --git a/web/src/__tests__/server/unit/comment-reference-validation.servertest.ts b/web/src/__tests__/server/unit/comment-reference-validation.servertest.tsnew file mode 100644index 0000000000..7ef8f827ec--- /dev/null+++ b/web/src/__tests__/server/unit/comment-reference-validation.servertest.ts@@ -0,0 +1,114 @@+import { LangfuseNotFoundError } from "@langfuse/shared";+import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";++const mocks = vi.hoisted(() => ({+ getObservationById: vi.fn(),+ getObservationByIdFromEventsTable: vi.fn(),+}));++vi.mock("@langfuse/shared/src/server", () => ({+ getObservationById: mocks.getObservationById,+ getObservationByIdFromEventsTable: mocks.getObservationByIdFromEventsTable,+}));++const input = {+ projectId: "comment-project",+ objectId: "root-observation",+ objectType: "OBSERVATION" as const,+ content: "Review this observation",+ objectStartTime: new Date("2026-09-18T10:00:00.000Z"),+};+const v4Context = { session: { user: { v4BetaEnabled: true } } };++describe("comment reference validation", () => {+ beforeEach(() => {+ mocks.getObservationById.mockReset();+ mocks.getObservationByIdFromEventsTable.mockReset();+ mocks.getObservationById.mockRejectedValue(+ new LangfuseNotFoundError("Observation not found"),+ );+ });++ it.each(["root-observation", "t-mirrored-trace"])(+ "accepts the v4 observation %s without a legacy observation row",+ async (objectId) => {+ mocks.getObservationByIdFromEventsTable.mockResolvedValue({+ id: objectId,+ });++ await expect(+ validateCommentReferenceObject({+ ctx: v4Context,+ input: { ...input, objectId },+ }),+ ).resolves.toEqual({});++ expect(+ mocks.getObservationByIdFromEventsTable,+ ).toHaveBeenCalledExactlyOnceWith({+ id: objectId,+ projectId: input.projectId,+ startTime: input.objectStartTime,+ });+ expect(mocks.getObservationById).not.toHaveBeenCalled();+ },+ );++ it.each([+ {+ name: "legacy session",+ ctx: { session: { user: { v4BetaEnabled: false } } },+ },+ {+ name: "public API context",+ ctx: { auth: { scope: { projectId: input.projectId } } },+ },+ ])("retains the routing wrapper for $name", async ({ ctx }) => {+ mocks.getObservationById.mockResolvedValue({ id: input.objectId });++ await expect(+ validateCommentReferenceObject({ ctx, input }),+ ).resolves.toEqual({});++ expect(mocks.getObservationById).toHaveBeenCalledExactlyOnceWith({+ id: input.objectId,+ projectId: input.projectId,+ startTime: input.objectStartTime,+ });+ expect(mocks.getObservationByIdFromEventsTable).not.toHaveBeenCalled();+ });++ it("retries a stale start-time hint on the same v4 read path", async () => {+ mocks.getObservationByIdFromEventsTable+ .mockRejectedValueOnce(new LangfuseNotFoundError("Observation not found"))+ .mockResolvedValueOnce({ id: input.objectId });++ await expect(+ validateCommentReferenceObject({ ctx: v4Context, input }),+ ).resolves.toEqual({});++ expect(mocks.getObservationByIdFromEventsTable.mock.calls).toEqual([+ [+ {+ id: input.objectId,+ projectId: input.projectId,+ startTime: input.objectStartTime,+ },+ ],+ [{ id: input.objectId, projectId: input.projectId }],+ ]);+ expect(mocks.getObservationById).not.toHaveBeenCalled();+ });++ it("propagates a v4 lookup failure without retrying or changing read paths", async () => {+ const error = new Error("Lookup timed out");+ mocks.getObservationByIdFromEventsTable.mockRejectedValue(error);++ await expect(+ validateCommentReferenceObject({ ctx: v4Context, input }),+ ).rejects.toBe(error);++ expect(mocks.getObservationByIdFromEventsTable).toHaveBeenCalledTimes(1);+ expect(mocks.getObservationById).not.toHaveBeenCalled();+ });+});diff --git a/web/src/components/ui/drawer.clienttest.tsx b/web/src/components/ui/drawer.clienttest.tsxindex 21aaeb5828..c60ab8dc0a 100644--- a/web/src/components/ui/drawer.clienttest.tsx+++ b/web/src/components/ui/drawer.clienttest.tsx@@ -1,4 +1,11 @@-import { fireEvent, render, screen } from "@testing-library/react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+} from "@testing-library/react";+import { vi } from "vitest";import {Drawer,DrawerContent,@@ -8,6 +15,20 @@ import {import { LayerProvider } from "@/src/context/LayerContext/LayerContext";describe("Drawer", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(async () => {+ try {+ cleanup();+ // Radix restores focus in a timer after the drawer unmounts.+ await act(() => vi.runOnlyPendingTimersAsync());+ } finally {+ vi.useRealTimers();+ }+ });+it("sizes compact bottom drawers to their content instead of a third of the viewport", () => {render(<Drawer open forceDirection="bottom" shouldScaleBackground={false}>diff --git a/web/src/features/annotation-queues/components/shared/CommentsSection.tsx b/web/src/features/annotation-queues/components/shared/CommentsSection.tsxindex 279a71c8b1..4533f7cdd1 100644--- a/web/src/features/annotation-queues/components/shared/CommentsSection.tsx+++ b/web/src/features/annotation-queues/components/shared/CommentsSection.tsx@@ -19,7 +19,6 @@ export const CommentsSection: React.FC<CommentsSectionProps> = ({projectId={projectId}objectId={objectId}objectType={objectType}- className="border-transparent p-2"cardViewonDraftChange={onDraftChange}/>diff --git a/web/src/features/comments/CommentDrawerController.clienttest.tsx b/web/src/features/comments/CommentDrawerController.clienttest.tsxnew file mode 100644index 0000000000..4febe2ed80--- /dev/null+++ b/web/src/features/comments/CommentDrawerController.clienttest.tsx@@ -0,0 +1,247 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { vi } from "vitest";++import { LayerProvider } from "@/src/context/LayerContext/LayerContext";+import {+ CommentDrawerController,+ type CommentDrawerControllerProps,+ getCommentDrawerInitialStateFromUrl,+} from "@/src/features/comments/CommentDrawerController";++const { fetchComments, invalidateComments, router } = vi.hoisted(() => ({+ fetchComments: vi.fn(),+ invalidateComments: vi.fn(),+ router: {+ isReady: true,+ pathname: "/project/[projectId]/traces/[traceId]",+ query: {} as Record<string, string>,+ replace: vi.fn(),+ },+}));++vi.mock("next/router", () => ({ useRouter: () => router }));+vi.mock("@/src/features/rbac", () => ({ useHasProjectAccess: () => true }));+vi.mock("@/src/utils/api", () => ({+ api: {+ useUtils: () => ({+ comments: {+ getByObjectId: { fetch: fetchComments, invalidate: invalidateComments },+ getCountByObjectId: { invalidate: vi.fn() },+ getCountByObjectType: { invalidate: vi.fn() },+ getTraceCommentCountsBySessionId: { invalidate: vi.fn() },+ },+ }),+ },+}));+vi.mock("@/src/features/comments/CommentList", () => ({+ CommentList: () => <p>Existing discussion</p>,+}));+vi.mock("@/src/features/comments/components/CommentComposer", () => ({+ CommentComposer: ({+ onCommentCreated,+ }: {+ onCommentCreated: () => Promise<void>;+ }) => (+ <button+ onClick={async () => {+ fetchComments.mockResolvedValue([{ id: "posted-comment" }]);+ await onCommentCreated();+ }}+ >+ Post comment+ </button>+ ),+}));++const target = {+ type: "comments" as const,+ objectId: "trace-id",+ objectType: "TRACE" as const,+};++describe("CommentDrawerController", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ router.query = {};+ router.isReady = true;+ fetchComments.mockResolvedValue([]);+ invalidateComments.mockResolvedValue(undefined);+ });++ it("uses the fetched thread when counts are missing or stale, then opens the discussion after posting", async () => {+ const onCommentChange = vi.fn();+ const controller = (count?: number) => (+ <CommentDrawerController+ projectId="project-id"+ count={count}+ onCommentChange={onCommentChange}+ >+ {({ disabled, openDrawer }) => (+ <button disabled={disabled} onClick={() => openDrawer(target)}>+ Open comments+ </button>+ )}+ </CommentDrawerController>+ );+ const { rerender } = render(controller(), { wrapper: LayerProvider });++ fireEvent.click(screen.getByRole("button", { name: "Open comments" }));+ expect(+ await screen.findByRole("dialog", { name: "Add a comment" }),+ ).toBeVisible();+ expect(screen.queryByText("Existing discussion")).not.toBeInTheDocument();+ fireEvent.keyDown(document, { key: "Escape" });+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );++ rerender(controller(12));+ fireEvent.click(screen.getByRole("button", { name: "Open comments" }));+ expect(+ await screen.findByRole("dialog", { name: "Add a comment" }),+ ).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Post comment" }));+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );+ expect(onCommentChange).toHaveBeenCalledOnce();+ expect(invalidateComments).toHaveBeenCalledWith({+ projectId: "project-id",+ objectId: target.objectId,+ objectType: target.objectType,+ });++ rerender(controller(0));+ fireEvent.click(screen.getByRole("button", { name: "Open comments" }));+ expect(+ await screen.findByRole("dialog", { name: "Comments" }),+ ).toBeVisible();+ expect(screen.getByText("Existing discussion")).toBeVisible();+ expect(+ screen.queryByRole("button", { name: "Post comment" }),+ ).not.toBeInTheDocument();+ });++ it("keeps the owning view stable while resolving, opening, and closing comments", async () => {+ let resolveComments!: (comments: { id: string }[]) => void;+ fetchComments.mockReturnValue(+ new Promise((resolve) => {+ resolveComments = resolve;+ }),+ );+ const renderView = vi.fn(+ ({+ openDrawer,+ }: Parameters<CommentDrawerControllerProps["children"]>[0]) => (+ <button onClick={() => openDrawer(target)}>Open comments</button>+ ),+ );+ render(+ <CommentDrawerController projectId="project-id">+ {renderView}+ </CommentDrawerController>,+ { wrapper: LayerProvider },+ );+ const initialRenders = renderView.mock.calls.length;+ fireEvent.click(screen.getByRole("button", { name: "Open comments" }));+ expect(renderView).toHaveBeenCalledTimes(initialRenders);+ await act(async () => resolveComments([{ id: "existing" }]));+ expect(+ await screen.findByRole("dialog", { name: "Comments" }),+ ).toBeVisible();+ expect(renderView).toHaveBeenCalledTimes(initialRenders);+ fireEvent.click(screen.getByRole("button", { name: "Close comments" }));+ expect(screen.getByRole("dialog", { name: "Comments" })).toHaveAttribute(+ "data-state",+ "closed",+ );+ expect(renderView).toHaveBeenCalledTimes(initialRenders);+ });++ it("ignores an obsolete lookup instead of opening a second overlay", async () => {+ let resolveFirst!: (comments: { id: string }[]) => void;+ fetchComments.mockImplementation(({ objectId }) =>+ objectId === "first"+ ? new Promise((resolve) => {+ resolveFirst = resolve;+ })+ : Promise.resolve([{ id: "existing" }]),+ );+ render(+ <CommentDrawerController projectId="project-id">+ {({ openDrawer }) => (+ <>+ <button+ onClick={() => openDrawer({ ...target, objectId: "first" })}+ >+ First+ </button>+ <button+ onClick={() => openDrawer({ ...target, objectId: "second" })}+ >+ Second+ </button>+ </>+ )}+ </CommentDrawerController>,+ { wrapper: LayerProvider },+ );+ fireEvent.click(screen.getByRole("button", { name: "First" }));+ fireEvent.click(screen.getByRole("button", { name: "Second" }));+ expect(+ await screen.findByRole("dialog", { name: "Comments" }),+ ).toBeVisible();+ await act(async () => resolveFirst([]));+ expect(screen.getAllByRole("dialog")).toHaveLength(1);+ expect(screen.getByRole("dialog", { name: "Comments" })).toHaveAttribute(+ "data-state",+ "open",+ );+ expect(+ screen.queryByRole("dialog", { name: "Add a comment" }),+ ).not.toBeInTheDocument();+ });++ it("opens a deep-linked discussion without a cached count", async () => {+ router.query = {+ comments: "open",+ commentObjectId: target.objectId,+ commentObjectType: target.objectType,+ };+ const view = () => (+ <CommentDrawerController+ projectId="project-id"+ initialState={() => getCommentDrawerInitialStateFromUrl(router.query)}+ >+ {() => <span>Trace</span>}+ </CommentDrawerController>+ );+ const { rerender } = render(view(), { wrapper: LayerProvider });++ expect(+ await screen.findByRole("dialog", { name: "Comments" }),+ ).toBeVisible();+ expect(screen.getByText("Existing discussion")).toBeVisible();+ expect(+ screen.queryByRole("button", { name: "Post comment" }),+ ).not.toBeInTheDocument();+ const openDialog = screen.getByRole("dialog", { name: "Comments" });+ rerender(view());+ expect(screen.getByRole("dialog", { name: "Comments" })).toBe(openDialog);+ fireEvent.click(screen.getByRole("button", { name: "Close comments" }));+ expect(openDialog).toHaveAttribute("data-state", "closed");+ router.isReady = false;+ rerender(view());+ router.isReady = true;+ rerender(view());+ expect(+ screen.queryByRole("dialog", { name: "Comments" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/web/src/features/comments/CommentDrawerController.tsx b/web/src/features/comments/CommentDrawerController.tsxindex 2baa033ddf..4108a733f1 100644--- a/web/src/features/comments/CommentDrawerController.tsx+++ b/web/src/features/comments/CommentDrawerController.tsx@@ -1,103 +1,30 @@-import Header from "@/src/components/layouts/header";-import {- DrawerContent,- DrawerController,- DrawerHeader,- DrawerTitle,-} from "@/src/components/ui/drawer";-import { CommentList } from "@/src/features/comments/CommentList";-import { useHasProjectAccess } from "@/src/features/rbac";-import { type CommentObjectType } from "@langfuse/shared";import { useRouter } from "next/router";-import { type ReactNode, useRef, useState } from "react";-import { type SelectionData } from "./contexts/InlineCommentSelectionContext";--type CommentDrawerContentProps = {- projectId: string;- objectId: string;- objectType: CommentObjectType;- objectStartTime?: Date | null;- pendingSelection: SelectionData | null;- onSelectionUsed: () => void;- onCommentChange?: () => void | Promise<void>;- onMentionDropdownChange: (isOpen: boolean) => void;-};--function CommentDrawerContent({- projectId,- objectId,- objectType,- objectStartTime,- pendingSelection,- onSelectionUsed,- onCommentChange,- onMentionDropdownChange,-}: CommentDrawerContentProps) {- const hasFocusedRef = useRef(false);-- return (- <DrawerContent- overlayClassName="bg-primary/10"- className="h-screen-with-banner max-h-screen-with-banner overflow-hidden"- >- <div- className="mx-auto flex h-full w-full flex-col overflow-hidden focus:ring-0 focus:outline-hidden focus-visible:ring-0 focus-visible:outline-hidden md:max-h-full"- tabIndex={-1}- ref={(element) => {- if (element && !hasFocusedRef.current) {- hasFocusedRef.current = true;- setTimeout(() => element.focus({ preventScroll: true }), 100);- }- }}- >- <DrawerHeader className="bg-background sr-only shrink-0 rounded-sm">- <DrawerTitle>- <Header title="Comments" />- </DrawerTitle>- </DrawerHeader>- <div- data-vaul-no-drag- className="min-h-0 flex-1 overflow-hidden px-2 py-2"- >- <CommentList- projectId={projectId}- objectId={objectId}- objectType={objectType}- objectStartTime={objectStartTime}- onMentionDropdownChange={onMentionDropdownChange}- isDrawerOpen- pendingSelection={pendingSelection}- onSelectionUsed={onSelectionUsed}- onCommentChange={onCommentChange}- />- </div>- </div>- </DrawerContent>- );-}+import { useState, type ReactNode } from "react";+import { type CommentObjectType } from "@langfuse/shared";+import { useHasProjectAccess } from "@/src/features/rbac";+import { api } from "@/src/utils/api";+import {+ createCommentOverlayStore,+ type CommentTarget,+} from "./state/commentOverlayStore";+import {+ CommentOverlayHost,+ CommentOverlayState,+} from "./components/CommentOverlayHost";export type CommentDrawerControllerProps = {projectId: string;// Evaluated only on mount; use for deep-linked comments, not reactive drawer state.- initialState?: () => CommentDrawerState | undefined;+ initialState?: () => CommentTarget | undefined;mode?: "read-write" | "read-only";count?: number;onCommentChange?: () => void | Promise<void>;children: (control: {disabled: boolean;- openDrawer: (state: CommentDrawerState) => void;+ openDrawer: (state: CommentTarget) => void;}) => ReactNode;};-type CommentDrawerTarget = {- objectId: string;- objectType: CommentObjectType;- objectStartTime?: Date | null;-};--type CommentDrawerState = CommentDrawerTarget &- ({ type: "comments" } | { type: "inline-comment"; selection: SelectionData });-export function getCommentDrawerInitialStateFromUrl(query: Record<string, string | string[] | undefined>,) {@@ -118,23 +45,6 @@ export function getCommentDrawerInitialStateFromUrl(};}-function CommentDrawerTriggers({- children,- disabled,- openDrawer,-}: {- children: CommentDrawerControllerProps["children"];- disabled: boolean;- openDrawer: (state: CommentDrawerState) => void;-}) {- return children({- disabled,- openDrawer: (state) => {- if (!disabled) openDrawer(state);- },- });-}-export function CommentDrawerController({children,projectId,@@ -144,8 +54,8 @@ export function CommentDrawerController({onCommentChange,}: CommentDrawerControllerProps) {const router = useRouter();- const [isMentionDropdownOpen, setIsMentionDropdownOpen] = useState(false);-+ const [store] = useState(createCommentOverlayStore);+ const utils = api.useUtils();const hasReadAccess = useHasProjectAccess({projectId,scope: "comments:read",@@ -157,43 +67,38 @@ export function CommentDrawerController({const disabled =!hasReadAccess || (mode === "read-write" && !hasWriteAccess && !count);- const handleOpenChange = (open: boolean) => {- if (!open && isMentionDropdownOpen) return false;- if (!open && router.query.comments === "open") {- const { comments, commentObjectType, commentObjectId, ...rest } =- router.query;- router.replace({ pathname: router.pathname, query: rest }, undefined, {- shallow: true,- });- }- };-return (- <DrawerController<CommentDrawerState>- initialState={disabled ? undefined : initialState}- key={`${disabled ? "disabled" : "enabled"}-${router.isReady ? "ready" : "pending"}`}- blockTextSelection={false}- onOpenChange={handleOpenChange}- renderContent={({ state, replaceState }) => (- <CommentDrawerContent- projectId={projectId}- objectId={state.objectId}- objectType={state.objectType}- objectStartTime={state.objectStartTime}- pendingSelection={- state.type === "inline-comment" ? state.selection : null- }- onSelectionUsed={() => replaceState({ ...state, type: "comments" })}- onCommentChange={onCommentChange}- onMentionDropdownChange={setIsMentionDropdownOpen}- />- )}- >- {({ openDrawer }) => (- <CommentDrawerTriggers disabled={disabled} openDrawer={openDrawer}>- {children}- </CommentDrawerTriggers>- )}- </DrawerController>+ <>+ {children({+ disabled,+ openDrawer: (target) => {+ if (disabled) return;+ store.getState().actions.open({+ target,+ canWrite: hasWriteAccess,+ confirmDiscard: () =>+ window.confirm("Discard your unsent comment?"),+ loadComments: () =>+ utils.comments.getByObjectId.fetch({+ projectId,+ objectId: target.objectId,+ objectType: target.objectType,+ }),+ });+ },+ })}+ {router.isReady && hasReadAccess ? (+ <CommentOverlayState store={store} initialState={initialState}>+ {(overlay) => (+ <CommentOverlayHost+ store={store}+ overlay={overlay}+ projectId={projectId}+ onCommentChange={onCommentChange}+ />+ )}+ </CommentOverlayState>+ ) : null}+ </>);}diff --git a/web/src/features/comments/CommentList.clienttest.tsx b/web/src/features/comments/CommentList.clienttest.tsxnew file mode 100644index 0000000000..36ef56ef52--- /dev/null+++ b/web/src/features/comments/CommentList.clienttest.tsx@@ -0,0 +1,137 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { type RouterOutputs } from "@/src/utils/api";+import { CommentList } from "./CommentList";++const { useCommentsQuery, composerRenders } = vi.hoisted(() => ({+ useCommentsQuery: vi.fn(),+ composerRenders: vi.fn(),+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ comments: {+ getByObjectId: { useQuery: useCommentsQuery },+ delete: { useMutation: () => ({ mutate: vi.fn(), isPending: false }) },+ },+ commentReactions: {+ add: { useMutation: () => ({ mutate: vi.fn() }) },+ remove: { useMutation: () => ({ mutate: vi.fn() }) },+ },+ useUtils: () => ({+ comments: {+ getByObjectId: { invalidate: vi.fn() },+ getCountByObjectId: { invalidate: vi.fn() },+ getCountByObjectType: { invalidate: vi.fn() },+ getTraceCommentCountsBySessionId: { invalidate: vi.fn() },+ },+ commentReactions: { invalidate: vi.fn() },+ }),+ },+}));++vi.mock("@/src/features/rbac", () => ({+ useHasProjectAccess: () => true,+}));++vi.mock("next-auth/react", () => ({+ useSession: () => ({+ status: "authenticated",+ data: { user: { id: "reviewer" } },+ }),+}));++vi.mock("next/router", () => ({+ useRouter: () => ({ asPath: "/project/project-1/traces/trace-1" }),+}));++vi.mock("./components/CommentCard", () => ({+ CommentCard: ({ content }: { content: string }) => (+ <article>{content}</article>+ ),+}));++vi.mock("./components/CommentComposer", async () => {+ const { useState } = await import("react");+ return {+ CommentComposer: function MockCommentComposer() {+ composerRenders();+ const [draft, setDraft] = useState("");+ return (+ <input+ aria-label="New comment"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ );+ },+ };+});++describe("CommentList draft lifecycle", () => {+ it("retains a draft after a background query error and resets it for a different object", () => {+ const comments: RouterOutputs["comments"]["getByObjectId"] = [+ {+ id: "comment-1",+ content: "Existing discussion",+ createdAt: new Date("2026-09-01T12:00:00Z"),+ updatedAt: new Date("2026-09-01T12:00:00Z"),+ authorUserId: "reviewer",+ authorUserName: "Reviewer",+ authorUserImage: null,+ dataField: null,+ path: [],+ rangeStart: [],+ rangeEnd: [],+ },+ ];+ const queryResult = {+ data: comments,+ isPending: false,+ isError: false,+ refetch: vi.fn(),+ };+ useCommentsQuery.mockReturnValue(queryResult);++ const { rerender } = render(+ <CommentList+ projectId="project-1"+ objectId="trace-1"+ objectType="TRACE"+ />,+ );+ expect(screen.getByText("Existing discussion")).toBeInTheDocument();+ const composer = screen.getByRole("textbox", { name: "New comment" });+ fireEvent.change(composer, { target: { value: "Unsent review" } });++ const renderCount = composerRenders.mock.calls.length;+ fireEvent.change(screen.getByRole("textbox", { name: "Search comments" }), {+ target: { value: "discussion" },+ });+ expect(composerRenders).toHaveBeenCalledTimes(renderCount);++ useCommentsQuery.mockReturnValue({ ...queryResult, isError: true });+ rerender(+ <CommentList+ projectId="project-1"+ objectId="trace-1"+ objectType="TRACE"+ />,+ );+ expect(screen.getByText("Existing discussion")).toBeInTheDocument();+ expect(screen.getByRole("textbox", { name: "New comment" })).toBe(composer);+ expect(composer).toHaveValue("Unsent review");++ useCommentsQuery.mockReturnValue({ ...queryResult, data: [] });+ rerender(+ <CommentList+ projectId="project-1"+ objectId="trace-2"+ objectType="TRACE"+ />,+ );+ expect(screen.getByRole("textbox", { name: "New comment" })).toHaveValue(+ "",+ );+ expect(composer).not.toBeInTheDocument();+ });+});diff --git a/web/src/features/comments/CommentList.tsx b/web/src/features/comments/CommentList.tsxindex 4e93136f54..a8282df996 100644--- a/web/src/features/comments/CommentList.tsx+++ b/web/src/features/comments/CommentList.tsx@@ -1,811 +1,137 @@-/* eslint-disable no-nested-ternary */-/* eslint-disable @repo/no-style-props, @repo/no-null-render */-import { Avatar } from "@/src/components/design-system/Avatar/Avatar";+/* eslint-disable @repo/no-null-render */+import { useRef } from "react";+import { Spinner } from "@/src/components/design-system/Spinner/Spinner";import { Button } from "@/src/components/ui/button";-import { KeyboardShortcut } from "@/src/components/design-system/KeyboardShortcut/KeyboardShortcut";-import {- Form,- FormControl,- FormField,- FormItem,- FormMessage,-} from "@/src/components/ui/form";-import {- HoverCard,- 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";import { useHasProjectAccess } from "@/src/features/rbac";import { api } from "@/src/utils/api";-import { getRelativeTimestampFromNow } from "@/src/utils/dates";import { cn } from "@/src/utils/tailwind";-import { zodResolver } from "@hookform/resolvers/zod";-import { type CommentObjectType, CreateCommentData } from "@langfuse/shared";-import { Spinner } from "@/src/components/design-system/Spinner/Spinner";-import { ArrowUpToLine, Search, Trash, X } from "lucide-react";+import { type CommentObjectType } from "@langfuse/shared";import { useSession } from "next-auth/react";-import React, {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";-import { useForm } from "react-hook-form";-import { type z } from "zod";-import { useMentionAutocomplete } from "@/src/features/comments/hooks/useMentionAutocomplete";-import { MentionAutocomplete } from "@/src/features/comments/components/MentionAutocomplete";-import { useRouter } from "next/router";-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 { CommentComposer } from "./components/CommentComposer";+import { CommentConversation } from "./components/CommentConversation";+import { refreshCommentQueries } from "./actions/refreshCommentQueries";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;+type CommentListProps = {+ projectId: string;+ objectId: string;+ objectType: CommentObjectType;+ objectStartTime?: Date | null;+ cardView?: boolean;+ onDraftChange?: (hasDraft: boolean) => void;+ onMentionDropdownChange?: (isOpen: boolean) => void;+ isDrawerOpen?: boolean;+ pendingSelection?: SelectionData | null;+ onSelectionUsed?: () => void;+ onCommentChange?: () => void | Promise<void>;+};-/**- * 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(" › ");+export function CommentList(props: CommentListProps) {+ return (+ <CommentThread+ key={`${props.projectId}-${props.objectType}-${props.objectId}`}+ {...props}+ />+ );}-const useIsomorphicLayoutEffect =- typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;--export function CommentList({+function CommentThread({projectId,objectId,objectType,objectStartTime,cardView = false,- className,onDraftChange,onMentionDropdownChange,isDrawerOpen = false,pendingSelection,onSelectionUsed,onCommentChange,-}: {- projectId: string;- objectId: string;- objectType: CommentObjectType;- objectStartTime?: Date | null;- cardView?: boolean;- className?: string;- onDraftChange?: (hasDraft: boolean) => void;- onMentionDropdownChange?: (isOpen: boolean) => void;- isDrawerOpen?: boolean;- pendingSelection?: SelectionData | null;- onSelectionUsed?: () => void;- onCommentChange?: () => void | Promise<void>;-}) {+}: CommentListProps) {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);- const textareaRef = useRef<HTMLTextAreaElement | null>(null);- const searchInputRef = useRef<HTMLInputElement | null>(null);- const didInitialAutoscrollRef = useRef(false);-- // Extract comment ID from hash for highlighting- const highlightedCommentId = useMemo(() => {- if (typeof window === "undefined") return null;- const hash = window.location.hash;- if (hash.startsWith("#comment-")) {- return hash.replace("#comment-", "");- }- return null;- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [router.asPath]);const hasReadAccess = useHasProjectAccess({projectId,scope: "comments:read",});-const hasWriteAccess = useHasProjectAccess({projectId,scope: "comments:CUD",});-- const hasMembersReadAccess = useHasProjectAccess({- projectId,- scope: "projectMembers:read",- });-- const canTagUsers = hasWriteAccess && hasMembersReadAccess;-const comments = api.comments.getByObjectId.useQuery(- {- projectId,- objectId,- objectType,- },+ { projectId, objectId, objectType },{ enabled: hasReadAccess && session.status === "authenticated" },);-- const form = useForm({- resolver: zodResolver(CreateCommentData),- defaultValues: {- content: "",- projectId,- objectId,- objectType,- },- });-- useEffect(() => {- form.reset({ content: "", projectId, objectId, objectType });- setSearchQuery(""); // Reset search when switching objects- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [objectId, objectType]);-- // Mention autocomplete - useCallback to ensure stable reference- const getTextareaValue = useCallback(() => {- return form.getValues("content");- }, [form]);-- const mentionAutocomplete = useMentionAutocomplete({- projectId,- getTextareaValue,- cursorPosition,- enabled: canTagUsers,- });-- // Notify parent when mention dropdown state changes- useEffect(() => {- onMentionDropdownChange?.(mentionAutocomplete.showDropdown);- }, [mentionAutocomplete.showDropdown, onMentionDropdownChange]);-- const handleTextareaResize = useCallback((target: HTMLTextAreaElement) => {- // Use requestAnimationFrame for optimal performance- requestAnimationFrame(() => {- if (target) {- target.style.height = "auto";- const newHeight = Math.min(target.scrollHeight, 100);- target.style.height = `${newHeight}px`;- }- });- }, []);-- const debouncedResize = useCallback(() => {- let timeoutId: NodeJS.Timeout;-- const debounced = (target: HTMLTextAreaElement) => {- clearTimeout(timeoutId);- timeoutId = setTimeout(() => handleTextareaResize(target), 16); // ~60fps- };-- return {- resize: debounced,- cleanup: () => clearTimeout(timeoutId),- };- }, [handleTextareaResize]);-- const resizeHandler = useMemo(() => debouncedResize(), [debouncedResize]);-- useEffect(() => {- return () => {- resizeHandler.cleanup();- };- }, [resizeHandler]);-- // Notify parent when a draft comment exists in the textarea- const watchedContent = form.watch("content");- useEffect(() => {- if (!onDraftChange) return;- onDraftChange(Boolean(watchedContent && watchedContent.trim().length > 0));- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [watchedContent]);-- // Scroll to bottom on initial load to show latest comments + input.- // Skip auto-scroll if there's a highlighted comment (deeplink takes precedence).- useIsomorphicLayoutEffect(() => {- if (- didInitialAutoscrollRef.current ||- !comments.data ||- !commentsContainerRef.current ||- highlightedCommentId- ) {- return;- }-- const el = commentsContainerRef.current;- // Do it synchronously post-DOM mutation to avoid flicker- el.scrollTop = el.scrollHeight;- // Fallback after paint in case content height changes (markdown, fonts, images)- requestAnimationFrame(() => {- el.scrollTop = el.scrollHeight;- });-- didInitialAutoscrollRef.current = true;- }, [comments.data, highlightedCommentId]);-- // If a highlighted comment is specified (via hash), scroll it into view within the container- useIsomorphicLayoutEffect(() => {- if (!highlightedCommentId || !comments.data) return;- const node = document.getElementById(`comment-${highlightedCommentId}`);- if (node) {- node.scrollIntoView({ block: "center", behavior: "smooth" });- }- }, [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-- const handleKeyDown = (event: KeyboardEvent) => {- // Don't trigger if user is typing in input/textarea- if (- event.target instanceof HTMLInputElement ||- event.target instanceof HTMLTextAreaElement ||- (event.target instanceof HTMLElement &&- event.target.getAttribute("role") === "textbox")- ) {- return;- }-- // Capture CMD+F or Ctrl+F- if ((event.metaKey || event.ctrlKey) && event.key === "f") {- event.preventDefault();- event.stopPropagation();- searchInputRef.current?.focus();- }- };-- // Use capture phase to intercept before browser default handler- window.addEventListener("keydown", handleKeyDown, { capture: true });- return () =>- window.removeEventListener("keydown", handleKeyDown, { capture: true });- }, [isDrawerOpen]);-const utils = api.useUtils();- const invalidateCommentQueries = async () => {- (async () => {- await onCommentChange?.();- })().catch(() => undefined);-- await utils.comments.invalidate();- };-- const createCommentMutation = api.comments.create.useMutation({- onSuccess: async () => {- form.reset();-- // Clear pending selection after successful comment creation- onSelectionUsed?.();-- // Reset textarea height- if (textareaRef.current) {- textareaRef.current.style.height = "auto";- }-- await invalidateCommentQueries();-- // Scroll to bottom of comments list (newest comment in chronological order)- if (commentsContainerRef.current) {- commentsContainerRef.current.scrollTo({- top: commentsContainerRef.current.scrollHeight,- behavior: "smooth",- });- }- },- });-- // Insert mention at cursor position- const insertMention = useCallback(- (userId: string, displayName: string) => {- if (!textareaRef.current || mentionAutocomplete.mentionStartPos === null)- return;-- const textarea = textareaRef.current;- const currentValue = form.getValues("content");- const cursorPos = textarea.selectionStart;-- // Replace from @ to cursor with mention- const before = currentValue.substring(- 0,- mentionAutocomplete.mentionStartPos,- );- const after = currentValue.substring(cursorPos);- const mention = `@[${displayName}](${MENTION_USER_PREFIX}${userId}) `;-- const newText = before + mention + after;- const newCursorPos = mentionAutocomplete.mentionStartPos + mention.length;-- // Update form value- form.setValue("content", newText, { shouldDirty: true });-- // Update cursor position- setTimeout(() => {- textarea.setSelectionRange(newCursorPos, newCursorPos);- textarea.focus();- setCursorPosition(newCursorPos);- }, 0);-- // Close dropdown- mentionAutocomplete.closeDropdown();- },- [form, mentionAutocomplete],- );-- const deleteCommentMutation = api.comments.delete.useMutation({- onSuccess: async () => {- await invalidateCommentQueries();- },- });-- const addReactionMutation = api.commentReactions.add.useMutation({- onSuccess: async () => {- await Promise.all([utils.commentReactions.invalidate()]);- },- });-- const removeReactionMutation = api.commentReactions.remove.useMutation({- onSuccess: async () => {- await Promise.all([utils.commentReactions.invalidate()]);- },- });-- const commentsWithFormattedTimestamp = useMemo(() => {- return comments.data- ?.map((comment) => ({- ...comment,- timestamp: getRelativeTimestampFromNow(comment.createdAt),- strippedLower: stripMarkdown(comment.content).toLowerCase(),- authorLower: (- comment.authorUserName ||- comment.authorUserId ||- ""- ).toLowerCase(),- }))- .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());- }, [comments.data]);-- // stripMarkdown imported from utils-- // Client-side filtering based on search query- const filteredComments = useMemo(() => {- if (!searchQuery.trim()) {- return commentsWithFormattedTimestamp;- }-- const query = searchQuery.toLowerCase();- return commentsWithFormattedTimestamp?.filter((comment) => {- const contentMatch = comment.strippedLower.includes(query);- const authorMatch = comment.authorLower.includes(query);- return contentMatch || authorMatch;- });- }, [commentsWithFormattedTimestamp, searchQuery]);-- if (- !hasReadAccess ||- (!hasWriteAccess && comments.data?.length === 0) ||- session.status !== "authenticated"- )- return null;-- function onSubmit(values: z.infer<typeof CreateCommentData>) {- createCommentMutation.mutateAsync({- ...values,- objectStartTime: objectStartTime ?? undefined,- dataField: pendingSelection?.dataField,- path: pendingSelection?.path,- rangeStart: pendingSelection?.rangeStart,- rangeEnd: pendingSelection?.rangeEnd,- });- }-- const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {- // Submit on Cmd+Enter (handle first, before dropdown checks)- if (event.key === "Enter" && event.metaKey) {- event.preventDefault();- form.handleSubmit(onSubmit)();- return;- }-- // Handle autocomplete navigation for mentions- if (!mentionAutocomplete.showDropdown) {- return;- }- if (mentionAutocomplete.users.length === 0) {- return;- }-- if (event.key === "ArrowDown") {- event.preventDefault();- const newIndex =- (mentionAutocomplete.selectedIndex + 1) %- mentionAutocomplete.users.length;- mentionAutocomplete.setSelectedIndex(newIndex);- return;- } else if (event.key === "ArrowUp") {- event.preventDefault();- const newIndex =- mentionAutocomplete.selectedIndex === 0- ? mentionAutocomplete.users.length - 1- : mentionAutocomplete.selectedIndex - 1;- mentionAutocomplete.setSelectedIndex(newIndex);- return;- } else if (event.key === "Enter" || event.key === "Tab") {- event.preventDefault();- const user = mentionAutocomplete.users[mentionAutocomplete.selectedIndex];- if (user) {- const displayName = user.name || user.email || "User";- insertMention(user.id, displayName);- }- return;- } else if (event.key === "Escape") {- event.preventDefault();- event.stopPropagation(); // we don't want the sheet to close- event.nativeEvent.stopImmediatePropagation(); // stops other event listeners- mentionAutocomplete.closeDropdown();- return;- }- };-+ if (!hasReadAccess || session.status !== "authenticated") return <></>;if (comments.isPending)return (- <div- className={cn(- "flex min-h-20 items-center justify-center rounded border border-dashed p-1",- className,- )}- >- <span className="mr-1.5 inline-flex">- <Spinner size="sm" variant="muted" />- </span>- <span className="text-muted-foreground text-sm opacity-60">- Loading comments...- </span>+ <div className="flex justify-center p-6">+ <Spinner size="sm" />+ <span className="sr-only">Loading comments</span></div>);-+ if (comments.isError && comments.data === undefined)+ return (+ <div className="flex flex-col items-start gap-3 p-4">+ <p className="text-muted-foreground text-sm">+ Comments could not be loaded.+ </p>+ <Button variant="outline" size="sm" onClick={() => comments.refetch()}>+ Try again+ </Button>+ </div>+ );+ const refresh = () =>+ refreshCommentQueries({+ utils,+ target: { projectId, objectId, objectType },+ onCommentChange,+ });return (<divclassName={cn(- cardView && "rounded-md border","flex h-full min-h-0 flex-col overflow-hidden",- className,+ cardView && "rounded-md",)}>- {cardView && (- <div className="shrink-0 border-b px-2 py-1 text-sm font-bold">- Comments ({comments.data?.length ?? 0})+ {cardView ? (+ <h3 className="shrink-0 border-b px-4 py-3 text-sm font-bold">+ Comments+ </h3>+ ) : null}+ <CommentConversation+ projectId={projectId}+ objectId={objectId}+ objectType={objectType}+ comments={comments.data}+ currentUserId={session.data?.user?.id}+ hasWriteAccess={hasWriteAccess}+ isDrawerOpen={isDrawerOpen}+ containerRef={commentsContainerRef}+ onCommentChange={refresh}+ />+ {hasWriteAccess && (+ <div className="shrink-0 border-t p-4 pb-[max(1rem,env(safe-area-inset-bottom))]">+ <CommentComposer+ projectId={projectId}+ objectId={objectId}+ objectType={objectType}+ objectStartTime={objectStartTime}+ pendingSelection={pendingSelection}+ onSelectionUsed={onSelectionUsed}+ onDraftChange={onDraftChange}+ onMentionDropdownChange={onMentionDropdownChange}+ onCommentCreated={async () => {+ await refresh();+ commentsContainerRef.current?.scrollTo({+ top: commentsContainerRef.current.scrollHeight,+ behavior: "smooth",+ });+ }}+ /></div>)}- <div className="flex min-h-0 flex-1 flex-col overflow-hidden">- {!cardView && (- <div className="shrink-0 border-b">- <div className="flex items-center justify-between gap-2 px-2 py-1.5">- <div className="text-sm font-bold">Comments</div>- <div className="relative max-w-xs flex-1">- <Search className="text-muted-foreground absolute top-1/2 left-2 h-3.5 w-3.5 -translate-y-1/2" />- <Input- ref={searchInputRef}- type="text"- placeholder="Search comments..."- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- className="h-7 pr-7 pl-7 text-xs"- />- {searchQuery && (- <Button- type="button"- variant="ghost"- size="icon-xs"- className="absolute top-1/2 right-1 h-5 w-5 -translate-y-1/2"- onClick={() => setSearchQuery("")}- >- <X className="h-3 w-3" />- </Button>- )}- {!searchQuery && (- <span className="absolute top-1/2 right-1 hidden -translate-y-1/2 opacity-50 md:inline-flex">- <KeyboardShortcut keys={["Mod", "F"]} />- </span>- )}- </div>- </div>- <div className="text-muted-foreground px-2 pb-1 text-xs">- {searchQuery.trim()- ? filteredComments && filteredComments.length > 0- ? `Showing ${filteredComments.length} of ${comments.data?.length ?? 0} comments`- : "No comments match your search"- : `${comments.data?.length ?? 0} comments`}- </div>- </div>- )}- <div- ref={commentsContainerRef}- className="flex min-h-0 flex-1 flex-col justify-end overflow-y-auto"- >- <div className="max-h-full space-y-2 p-2">- {filteredComments?.map((comment) => (- <div- key={comment.id}- id={`comment-${comment.id}`}- className={cn(- "group relative grid grid-cols-[auto_1fr] gap-2.5 rounded-lg border p-3 transition-colors",- highlightedCommentId === comment.id- ? "border-primary-accent"- : "border-border/40 hover:bg-muted/20",- )}- >- <Avatar- size="sm"- src={comment.authorUserImage ?? undefined}- displayName={- comment.authorUserName ?? comment.authorUserId ?? "User"- }- />- <div className="min-w-0">- {/* Name + timestamp inline */}- <div className="mb-1.5 flex items-center gap-2 pt-1.5 text-xs leading-none">- <span className="text-foreground font-bold">- {comment.authorUserName ?? comment.authorUserId ?? "User"}- </span>- <span className="text-muted-foreground/50">·</span>- <span className="text-muted-foreground/70">- {comment.timestamp}- </span>- </div>-- {/* Comment content with CSS overrides for markdown */}- <MarkdownView- markdown={comment.content}- className="border-none p-0 py-1 text-xs [&_h1]:text-[0.9rem] [&_h1]:font-bold [&_h2]:text-[0.85rem] [&_h2]:font-bold [&_h3]:text-[0.8rem] [&_h3]:font-bold [&_h4]:text-xs [&_h4]:font-bold [&_h5]:text-xs [&_h5]:font-bold [&_h6]:text-xs [&_h6]:font-bold [&_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="text-foreground pointer-events-none px-1.5 py-0 text-[10px] font-bold"- 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- projectId={projectId}- commentId={comment.id}- onReactionToggle={(emoji, hasReacted) => {- if (hasReacted) {- removeReactionMutation.mutate({- projectId,- commentId: comment.id,- emoji,- });- } else {- addReactionMutation.mutate({- projectId,- commentId: comment.id,- emoji,- });- }- }}- />- {hasWriteAccess && (- <ReactionPicker- onEmojiSelect={(emoji) => {- addReactionMutation.mutate({- projectId,- commentId: comment.id,- emoji,- });- }}- />- )}- </div>- </div>-- {/* Actions - absolute positioned */}- {session.data?.user?.id === comment.authorUserId && (- <div className="absolute top-2 right-2 opacity-50 transition-opacity hover:opacity-100">- <Button- type="button"- size="icon-xs"- variant="ghost"- title="Delete comment"- loading={deleteCommentMutation.isPending}- onClick={() => {- if (- confirm(- "Are you sure you want to delete this comment?",- )- )- deleteCommentMutation.mutateAsync({- commentId: comment.id,- projectId,- objectId,- objectType,- });- }}- >- <Trash className="h-3 w-3" />- </Button>- </div>- )}- </div>- ))}- </div>- </div>-- {hasWriteAccess && (- <div className="bg-background shrink-0 px-2 pt-2 pb-[calc(0.5rem+env(safe-area-inset-bottom,0px))]">- <div className="text-muted-foreground relative flex flex-row items-center justify-between text-xs">- <span className="sr-only">New comment</span>- <span></span>- <span>Markdown and @-mentions support</span>- </div>- <div className="border-border/60 relative mt-0.5 min-h-[70px] rounded-lg border pt-1">- {/* Visually hidden header for accessibility */}-- <Form {...form}>- <form>- <FormField- control={form.control}- name="content"- render={({ field }) => (- <FormItem>- <div>- <FormControl>- <Textarea- placeholder="Add a comment..."- {...field}- ref={(el) => {- if (textareaRef.current !== el) {- textareaRef.current = el;- }- // Call the field ref if it exists (for react-hook-form)- if (typeof field.ref === "function") {- field.ref(el);- }- }}- onKeyDown={handleKeyDown}- className="max-h-[100px] min-h-9 w-full resize-none overflow-hidden border-none py-2 pr-7 text-xs leading-tight focus:ring-0 focus:outline-hidden focus-visible:ring-0 focus-visible:ring-offset-0 active:ring-0"- style={{- whiteSpace: "pre-wrap",- wordWrap: "break-word",- overflowWrap: "break-word",- height: "auto",- minHeight: "2.25rem",- }}- onInput={(e) => {- const target = e.target as HTMLTextAreaElement;- resizeHandler.resize(target);- setCursorPosition(target.selectionStart);- }}- onClick={(e) => {- const target = e.target as HTMLTextAreaElement;- setCursorPosition(target.selectionStart);- }}- onSelect={(e) => {- const target = e.target as HTMLTextAreaElement;- setCursorPosition(target.selectionStart);- }}- autoFocus- />- </FormControl>- {canTagUsers && mentionAutocomplete.showDropdown && (- <MentionAutocomplete- users={mentionAutocomplete.users}- isLoading={mentionAutocomplete.isLoading}- selectedIndex={mentionAutocomplete.selectedIndex}- onSelect={insertMention}- onClose={mentionAutocomplete.closeDropdown}- onSelectedIndexChange={- mentionAutocomplete.setSelectedIndex- }- />- )}- </div>- <FormMessage className="ml-2 text-sm" />- </FormItem>- )}- />- <div className="flex justify-end">- <HoverCard openDelay={200}>- <HoverCardTrigger asChild>- <Button- type="submit"- size="icon-xs"- variant="outline"- title="Submit comment"- loading={createCommentMutation.isPending}- onClick={() => {- form.handleSubmit(onSubmit)();- }}- className="absolute right-1 bottom-1"- >- <ArrowUpToLine className="h-3 w-3" />- </Button>- </HoverCardTrigger>- <HoverCardContent- side="top"- align="end"- className="w-auto p-2"- >- <div className="flex items-center gap-2 text-sm">- <span>Send comment</span>- <span className="hidden md:inline-flex">- <KeyboardShortcut keys={["Mod", "Enter"]} />- </span>- </div>- </HoverCardContent>- </HoverCard>- </div>- </form>- </Form>- </div>- </div>- )}- </div></div>);}diff --git a/web/src/features/comments/README.md b/web/src/features/comments/README.mdnew file mode 100644index 0000000000..4ac933fc54--- /dev/null+++ b/web/src/features/comments/README.md@@ -0,0 +1,54 @@+# Comments++## Surface and entry points++Trace/observation details, sessions, prompts and queue processors mount+`CommentDrawerController`. Dataset comparison mounts `CommentList` inline.+These exports remain usable without a feature provider.++## State ownership++- `CommentDrawerController` creates one local `commentOverlayStore` per mounted+ view. Its children receive actions and permissions; opening, resolving,+ typing and closing do not rerender the owning detail view.+- `CommentOverlayState` subscribes only to the overlay. Route readiness gates+ its initial deep-link seed. `CommentOverlayHost` renders one controlled+ composer dialog or conversation drawer; the chosen presentation stays pinned+ until another explicit open. Counts and query refreshes never select a mode.+- `commentOverlayStore` owns target intent, request identity and dismissal+ guards. Obsolete requests and post callbacks cannot reopen dismissed overlays,+ replace newer selections or discard drafts edited during a lookup. It stores+ no server comments or draft content.+- React Query owns threads, counts and reactions. `refreshCommentQueries`+ refreshes the affected thread/counts and relevant aggregate counts. Reaction+ invalidation targets one comment. Refresh failures stay with query error UI.+- `CommentList` gates its target-keyed thread on permissions and initial data;+ cached data survives background failures. `CommentConversation` owns search+ and history, so search does not wake the composer. `CommentCard` is view-only.+- `CommentComposer` owns the editable RHF draft and mention state. `CommentEditor`+ integrates CodeMirror, preserving Markdown wire text while rendering atomic+ mention chips. No query-to-draft synchronization effect exists.++## Integrations and stability++| Boundary | Retained integration | Cleanup |+| ---------------- | ------------------------------------------------------- | ----------------------------- |+| Conversation | Scroll to linked/latest comment; window search shortcut | Cancel frame; remove listener |+| Composer | Capture Escape while mention picker is open | Remove listener |+| Mention picker | Scroll selected suggestion into view | DOM-only update |+| Inline selection | Browser selection, pointer and keyboard events | Remove listeners/timers |+| Editor | CodeMirror lifecycle and extension configuration | Owned by CodeMirror wrapper |++Mention suggestions portal inside the active modal. Editors, message cards and+suggestions block customer content from session replay. Server sanitization and+`validateCommentReferenceObject` remain authoritative; target validation uses the+session's observation read path.++## Migration boundaries++Overlay state, history search, server cache and composer drafts are independent.+The trace's aggregate count/inline-highlight queries remain owned by trace views;+refreshing their data legitimately updates those consumers. The shared inline+selection context and browser selection integration remain outside overlay state.+Read the frontend-large-feature-architecture and refactor-react-effects skills+before extending these boundaries.diff --git a/web/src/features/comments/actions/refreshCommentQueries.ts b/web/src/features/comments/actions/refreshCommentQueries.tsnew file mode 100644index 0000000000..fef9f1063b--- /dev/null+++ b/web/src/features/comments/actions/refreshCommentQueries.ts@@ -0,0 +1,32 @@+import { type api } from "@/src/utils/api";+import { type CommentObjectType } from "@langfuse/shared";++export async function refreshCommentQueries({+ utils,+ target,+ onCommentChange,+}: {+ utils: Pick<ReturnType<typeof api.useUtils>, "comments">;+ target: {+ projectId: string;+ objectId: string;+ objectType: CommentObjectType;+ };+ onCommentChange?: () => void | Promise<void>;+}) {+ const { projectId, objectId, objectType } = target;+ const queryTarget = { projectId, objectId, objectType };+ await Promise.allSettled([+ utils.comments.getByObjectId.invalidate(queryTarget),+ utils.comments.getCountByObjectId.invalidate(queryTarget),+ utils.comments.getCountByObjectType.invalidate({ projectId, objectType }),+ ...(objectType === "TRACE"+ ? [+ utils.comments.getTraceCommentCountsBySessionId.invalidate({+ projectId,+ }),+ ]+ : []),+ Promise.resolve().then(() => onCommentChange?.()),+ ]);+}diff --git a/web/src/features/comments/components/CommentCard.stories.tsx b/web/src/features/comments/components/CommentCard.stories.tsxnew file mode 100644index 0000000000..4f8aa233ee--- /dev/null+++ b/web/src/features/comments/components/CommentCard.stories.tsx@@ -0,0 +1,112 @@+import { type ComponentProps } from "react";+import { Trash2 } from "lucide-react";+import { fn } from "storybook/test";++import preview from "../../../../.storybook/preview";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { Button } from "@/src/components/ui/button";+import { CommentCard } from "./CommentCard";++const meta = preview.meta({ component: CommentCard });++const comment = {+ id: "review-note",+ authorName: "Maya Chen",+ authorImage: null,+ timestamp: "5 minutes ago",+ content:+ "The answer is clear, but the second claim needs a source. I'd mark this as **partially correct** until we check it.",+ highlighted: false,+ isOwnComment: false,+ actions: (+ <IconButton+ icon={Trash2}+ label="Delete comment"+ size="sm"+ variant="ghost"+ onClick={fn()}+ />+ ),+ footer: null,+ location: null,+} satisfies ComponentProps<typeof CommentCard>;++export const Default = meta.story({ args: comment });++export const OwnMessage = meta.story({+ args: { ...comment, isOwnComment: true },+});++export const Conversation = meta.story({+ render: () => (+ <div className="flex w-full max-w-md flex-col gap-4 p-4">+ <CommentCard {...comment} actions={null} />+ <CommentCard+ {...comment}+ id="reply"+ authorName="Alex Rivera"+ timestamp="2 minutes ago"+ isOwnComment={true}+ content="Agreed. I'll check the source and update the score."+ />+ <CommentCard+ {...comment}+ id="follow-up"+ timestamp="Just now"+ content="Thanks!"+ actions={null}+ />+ </div>+ ),+});++export const Highlighted = meta.story({+ args: { ...comment, highlighted: true },+});++export const LongMarkdown = meta.story({+ args: {+ ...comment,+ authorName: "Alexandra Rivera — Evaluation and Quality Engineering",+ content: `@[Maya Chen](user:maya-chen) I reviewed the response against the reference answer. The conclusion is useful, but the supporting evidence needs another pass before we can call this complete.++### What I checked++- **Accuracy:** the first claim matches the reference.+- **Grounding:** the second claim isn't supported by the supplied context.+- **Completeness:** the answer should explain what happens when the input is empty.++The fallback should return \`null\` instead of guessing. That gives callers a clear signal that they need more context and keeps the behavior consistent across retries.++> Ask for clarification when the source doesn't contain enough information.++Please revisit the second paragraph and add a short explanation of the fallback. The rest can stay as written.`,+ },+});++export const WithLocationAndReactions = meta.story({+ args: {+ ...comment,+ content: "This sentence is the unsupported claim I mentioned above.",+ location: <span>Output · messages[1].content</span>,+ footer: (+ <>+ <Button+ variant="outline"+ size="xs"+ onClick={fn()}+ aria-label="Agree, 2 reactions"+ >+ 👍 2+ </Button>+ <Button variant="ghost" size="xs" onClick={fn()}>+ Add reaction+ </Button>+ </>+ ),+ },+});++export const ReadOnly = meta.story({+ args: { ...comment, actions: null },+});diff --git a/web/src/features/comments/components/CommentCard.tsx b/web/src/features/comments/components/CommentCard.tsxnew file mode 100644index 0000000000..38d551a04c--- /dev/null+++ b/web/src/features/comments/components/CommentCard.tsx@@ -0,0 +1,98 @@+import { type ReactNode } from "react";+import { cva } from "class-variance-authority";++import { Avatar } from "@/src/components/design-system/Avatar/Avatar";+import { MarkdownView } from "@/src/components/ui/MarkdownViewer";+import { cn } from "@/src/utils/tailwind";++const commentCardVariants = cva(+ "min-w-0 max-w-full rounded-2xl px-3 py-2.5 transition-colors",+ {+ variants: {+ highlighted: {+ true: "ring-primary-accent ring-2 ring-inset",+ false: null,+ },+ isOwnComment: {+ true: "bg-primary/10 rounded-br-sm",+ false: "bg-muted rounded-bl-sm",+ },+ },+ },+);++type CommentCardProps = {+ id: string;+ authorName: string;+ authorImage: string | null;+ timestamp: string;+ content: string;+ highlighted: boolean;+ isOwnComment: boolean;+ actions: ReactNode;+ footer: ReactNode;+ location: ReactNode;+};++export function CommentCard({+ id,+ authorName,+ authorImage,+ timestamp,+ content,+ highlighted,+ isOwnComment,+ actions,+ footer,+ location,+}: CommentCardProps) {+ return (+ <article+ id={`comment-${id}`}+ className={cn(+ "ph-no-capture flex min-w-0 items-start gap-2",+ isOwnComment && "flex-row-reverse",+ )}+ >+ <div className="shrink-0 pt-5">+ <Avatar+ size="sm"+ src={authorImage ?? undefined}+ displayName={authorName}+ aria-hidden="true"+ />+ </div>+ <div+ className={cn(+ "flex max-w-[85%] min-w-0 flex-col gap-1",+ isOwnComment ? "items-end" : "items-start",+ )}+ >+ <span+ className="text-muted-foreground max-w-full truncate px-1 text-xs"+ title={authorName}+ >+ {isOwnComment ? "You" : authorName}+ </span>+ <div className={commentCardVariants({ highlighted, isOwnComment })}>+ <MarkdownView+ markdown={content}+ className="text-foreground p-0 text-sm leading-6 wrap-anywhere [&_h1]:text-base [&_h2]:text-base [&_h3]:text-sm [&_h4]:text-sm [&_h5]:text-sm [&_h6]:text-sm"+ />+ {location ? (+ <div className="text-muted-foreground min-w-0 pt-2 text-xs">+ {location}+ </div>+ ) : null}+ </div>+ <div className="text-muted-foreground flex min-h-6 max-w-full flex-wrap items-center gap-x-2 gap-y-1 px-1">+ <span className="text-[11px]">{timestamp}</span>+ {footer ? (+ <div className="flex flex-wrap items-center gap-1">{footer}</div>+ ) : null}+ {actions}+ </div>+ </div>+ </article>+ );+}diff --git a/web/src/features/comments/components/CommentComposer.tsx b/web/src/features/comments/components/CommentComposer.tsxnew file mode 100644index 0000000000..3616dadec8--- /dev/null+++ b/web/src/features/comments/components/CommentComposer.tsx@@ -0,0 +1,238 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { type z } from "zod";+import { type CommentObjectType, CreateCommentData } from "@langfuse/shared";+import { Button } from "@/src/components/ui/button";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormMessage,+} from "@/src/components/ui/form";+import { KeyboardShortcut } from "@/src/components/design-system/KeyboardShortcut/KeyboardShortcut";+import {+ Popover,+ PopoverAnchor,+ PopoverContent,+} from "@/src/components/ui/popover";+import { useHasProjectAccess } from "@/src/features/rbac";+import { api } from "@/src/utils/api";+import { CommentEditor, type CommentEditorHandle } from "./CommentEditor";+import { MentionAutocomplete } from "./MentionAutocomplete";+import { useMentionAutocomplete } from "../hooks/useMentionAutocomplete";+import { MENTION_USER_PREFIX } from "../lib/mentionParser";+import { type SelectionData } from "../contexts/InlineCommentSelectionContext";++export function CommentComposer({+ projectId,+ objectId,+ objectType,+ objectStartTime,+ pendingSelection,+ onSelectionUsed,+ onDraftChange,+ onMentionDropdownChange,+ onCommentCreated,+}: {+ projectId: string;+ objectId: string;+ objectType: CommentObjectType;+ objectStartTime?: Date | null;+ pendingSelection?: SelectionData | null;+ onSelectionUsed?: () => void;+ onDraftChange?: (hasDraft: boolean) => void;+ onMentionDropdownChange?: (isOpen: boolean) => void;+ onCommentCreated: () => void | Promise<void>;+}) {+ const editorRef = useRef<CommentEditorHandle>(null);+ const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(+ null,+ );+ const [cursorAnchor] = useState(() => ({+ getBoundingClientRect: () =>+ editorRef.current?.getCursorRect() ?? new DOMRect(),+ }));+ const attachForm = useCallback((node: HTMLFormElement | null) => {+ if (node) setPortalContainer(node.closest<HTMLElement>('[role="dialog"]'));+ }, []);+ const hasMembersReadAccess = useHasProjectAccess({+ projectId,+ scope: "projectMembers:read",+ });+ const form = useForm({+ resolver: zodResolver(CreateCommentData),+ defaultValues: { content: "", projectId, objectId, objectType },+ });+ const mentions = useMentionAutocomplete({+ projectId,+ enabled: hasMembersReadAccess,+ onOpenChange: onMentionDropdownChange,+ });++ const { showDropdown, closeDropdown } = mentions;++ // Window capture runs before the overlay's document-level Escape handler.+ useEffect(() => {+ if (!showDropdown) return;+ function dismissMentions(event: KeyboardEvent) {+ if (event.key !== "Escape") return;+ event.preventDefault();+ event.stopImmediatePropagation();+ closeDropdown();+ }+ window.addEventListener("keydown", dismissMentions, true);+ return () => window.removeEventListener("keydown", dismissMentions, true);+ }, [showDropdown, closeDropdown]);++ const createComment = api.comments.create.useMutation({+ onSuccess: async () => {+ form.reset();+ onDraftChange?.(false);+ mentions.closeDropdown();+ onSelectionUsed?.();+ await onCommentCreated();+ editorRef.current?.focus();+ },+ });++ function submit(values: z.infer<typeof CreateCommentData>) {+ if (createComment.isPending) return;+ createComment.mutate({+ ...values,+ objectStartTime: objectStartTime ?? undefined,+ dataField: pendingSelection?.dataField,+ path: pendingSelection?.path,+ rangeStart: pendingSelection?.rangeStart,+ rangeEnd: pendingSelection?.rangeEnd,+ });+ }++ function insertMention(userId: string, displayName: string) {+ const editor = editorRef.current;+ if (!editor || mentions.mentionStartPos === null) return;+ editor.replaceRange(+ mentions.mentionStartPos,+ editor.getCursorPosition(),+ `@[${displayName}](${MENTION_USER_PREFIX}${userId}) `,+ );+ mentions.closeDropdown();+ editor.focus();+ }++ function handleKeyDown(event: KeyboardEvent): boolean {+ if (event.isComposing) return false;+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ form.handleSubmit(submit)();+ return true;+ }+ if (!mentions.showDropdown) return false;+ if (event.key === "Escape") {+ event.stopPropagation();+ event.stopImmediatePropagation();+ mentions.closeDropdown();+ return true;+ }+ if (!mentions.users.length) return false;+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ const direction = event.key === "ArrowDown" ? 1 : -1;+ mentions.setSelectedIndex(+ (mentions.selectedIndex + direction + mentions.users.length) %+ mentions.users.length,+ );+ return true;+ }+ if (event.key === "Enter" || event.key === "Tab") {+ const user = mentions.users[mentions.selectedIndex];+ if (user) insertMention(user.id, user.name || user.email || "User");+ return true;+ }+ return false;+ }++ return (+ <Form {...form}>+ <form+ ref={attachForm}+ className="flex min-w-0 flex-col gap-3"+ onSubmit={form.handleSubmit(submit)}+ >+ {pendingSelection && (+ <p className="text-muted-foreground text-xs">+ Commenting on selected {pendingSelection.dataField} text+ </p>+ )}+ <FormField+ control={form.control}+ name="content"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <CommentEditor+ ref={editorRef}+ value={field.value}+ onChange={(value) => {+ field.onChange(value);+ onDraftChange?.(value.trim().length > 0);+ }}+ onCursorChange={(position) =>+ mentions.updateQuery(form.getValues("content"), position)+ }+ onKeyDown={handleKeyDown}+ disabled={createComment.isPending}+ autoFocus+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Popover+ open={mentions.showDropdown}+ onOpenChange={(open) => {+ if (!open) mentions.closeDropdown();+ }}+ >+ <PopoverAnchor virtualRef={{ current: cursorAnchor }} />+ <PopoverContent+ portalContainer={portalContainer}+ align="start"+ sideOffset={6}+ className="w-72 min-w-0 p-1"+ updatePositionStrategy="always"+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ >+ <MentionAutocomplete+ users={mentions.users}+ isLoading={mentions.isLoading}+ selectedIndex={mentions.selectedIndex}+ onSelect={insertMention}+ onSelectedIndexChange={mentions.setSelectedIndex}+ />+ </PopoverContent>+ </Popover>+ <div className="flex items-center justify-between gap-3">+ <p className="text-muted-foreground text-xs">+ {hasMembersReadAccess+ ? "Markdown and @mentions supported"+ : "Markdown supported"}+ </p>+ <div className="flex shrink-0 items-center gap-3">+ <span className="text-muted-foreground hidden sm:inline-flex">+ <KeyboardShortcut keys={["Mod", "Enter"]} />+ </span>+ <Button+ type="submit"+ loading={createComment.isPending}+ disabled={!form.watch("content").trim()}+ >+ Comment+ </Button>+ </div>+ </div>+ </form>+ </Form>+ );+}diff --git a/web/src/features/comments/components/CommentConversation.tsx b/web/src/features/comments/components/CommentConversation.tsxnew file mode 100644index 0000000000..709a6e5042--- /dev/null+++ b/web/src/features/comments/components/CommentConversation.tsx@@ -0,0 +1,246 @@+import { useEffect, useRef, useState, type RefObject } from "react";+import { useRouter } from "next/router";+import { type CommentObjectType } from "@langfuse/shared";+import { api, type RouterOutputs } from "@/src/utils/api";+import { Button } from "@/src/components/ui/button";+import { Input } from "@/src/components/ui/input";+import { Badge } from "@/src/components/ui/badge";+import { Search, Trash, X } from "lucide-react";+import { getRelativeTimestampFromNow } from "@/src/utils/dates";+import { stripMarkdown } from "@/src/utils/markdown";+import { ReactionBar } from "../ReactionBar";+import { ReactionPicker } from "../ReactionPicker";+import { CommentCard } from "./CommentCard";++function humanizeJsonPath(path: string): string {+ if (path === "$") return "(root)";+ return path+ .replace(/^\$\.?/, "")+ .replace(/\[(\d+)\]/g, ".$1")+ .split(".")+ .filter(Boolean)+ .join(" › ");+}++export function CommentConversation({+ projectId,+ objectId,+ objectType,+ comments,+ currentUserId,+ hasWriteAccess,+ isDrawerOpen,+ containerRef: commentsContainerRef,+ onCommentChange,+}: {+ projectId: string;+ objectId: string;+ objectType: CommentObjectType;+ comments: RouterOutputs["comments"]["getByObjectId"];+ currentUserId?: string;+ hasWriteAccess: boolean;+ isDrawerOpen: boolean;+ containerRef: RefObject<HTMLDivElement | null>;+ onCommentChange: () => Promise<void>;+}) {+ const router = useRouter();+ const [searchQuery, setSearchQuery] = useState("");+ const searchInputRef = useRef<HTMLInputElement>(null);+ const didInitialAutoscrollRef = useRef(false);+ const hash = router.asPath.split("#")[1];+ const highlightedCommentId = hash?.startsWith("comment-")+ ? hash.slice("comment-".length)+ : null;+ const utils = api.useUtils();+ const deleteComment = api.comments.delete.useMutation({+ onSuccess: onCommentChange,+ });+ const addReaction = api.commentReactions.add.useMutation({+ onSuccess: (_data, { commentId }) =>+ utils.commentReactions.listForComment.invalidate({+ projectId,+ commentId,+ }),+ });+ const removeReaction = api.commentReactions.remove.useMutation({+ onSuccess: (_data, { commentId }) =>+ utils.commentReactions.listForComment.invalidate({+ projectId,+ commentId,+ }),+ });++ // Keep the DOM scroll position on the linked comment or the latest conversation.+ useEffect(() => {+ const container = commentsContainerRef.current;+ if (!comments || !container) return;+ const frame = requestAnimationFrame(() => {+ if (highlightedCommentId) {+ document+ .getElementById(`comment-${highlightedCommentId}`)+ ?.scrollIntoView({ block: "center" });+ } else if (!didInitialAutoscrollRef.current) {+ container.scrollTop = container.scrollHeight;+ didInitialAutoscrollRef.current = true;+ }+ });+ return () => cancelAnimationFrame(frame);+ }, [comments, highlightedCommentId, commentsContainerRef]);++ useEffect(() => {+ if (!isDrawerOpen) return;+ function focusSearch(event: KeyboardEvent) {+ if (+ event.target instanceof HTMLElement &&+ event.target.closest("input, textarea, [contenteditable=true]")+ )+ return;+ if ((event.metaKey || event.ctrlKey) && event.key === "f") {+ event.preventDefault();+ searchInputRef.current?.focus();+ }+ }+ window.addEventListener("keydown", focusSearch, { capture: true });+ return () =>+ window.removeEventListener("keydown", focusSearch, { capture: true });+ }, [isDrawerOpen]);++ const sortedComments = [...comments].sort(+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime(),+ );+ const query = searchQuery.trim().toLowerCase();+ const filteredComments = sortedComments.filter(+ (comment) =>+ !query ||+ stripMarkdown(comment.content).toLowerCase().includes(query) ||+ (comment.authorUserName ?? comment.authorUserId ?? "")+ .toLowerCase()+ .includes(query),+ );++ return (+ <>+ {comments.length > 0 && (+ <div className="flex shrink-0 flex-col gap-2 border-b px-4 py-3">+ <div className="relative">+ <Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2" />+ <Input+ ref={searchInputRef}+ aria-label="Search comments"+ placeholder="Search comments…"+ value={searchQuery}+ onChange={(event) => setSearchQuery(event.target.value)}+ className="h-9 pr-9 pl-9"+ />+ {searchQuery && (+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ title="Clear search"+ className="absolute top-1/2 right-2 -translate-y-1/2"+ onClick={() => setSearchQuery("")}+ >+ <X className="size-3" />+ </Button>+ )}+ </div>+ <p className="text-muted-foreground text-xs" aria-live="polite">+ {query+ ? `${filteredComments.length} of ${comments.length} comments`+ : `${comments.length} comment${comments.length === 1 ? "" : "s"}`}+ </p>+ </div>+ )}+ <div+ ref={commentsContainerRef}+ className="min-h-0 flex-1 overflow-y-auto px-4 py-4"+ >+ <div className="flex min-h-full flex-col justify-end gap-4">+ {filteredComments.length === 0 && (+ <p className="text-muted-foreground py-6 text-sm">+ {query ? "No comments match your search." : "No comments yet."}+ </p>+ )}+ {filteredComments.map((comment) => (+ <CommentCard+ key={comment.id}+ id={comment.id}+ authorName={+ comment.authorUserName ?? comment.authorUserId ?? "User"+ }+ authorImage={comment.authorUserImage}+ timestamp={getRelativeTimestampFromNow(comment.createdAt)}+ content={comment.content}+ highlighted={highlightedCommentId === comment.id}+ isOwnComment={currentUserId === comment.authorUserId}+ location={+ comment.dataField && comment.path.length > 0 ? (+ <div className="flex min-w-0 items-center gap-2">+ <Badge variant="outline" className="shrink-0 text-[10px]">+ {comment.dataField.toUpperCase()}+ </Badge>+ <span className="truncate" title={comment.path[0]}>+ {humanizeJsonPath(comment.path[0])}+ </span>+ </div>+ ) : null+ }+ actions={+ hasWriteAccess && currentUserId === comment.authorUserId ? (+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ title="Delete comment"+ loading={deleteComment.isPending}+ onClick={() => {+ if (+ window.confirm(+ "Are you sure you want to delete this comment?",+ )+ )+ deleteComment.mutate({+ commentId: comment.id,+ projectId,+ objectId,+ objectType,+ });+ }}+ >+ <Trash className="size-3.5" />+ </Button>+ ) : null+ }+ footer={+ <>+ <ReactionBar+ projectId={projectId}+ commentId={comment.id}+ onReactionToggle={(emoji, hasReacted) => {+ if (!hasWriteAccess) return;+ const input = { projectId, commentId: comment.id, emoji };+ if (hasReacted) removeReaction.mutate(input);+ else addReaction.mutate(input);+ }}+ />+ {hasWriteAccess && (+ <ReactionPicker+ onEmojiSelect={(emoji) =>+ addReaction.mutate({+ projectId,+ commentId: comment.id,+ emoji,+ })+ }+ />+ )}+ </>+ }+ />+ ))}+ </div>+ </div>+ </>+ );+}diff --git a/web/src/features/comments/components/CommentEditor.stories.tsx b/web/src/features/comments/components/CommentEditor.stories.tsxnew file mode 100644index 0000000000..4776c28cc5--- /dev/null+++ b/web/src/features/comments/components/CommentEditor.stories.tsx@@ -0,0 +1,189 @@+import { useRef, useState, type ComponentProps } from "react";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";+import preview from "../../../../.storybook/preview";+import { Button } from "@/src/components/ui/button";+import { CommentEditor, type CommentEditorHandle } from "./CommentEditor";++const meta = preview.meta({ component: CommentEditor });++function ControlledEditor(args: ComponentProps<typeof CommentEditor>) {+ const [value, setValue] = useState(args.value);+ return (+ <CommentEditor+ {...args}+ value={value}+ onChange={(nextValue) => {+ setValue(nextValue);+ args.onChange(nextValue);+ }}+ />+ );+}++export const Empty = meta.story({+ args: { value: "", onChange: fn() },+ render: (args) => <ControlledEditor {...args} />,+});++export const TestEmptyCaret = meta.story({+ name: "(Test) Keeps The Empty Caret Inside The Scrollport",+ args: { value: "", onChange: fn() },+ render: (args) => <ControlledEditor {...args} />,+ play: async ({ canvasElement }) => {+ const textbox = within(canvasElement).getByRole("textbox", {+ name: "New comment",+ });+ await userEvent.click(textbox);+ await expect(textbox).toHaveFocus();+ await waitFor(() => {+ const editor = textbox.closest(".cm-editor");+ const cursor = editor?.querySelector(".cm-cursor-primary");+ const scroller = editor?.querySelector(".cm-scroller");+ expect(cursor).not.toBeNull();+ expect(scroller).not.toBeNull();+ if (!cursor || !scroller) return;+ const caretBounds = cursor.getBoundingClientRect();+ const scrollBounds = scroller.getBoundingClientRect();+ expect(caretBounds.left).toBeGreaterThanOrEqual(scrollBounds.left);+ expect(caretBounds.right).toBeLessThanOrEqual(scrollBounds.right);+ });+ },+});++export const WithMentions = meta.story({+ args: {+ value: "Could @[Alice](user:alice_1) review this **response**?\nThanks!",+ onChange: fn(),+ },+ render: (args) => <ControlledEditor {...args} />,+});++export const Disabled = meta.story({+ args: {+ value: "Thanks @[Alice](user:alice_1)!",+ onChange: fn(),+ disabled: true,+ },+});++export const TestInsertedMention = meta.story({+ name: "(Test) Inserts Mention Without Exposing Syntax",+ args: { value: "Review @al", onChange: fn(), onCursorChange: fn() },+ render: (args) => {+ const [value, setValue] = useState(args.value);+ const editorRef = useRef<CommentEditorHandle>(null);+ return (+ <>+ <CommentEditor+ {...args}+ ref={editorRef}+ value={value}+ onChange={(nextValue) => {+ setValue(nextValue);+ args.onChange(nextValue);+ }}+ />+ <Button+ onClick={() =>+ editorRef.current?.replaceRange(+ 7,+ 10,+ "@[Alice [Ops]](user:alice_1) ",+ )+ }+ >+ Mention Alice+ </Button>+ </>+ );+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(+ canvas.getByRole("button", { name: "Mention Alice" }),+ );+ const raw = "Review @[Alice [Ops]](user:alice_1) ";+ await expect(args.onChange).toHaveBeenLastCalledWith(raw);+ await expect(args.onCursorChange).toHaveBeenLastCalledWith(raw.length);+ const textbox = canvas.getByRole("textbox", { name: "New comment" });+ await expect(textbox).toHaveTextContent("Review @Alice [Ops]");+ await expect(textbox).not.toHaveTextContent("user:alice_1");+ await userEvent.keyboard("Looks good");+ await expect(args.onChange).toHaveBeenLastCalledWith(`${raw}Looks good`);+ },+});++export const TestAtomicMentionNavigation = meta.story({+ name: "(Test) Navigates And Deletes A Whole Mention",+ args: {+ value: "Hi @[Alice](user:alice_1)!",+ onChange: fn(),+ onCursorChange: fn(),+ },+ render: (args) => <ControlledEditor {...args} />,+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const textbox = canvas.getByRole("textbox", { name: "New comment" });+ await userEvent.click(textbox);+ await userEvent.keyboard("{End}{ArrowLeft}");+ await expect(args.onCursorChange).toHaveBeenLastCalledWith(+ args.value.length - 1,+ );+ await userEvent.keyboard("{ArrowLeft}");+ await expect(args.onCursorChange).toHaveBeenLastCalledWith(3);+ await userEvent.keyboard("{ArrowRight}{Backspace}");+ await expect(args.onChange).toHaveBeenLastCalledWith("Hi !");+ await expect(textbox).toHaveTextContent("Hi !");+ },+});++export const TestMultilineMentionName = meta.story({+ name: "(Test) Preserves Multiline Mention Names In Storage",+ args: {+ value: "@[Alice [Ops]\nOn call](user:alice_1)",+ onChange: fn(),+ },+ render: (args) => <ControlledEditor {...args} />,+ play: async ({ args, canvasElement }) => {+ const textbox = within(canvasElement).getByRole("textbox", {+ name: "New comment",+ });+ await expect(textbox).toHaveTextContent("@Alice [Ops] On call");+ await expect(textbox).not.toHaveTextContent("user:alice_1");+ await userEvent.click(textbox);+ await userEvent.keyboard("{End} thanks");+ await expect(args.onChange).toHaveBeenLastCalledWith(+ `${args.value} thanks`,+ );+ },+});++export const TestHandledKeyDoesNotEdit = meta.story({+ name: "(Test) Lets The Composer Handle Enter Before Editing",+ args: {+ value: "Draft",+ onChange: fn(),+ onKeyDown: fn((event: KeyboardEvent) => event.key === "Enter"),+ id: "comment-content",+ "aria-invalid": true,+ "aria-describedby": "comment-error",+ },+ render: (args) => (+ <>+ <ControlledEditor {...args} />+ <p id="comment-error">Comment is too long.</p>+ </>+ ),+ play: async ({ args, canvasElement }) => {+ const textbox = within(canvasElement).getByRole("textbox", {+ name: "New comment",+ });+ await expect(textbox).toHaveAttribute("id", "comment-content");+ await expect(textbox).toHaveAttribute("aria-invalid", "true");+ await expect(textbox).toHaveAccessibleDescription("Comment is too long.");+ await userEvent.click(textbox);+ await userEvent.keyboard("{End}{Enter}!");+ await expect(args.onChange).toHaveBeenLastCalledWith("Draft!");+ await expect(args.onKeyDown).toHaveBeenCalled();+ },+});diff --git a/web/src/features/comments/components/CommentEditor.tsx b/web/src/features/comments/components/CommentEditor.tsxnew file mode 100644index 0000000000..a13d60051c--- /dev/null+++ b/web/src/features/comments/components/CommentEditor.tsx@@ -0,0 +1,172 @@+import {+ forwardRef,+ useImperativeHandle,+ useMemo,+ useRef,+ type AriaAttributes,+} from "react";+import CodeMirror, {+ EditorView,+ type ReactCodeMirrorRef,+} from "@uiw/react-codemirror";+import { Prec } from "@codemirror/state";+import { commentEditorMentions } from "./CommentEditorMentions";++export type CommentEditorHandle = {+ focus: () => void;+ getCursorPosition: () => number;+ getCursorRect: () => DOMRect;+ replaceRange: (from: number, to: number, text: string) => void;+};++type CommentEditorProps = {+ id?: string;+ "aria-invalid"?: AriaAttributes["aria-invalid"];+ "aria-describedby"?: string;+ value: string;+ onChange: (value: string) => void;+ onCursorChange?: (offset: number) => void;+ onKeyDown?: (event: KeyboardEvent) => boolean;+ disabled?: boolean;+ autoFocus?: boolean;+};++const basicSetup = {+ lineNumbers: false,+ foldGutter: false,+ highlightActiveLine: false,+ highlightActiveLineGutter: false,+ highlightSelectionMatches: false,+ searchKeymap: false,+ autocompletion: false,+ bracketMatching: false,+ closeBrackets: false,+};++const editorTheme = EditorView.theme({+ "&": { backgroundColor: "transparent", color: "inherit" },+ "&.cm-focused": { outline: "none" },+ ".cm-scroller": { fontFamily: "inherit", maxHeight: "12rem" },+ ".cm-content": { padding: "0", minHeight: "5rem" },+ ".cm-line": { padding: "0 1px" },+ ".cm-cursor, .cm-dropCursor": { borderLeftColor: "currentColor" },+ ".cm-placeholder": { color: "hsl(var(--muted-foreground))" },+ ".cm-selectionBackground, &.cm-focused .cm-selectionBackground": {+ backgroundColor: "hsl(var(--primary) / 0.18)",+ },+});++export const CommentEditor = forwardRef<+ CommentEditorHandle,+ CommentEditorProps+>(function CommentEditor(+ {+ id,+ "aria-invalid": ariaInvalid,+ "aria-describedby": ariaDescribedBy,+ value,+ onChange,+ onCursorChange,+ onKeyDown,+ disabled,+ autoFocus,+ },+ ref,+) {+ const editorRef = useRef<ReactCodeMirrorRef>(null);++ useImperativeHandle(+ ref,+ () => ({+ focus: () => editorRef.current?.view?.focus(),+ getCursorPosition: () =>+ editorRef.current?.view?.state.selection.main.head ?? 0,+ getCursorRect: () => {+ const view = editorRef.current?.view;+ const rect = view?.coordsAtPos(view.state.selection.main.head);+ return rect+ ? new DOMRect(+ rect.left,+ rect.top,+ rect.right - rect.left,+ rect.bottom - rect.top,+ )+ : new DOMRect();+ },+ replaceRange: (from, to, text) => {+ const view = editorRef.current?.view;+ if (!view || disabled) return;+ view.dispatch({+ changes: { from, to, insert: text },+ selection: { anchor: from + text.length },+ scrollIntoView: true,+ userEvent: "input.complete",+ });+ view.focus();+ },+ }),+ [disabled],+ );++ // CodeMirror reconfigures when extensions change identity.+ const extensions = useMemo(+ () => [+ editorTheme,+ commentEditorMentions,+ EditorView.lineWrapping,+ EditorView.contentAttributes.of({+ "aria-label": "New comment",+ "aria-multiline": "true",+ ...(id === undefined ? {} : { id }),+ ...(ariaInvalid === undefined+ ? {}+ : { "aria-invalid": String(ariaInvalid) }),+ ...(ariaDescribedBy === undefined+ ? {}+ : { "aria-describedby": ariaDescribedBy }),+ spellcheck: "true",+ }),+ Prec.highest(+ EditorView.domEventHandlers({+ keydown: (event) => {+ if (disabled || event.isComposing || !onKeyDown?.(event)) {+ return false;+ }+ event.preventDefault();+ return true;+ },+ }),+ ),+ ],+ [ariaDescribedBy, ariaInvalid, disabled, id, onKeyDown],+ );++ return (+ <div+ data-disabled={disabled || undefined}+ className="border-input focus-within:ring-ring ph-no-capture min-w-0 rounded-md border px-3 py-2 text-sm focus-within:ring-1 data-disabled:opacity-50"+ >+ <CodeMirror+ ref={editorRef}+ value={value}+ onChange={onChange}+ onUpdate={(update) => {+ if (update.selectionSet || update.docChanged) {+ onCursorChange?.(update.state.selection.main.head);+ }+ }}+ onCreateEditor={(view) => {+ onCursorChange?.(view.state.selection.main.head);+ }}+ extensions={extensions}+ basicSetup={basicSetup}+ theme="none"+ indentWithTab={false}+ editable={!disabled}+ readOnly={disabled}+ autoFocus={autoFocus}+ placeholder="Add a comment..."+ />+ </div>+ );+});diff --git a/web/src/features/comments/components/CommentEditorMentions.ts b/web/src/features/comments/components/CommentEditorMentions.tsnew file mode 100644index 0000000000..41877db264--- /dev/null+++ b/web/src/features/comments/components/CommentEditorMentions.ts@@ -0,0 +1,64 @@+import { StateField, type EditorState } from "@codemirror/state";+import {+ Decoration,+ type DecorationSet,+ EditorView,+ WidgetType,+} from "@uiw/react-codemirror";+import { MENTION_USER_PREFIX } from "@/src/features/comments/lib/mentionParser";++class MentionWidget extends WidgetType {+ constructor(+ private readonly displayName: string,+ private readonly userId: string,+ ) {+ super();+ }++ eq(other: MentionWidget) {+ return (+ other.displayName === this.displayName && other.userId === this.userId+ );+ }++ toDOM() {+ const chip = document.createElement("span");+ chip.textContent = `@${this.displayName.replace(/\s+/g, " ")}`;+ chip.dataset.userId = this.userId;+ chip.contentEditable = "false";+ chip.className =+ "bg-accent text-accent-foreground rounded px-1 py-0.5 font-bold";+ return chip;+ }++ ignoreEvent() {+ return false;+ }+}++function decorateMentions(state: EditorState): DecorationSet {+ // Keep the wire-format boundaries aligned with mentionParser, including+ // bracketed and multiline display names. Only the chip normalizes whitespace.+ const pattern = new RegExp(+ `@\\[([\\s\\S]{1,100}?)\\]\\(${MENTION_USER_PREFIX}([a-z0-9_-]{1,30})\\)`,+ "gi",+ );+ const ranges = Array.from(state.doc.toString().matchAll(pattern), (match) =>+ Decoration.replace({+ widget: new MentionWidget(match[1]!, match[2]!),+ }).range(match.index, match.index + match[0].length),+ );+ return Decoration.set(ranges);+}++// A state field supplies decorations before layout, so a mention can replace+// line breaks in its stored display name as well as ordinary inline text.+export const commentEditorMentions = StateField.define<DecorationSet>({+ create: decorateMentions,+ update: (decorations, transaction) =>+ transaction.docChanged ? decorateMentions(transaction.state) : decorations,+ provide: (field) => [+ EditorView.decorations.from(field),+ EditorView.atomicRanges.of((view) => view.state.field(field)),+ ],+});diff --git a/web/src/features/comments/components/CommentOverlayHost.tsx b/web/src/features/comments/components/CommentOverlayHost.tsxnew file mode 100644index 0000000000..ef39c6ec25--- /dev/null+++ b/web/src/features/comments/components/CommentOverlayHost.tsx@@ -0,0 +1,201 @@+import { useState, type ReactNode } from "react";+import { useStore } from "zustand";+import { useRouter } from "next/router";+import { X } from "lucide-react";+import { type CommentObjectType } from "@langfuse/shared";+import {+ Drawer,+ DrawerContent,+ DrawerHeader,+ DrawerTitle,+ DrawerClose,+} from "@/src/components/ui/drawer";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogBody,+} from "@/src/components/ui/dialog";+import { Button } from "@/src/components/ui/button";+import { api } from "@/src/utils/api";+import { CommentList } from "../CommentList";+import { CommentComposer } from "./CommentComposer";+import { type SelectionData } from "../contexts/InlineCommentSelectionContext";+import {+ type CommentOverlay,+ type CommentOverlayStore,+ type CommentTarget,+} from "../state/commentOverlayStore";+import { refreshCommentQueries } from "../actions/refreshCommentQueries";++export function CommentOverlayState({+ store,+ initialState,+ children,+}: {+ store: CommentOverlayStore;+ initialState?: () => CommentTarget | undefined;+ children: (overlay: CommentOverlay) => ReactNode;+}) {+ const [initialOverlay] = useState<CommentOverlay | undefined>(() => {+ const target = initialState?.();+ return target+ ? { id: 0, target, presentation: "thread", isOpen: true }+ : undefined;+ });+ const selectedOverlay = useStore(store, (state) => state.overlay);+ const overlay = selectedOverlay ?? initialOverlay;+ return overlay ? children(overlay) : null;+}++export function CommentOverlayHost({+ store,+ projectId,+ overlay,+ onCommentChange,+}: {+ store: CommentOverlayStore;+ projectId: string;+ overlay: CommentOverlay;+ onCommentChange?: () => void | Promise<void>;+}) {+ const router = useRouter();+ const utils = api.useUtils();+ const actions = store.getState().actions;+ const target = overlay.target;+ const clearCommentUrl = () => {+ if (router.query.comments !== "open") return;+ const { comments, commentObjectType, commentObjectId, ...rest } =+ router.query;+ router.replace({ pathname: router.pathname, query: rest }, undefined, {+ shallow: true,+ });+ };+ const close = () => {+ if (+ actions.close(overlay, () =>+ window.confirm("Discard your unsent comment?"),+ )+ )+ clearCommentUrl();+ };+ const guardProps = {+ onDraftChange: (hasDraft: boolean) =>+ actions.setDraft(overlay.id, hasDraft),+ onMentionDropdownChange: (open: boolean) =>+ actions.setMentionsOpen(overlay.id, open),+ };+ return overlay.presentation === "composer" ? (+ <Dialog+ open={overlay.isOpen}+ onOpenChange={(open) => {+ if (!open) close();+ }}+ >+ <DialogContent className="overflow-visible" closeOnInteractionOutside>+ <DialogHeader>+ <DialogTitle>Add a comment</DialogTitle>+ </DialogHeader>+ <DialogBody>+ <CommentComposer+ key={overlay.id}+ projectId={projectId}+ objectId={target.objectId}+ objectType={target.objectType}+ objectStartTime={target.objectStartTime}+ pendingSelection={+ target.type === "inline-comment" ? target.selection : null+ }+ {...guardProps}+ onCommentCreated={async () => {+ if (actions.close(overlay)) clearCommentUrl();+ await refreshCommentQueries({+ utils,+ target: { projectId, ...target },+ onCommentChange,+ });+ }}+ />+ </DialogBody>+ </DialogContent>+ </Dialog>+ ) : (+ <Drawer+ open={overlay.isOpen}+ blockTextSelection={false}+ onOpenChange={(open) => {+ if (!open) close();+ }}+ >+ <CommentDrawerContent+ key={overlay.id}+ projectId={projectId}+ objectId={target.objectId}+ objectType={target.objectType}+ objectStartTime={target.objectStartTime}+ pendingSelection={+ target.type === "inline-comment" ? target.selection : null+ }+ onSelectionUsed={() => actions.consumeSelection(overlay)}+ onCommentChange={onCommentChange}+ {...guardProps}+ />+ </Drawer>+ );+}++type CommentDrawerContentProps = {+ projectId: string;+ objectId: string;+ objectType: CommentObjectType;+ objectStartTime?: Date | null;+ pendingSelection: SelectionData | null;+ onSelectionUsed: () => void;+ onCommentChange?: () => void | Promise<void>;+ onMentionDropdownChange: (isOpen: boolean) => void;+ onDraftChange: (hasDraft: boolean) => void;+};++function CommentDrawerContent({+ projectId,+ objectId,+ objectType,+ objectStartTime,+ pendingSelection,+ onSelectionUsed,+ onCommentChange,+ onMentionDropdownChange,+ onDraftChange,+}: CommentDrawerContentProps) {+ return (+ <DrawerContent+ overlayClassName="bg-primary/10"+ className="h-screen-with-banner max-h-screen-with-banner overflow-hidden outline-hidden"+ >+ <DrawerHeader className="flex shrink-0 flex-row items-center justify-between border-b text-left">+ <DrawerTitle>Comments</DrawerTitle>+ <DrawerClose asChild>+ <Button variant="ghost" size="icon" title="Close comments">+ <X className="size-4" />+ </Button>+ </DrawerClose>+ </DrawerHeader>+ <div data-vaul-no-drag className="min-h-0 flex-1 overflow-hidden">+ <CommentList+ key={`${projectId}-${objectType}-${objectId}`}+ projectId={projectId}+ objectId={objectId}+ objectType={objectType}+ objectStartTime={objectStartTime}+ onMentionDropdownChange={onMentionDropdownChange}+ onDraftChange={onDraftChange}+ isDrawerOpen+ pendingSelection={pendingSelection}+ onSelectionUsed={onSelectionUsed}+ onCommentChange={onCommentChange}+ />+ </div>+ </DrawerContent>+ );+}diff --git a/web/src/features/comments/components/MentionAutocomplete.tsx b/web/src/features/comments/components/MentionAutocomplete.tsxindex 92dad7919e..592dfeaebb 100644--- a/web/src/features/comments/components/MentionAutocomplete.tsx+++ b/web/src/features/comments/components/MentionAutocomplete.tsx@@ -20,7 +20,6 @@ interface MentionAutocompleteProps {isLoading: boolean;selectedIndex: number;onSelect: (userId: string, displayName: string) => void;- onClose: () => void;onSelectedIndexChange: (index: number) => void;}@@ -29,7 +28,6 @@ export function MentionAutocomplete({isLoading,selectedIndex,onSelect,- onClose: _onClose,onSelectedIndexChange,}: MentionAutocompleteProps) {const selectedItemRef = useRef<HTMLDivElement>(null);@@ -42,25 +40,22 @@ export function MentionAutocomplete({// Get the currently selected user's ID for Command's value propconst selectedUserId = users[selectedIndex]?.id;- // Limit displayed users to first 3- const MAX_DISPLAYED_USERS = 3;- const displayedUsers = users.slice(0, MAX_DISPLAYED_USERS);- const remainingCount = users.length - MAX_DISPLAYED_USERS;-return (<div- className="absolute right-0 bottom-full left-0 z-50 mb-1"+ className="ph-no-capture min-w-0"role="region"aria-label="User mention suggestions"><Command- className="max-h-60 rounded-md border shadow-md"+ className="rounded-md"value={selectedUserId}+ shouldFilter={false}aria-label="Mention user autocomplete"><CommandListrole="listbox"- aria-activedescendant={selectedUserId || ""}+ className="max-h-44"+ aria-label="People to mention">{isLoading && (<div@@ -78,10 +73,10 @@ export function MentionAutocomplete({{!isLoading && users.length > 0 && (<><CommandGroup>- {displayedUsers.map((user, index) => {+ {users.map((user, index) => {const displayName = user.name || user.email || "User";const isSelected = index === selectedIndex;- const userLabel = user.name || "Unknown";+ const userLabel = displayName;return (<CommandItemkey={user.id}@@ -115,15 +110,6 @@ export function MentionAutocomplete({);})}</CommandGroup>- {remainingCount > 0 && (- <div- className="text-muted-foreground border-t px-2 py-2 text-xs"- role="status"- aria-live="polite"- >- and {remainingCount} more...- </div>- )}</>)}</CommandList>diff --git a/web/src/features/comments/hooks/useMentionAutocomplete.ts b/web/src/features/comments/hooks/useMentionAutocomplete.tsindex 9e76ec5413..627d3825a6 100644--- a/web/src/features/comments/hooks/useMentionAutocomplete.ts+++ b/web/src/features/comments/hooks/useMentionAutocomplete.ts@@ -1,82 +1,54 @@-import { useState, useEffect, useCallback } from "react";+import { useState } from "react";import { useUserSearch } from "@/src/hooks/useUserSearch";export function useMentionAutocomplete({projectId,- getTextareaValue,- cursorPosition,enabled,+ onOpenChange,}: {projectId: string;- getTextareaValue: () => string;- cursorPosition: number;enabled: boolean;+ onOpenChange?: (open: boolean) => void;}) {- const [showDropdown, setShowDropdown] = useState(false);const [mentionStartPos, setMentionStartPos] = useState<number | null>(null);const [selectedIndex, setSelectedIndex] = useState(0);-- // Use shared user search hook+ const showDropdown = enabled && mentionStartPos !== null;const userSearch = useUserSearch({projectId,limit: 10,- enabled: enabled && showDropdown,+ enabled: showDropdown,});- const { setSearchQuery } = userSearch;+ function closeDropdown() {+ setMentionStartPos(null);+ userSearch.setSearchQuery("");+ onOpenChange?.(false);+ }- // Detect @ character and update state- useEffect(() => {+ function updateQuery(value: string, cursorPosition: number) {if (!enabled) return;-- const textareaValue = getTextareaValue();- const textBeforeCursor = textareaValue.substring(0, cursorPosition);- const lastAtIndex = textBeforeCursor.lastIndexOf("@");-- if (lastAtIndex === -1) {- setShowDropdown(false);- setMentionStartPos(null);- return;- }-- // Check if @ is at start or preceded by whitespace- const charBeforeAt = textBeforeCursor[lastAtIndex - 1];- const isValidStart = lastAtIndex === 0 || /\s/.test(charBeforeAt);-- if (!isValidStart) {- setShowDropdown(false);+ const beforeCursor = value.slice(0, cursorPosition);+ const match = /(?:^|\s)@([^\s@[\]()]*)$/.exec(beforeCursor);+ if (!match) {+ closeDropdown();return;}-- // Get text after @ (search query)- const textAfterAt = textBeforeCursor.substring(lastAtIndex + 1);-- // Check if there's a space after @ (means mention is complete)- if (/\s/.test(textAfterAt)) {- setShowDropdown(false);- return;- }-- // Show dropdown- setMentionStartPos(lastAtIndex);- setSearchQuery(textAfterAt);- setShowDropdown(true);- setSelectedIndex(0);- }, [getTextareaValue, cursorPosition, enabled, setSearchQuery]);-- const closeDropdown = useCallback(() => {- setShowDropdown(false);- setMentionStartPos(null);- setSearchQuery("");- }, [setSearchQuery]);+ const query = match[1];+ setMentionStartPos(cursorPosition - query.length - 1);+ if (query !== userSearch.searchQuery) setSelectedIndex(0);+ userSearch.setSearchQuery(query);+ onOpenChange?.(true);+ }return {showDropdown,users: userSearch.searchResults,isLoading: userSearch.isLoading,- selectedIndex,+ selectedIndex:+ selectedIndex < userSearch.searchResults.length ? selectedIndex : 0,setSelectedIndex,mentionStartPos,closeDropdown,+ updateQuery,};}diff --git a/web/src/features/comments/state/commentOverlayStore.clienttest.ts b/web/src/features/comments/state/commentOverlayStore.clienttest.tsnew file mode 100644index 0000000000..37a66f46bf--- /dev/null+++ b/web/src/features/comments/state/commentOverlayStore.clienttest.ts@@ -0,0 +1,110 @@+import {+ createCommentOverlayStore,+ type CommentTarget,+} from "./commentOverlayStore";++const target: CommentTarget = {+ type: "comments",+ objectId: "first",+ objectType: "TRACE",+};+const selection = {+ dataField: "output" as const,+ path: ["$"],+ rangeStart: [0],+ rangeEnd: [4],+ selectedText: "text",+ anchorRect: null,+};+const input = {+ target,+ canWrite: true,+ loadComments: async () => [{ id: "comment" }],+ confirmDiscard: () => true,+};+function deferred() {+ let resolve!: (comments: { id: string }[]) => void;+ const promise = new Promise<{ id: string }[]>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++describe("comment overlay asynchronous actions", () => {+ it("does not reopen a dismissed inline thread when a late comment finishes", async () => {+ const store = createCommentOverlayStore();+ await store.getState().actions.open({+ ...input,+ target: { ...target, type: "inline-comment", selection },+ });+ const opened = store.getState().overlay!;+ store.getState().actions.close(opened, () => true);+ store.getState().actions.consumeSelection(opened);+ expect(store.getState().overlay?.isOpen).toBe(false);+ });++ it("keeps a draft edited while another target is loading", async () => {+ const store = createCommentOverlayStore();+ await store.getState().actions.open(input);+ const opened = store.getState().overlay!;+ const request = deferred();+ const opening = store.getState().actions.open({+ ...input,+ target: { ...target, objectId: "second" },+ loadComments: () => request.promise,+ });+ store.getState().actions.setDraft(opened.id, true);+ request.resolve([]);+ await opening;+ expect(store.getState().overlay?.target.objectId).toBe("first");+ expect(store.getState().hasDraft).toBe(true);+ expect(store.getState().actions.close(opened)).toBe(true);+ expect(store.getState().overlay?.isOpen).toBe(false);+ });++ it("keeps the latest inline selection on the same target", async () => {+ const store = createCommentOverlayStore();+ const request = deferred();+ const first = store.getState().actions.open({+ ...input,+ target: { ...target, type: "inline-comment", selection },+ loadComments: () => request.promise,+ });+ const latestSelection = { ...selection, rangeStart: [5], rangeEnd: [9] };+ const second = store.getState().actions.open({+ ...input,+ target: {+ ...target,+ type: "inline-comment",+ selection: latestSelection,+ },+ loadComments: () => request.promise,+ });+ request.resolve([]);+ await Promise.all([first, second]);+ expect(store.getState().overlay?.target).toMatchObject({+ selection: latestSelection,+ });+ });++ it("does not let completion in an older composer cancel a newer open request", async () => {+ const store = createCommentOverlayStore();+ await store+ .getState()+ .actions.open({ ...input, loadComments: async () => [] });+ const opened = store.getState().overlay!;+ const request = deferred();+ const opening = store.getState().actions.open({+ ...input,+ target: { ...target, objectId: "second" },+ loadComments: () => request.promise,+ });+ store.getState().actions.close(opened);+ request.resolve([{ id: "second-comment" }]);+ await opening;+ expect(store.getState().overlay).toMatchObject({+ isOpen: true,+ target: { objectId: "second" },+ });+ });+});diff --git a/web/src/features/comments/state/commentOverlayStore.ts b/web/src/features/comments/state/commentOverlayStore.tsnew file mode 100644index 0000000000..b7154bd397--- /dev/null+++ b/web/src/features/comments/state/commentOverlayStore.ts@@ -0,0 +1,129 @@+import { createStore } from "zustand/vanilla";+import { type CommentObjectType } from "@langfuse/shared";+import { type SelectionData } from "../contexts/InlineCommentSelectionContext";++export type CommentTarget = {+ objectId: string;+ objectType: CommentObjectType;+ objectStartTime?: Date | null;+} & (+ | { type: "comments" }+ | { type: "inline-comment"; selection: SelectionData }+);++export type CommentOverlay = {+ id: number;+ target: CommentTarget;+ presentation: "composer" | "thread";+ isOpen: boolean;+};++export function createCommentOverlayStore() {+ let requestId = 0;+ let pendingRequestId: number | undefined;+ let draftRevision = 0;+ return createStore<{+ overlay: CommentOverlay | undefined;+ hasDraft: boolean;+ mentionsOpen: boolean;+ actions: {+ open: (input: {+ target: CommentTarget;+ canWrite: boolean;+ loadComments: () => Promise<readonly unknown[]>;+ confirmDiscard: () => boolean;+ }) => Promise<void>;+ close: (+ overlay: CommentOverlay,+ confirmDiscard?: () => boolean,+ ) => boolean;+ setDraft: (sessionId: number, hasDraft: boolean) => void;+ setMentionsOpen: (sessionId: number, open: boolean) => void;+ consumeSelection: (overlay: CommentOverlay) => void;+ };+ }>((set, get) => ({+ overlay: undefined,+ hasDraft: false,+ mentionsOpen: false,+ actions: {+ async open({ target, canWrite, loadComments, confirmDiscard }) {+ if (get().hasDraft && !confirmDiscard()) return;+ const id = ++requestId;+ pendingRequestId = id;+ const initialDraftRevision = draftRevision;+ let presentation: CommentOverlay["presentation"] = "thread";+ try {+ const comments = await loadComments();+ if (comments.length === 0 && canWrite) presentation = "composer";+ } catch {+ // The thread query owns the error and retry UI.+ }+ if (requestId !== id) return;+ pendingRequestId = undefined;+ if (get().hasDraft && draftRevision !== initialDraftRevision) return;+ set({+ overlay: { id, target, presentation, isOpen: true },+ hasDraft: false,+ mentionsOpen: false,+ });+ },+ close(overlay, confirmDiscard) {+ const current = get();+ if (+ current.overlay &&+ (current.overlay.id !== overlay.id || !current.overlay.isOpen)+ )+ return false;+ if (!confirmDiscard && pendingRequestId !== undefined) return false;+ if (+ confirmDiscard &&+ (current.mentionsOpen || (current.hasDraft && !confirmDiscard()))+ )+ return false;+ ++requestId;+ pendingRequestId = undefined;+ set({+ overlay: { ...(current.overlay ?? overlay), isOpen: false },+ hasDraft: false,+ mentionsOpen: false,+ });+ return true;+ },+ setDraft(sessionId, hasDraft) {+ const current = get();+ if (+ (current.overlay?.id ?? 0) !== sessionId ||+ current.overlay?.isOpen === false+ )+ return;+ draftRevision += 1;+ if (current.hasDraft !== hasDraft) set({ hasDraft });+ },+ setMentionsOpen(sessionId, mentionsOpen) {+ if (+ (get().overlay?.id ?? 0) === sessionId &&+ get().overlay?.isOpen !== false &&+ get().mentionsOpen !== mentionsOpen+ )+ set({ mentionsOpen });+ },+ consumeSelection(overlay) {+ const current = get().overlay ?? overlay;+ if (+ current.id !== overlay.id ||+ !current.isOpen ||+ current.target.type !== "inline-comment"+ )+ return;+ set({+ overlay: {+ ...current,+ target: { ...current.target, type: "comments" },+ },+ });+ },+ },+ }));+}++export type CommentOverlayStore = ReturnType<typeof createCommentOverlayStore>;diff --git a/web/src/features/comments/validateCommentReferenceObject.ts b/web/src/features/comments/validateCommentReferenceObject.tsindex aa7cd82524..c3e36d38df 100644--- a/web/src/features/comments/validateCommentReferenceObject.ts+++ b/web/src/features/comments/validateCommentReferenceObject.ts@@ -6,6 +6,7 @@ import {import { type z } from "zod";import {getObservationById,+ getObservationByIdFromEventsTable,getTraceById,getTracesIdentifierForSession,} from "@langfuse/shared/src/server";@@ -22,9 +23,15 @@ export const validateCommentReferenceObject = async ({let commentTarget;switch (objectType) {case CommentObjectType.OBSERVATION: {+ const getObservation = (+ params: Parameters<typeof getObservationByIdFromEventsTable>[0],+ ) =>+ ctx.session?.user?.v4BetaEnabled === true+ ? getObservationByIdFromEventsTable(params)+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ getObservationById(params);try {- // eslint-disable-next-line @typescript-eslint/no-deprecated- commentTarget = await getObservationById({+ commentTarget = await getObservation({id: objectId,projectId,// objectStartTime is a performance hint: it bounds the lookup to its@@ -35,8 +42,7 @@ export const validateCommentReferenceObject = async ({});} catch (e) {if (!(e instanceof LangfuseNotFoundError) || !objectStartTime) throw e;- // eslint-disable-next-line @typescript-eslint/no-deprecated- commentTarget = await getObservationById({ id: objectId, projectId });+ commentTarget = await getObservation({ id: objectId, projectId });}break;}