diff --git a/apps/realtime/src/routes/http.ts b/apps/realtime/src/routes/http.ts index 152e8793e4e..cee13d21961 100644 --- a/apps/realtime/src/routes/http.ts +++ b/apps/realtime/src/routes/http.ts @@ -1,5 +1,9 @@ import type { IncomingMessage, ServerResponse } from 'http' -import { FILE_DOC_EVENTS, type FileDocInvalidated } from '@sim/realtime-protocol/file-doc' +import { + FILE_DOC_EVENTS, + type FileDocCommentsChanged, + type FileDocInvalidated, +} from '@sim/realtime-protocol/file-doc' import { fileDocAdmissionRoom, fileDocRoom, @@ -282,6 +286,23 @@ export function createHttpHandler(roomManager: IRoomManager, logger: Logger) { return } + if (req.method === 'POST' && req.url === '/api/file-doc/comments-changed') { + try { + const body = await readRequestBody(req) + const target = parseFileDocTarget(JSON.parse(body)) + if (!target) return sendError(res, 'Invalid file target', 400) + const payload: FileDocCommentsChanged = { fileId: target.fileId } + roomManager.io + .to([roomName(fileDocRoom(target)), fileDocAdmissionRoom(target)]) + .emit(FILE_DOC_EVENTS.COMMENTS_CHANGED, payload) + sendSuccess(res) + } catch (error) { + logger.error('Error relaying file comment change:', error) + sendError(res, 'Failed to relay comment change') + } + return + } + res.writeHead(404, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ error: 'Not found' })) } diff --git a/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/messages/[commentId]/route.ts b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/messages/[commentId]/route.ts new file mode 100644 index 00000000000..3a1a7ef365e --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/messages/[commentId]/route.ts @@ -0,0 +1,48 @@ +import { + deleteWorkspaceFileCommentContract, + editWorkspaceFileCommentContract, +} from '@/lib/api/contracts/workspace-file-comments' +import { defineInternalJsonRoute, internalSessionAuth } from '@/lib/api/server/routes' +import { + fileCommentRateLimits, + internalFileErrorPolicies, + toFileCommentThread, +} from '@/lib/workspace-files/api' +import { + deleteWorkspaceFileComment, + editWorkspaceFileComment, +} from '@/lib/workspace-files/application/file-comments' +import { fileOperations } from '@/lib/workspace-files/application/operations' + +export const PATCH = defineInternalJsonRoute({ + contract: editWorkspaceFileCommentContract, + auth: internalSessionAuth, + operation: fileOperations.changeComment, + rateLimit: fileCommentRateLimits.write, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params, body }) => ({ + fileId: params.fileId, + assertedWorkspaceId: params.id, + threadId: params.threadId, + commentId: params.commentId, + body: body.body, + }), + useCase: editWorkspaceFileComment, + present: ({ thread }) => ({ thread: toFileCommentThread(thread) }), +}) + +export const DELETE = defineInternalJsonRoute({ + contract: deleteWorkspaceFileCommentContract, + auth: internalSessionAuth, + operation: fileOperations.changeComment, + rateLimit: fileCommentRateLimits.write, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params }) => ({ + fileId: params.fileId, + assertedWorkspaceId: params.id, + threadId: params.threadId, + commentId: params.commentId, + }), + useCase: deleteWorkspaceFileComment, + present: ({ thread }) => ({ thread: thread ? toFileCommentThread(thread) : null }), +}) diff --git a/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/messages/route.ts b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/messages/route.ts new file mode 100644 index 00000000000..2bc3df2e82d --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/messages/route.ts @@ -0,0 +1,27 @@ +import { replyToWorkspaceFileCommentThreadContract } from '@/lib/api/contracts/workspace-file-comments' +import { defineInternalJsonRoute, internalSessionAuth } from '@/lib/api/server/routes' +import { + fileCommentRateLimits, + internalFileAnalytics, + internalFileErrorPolicies, + toFileCommentThread, +} from '@/lib/workspace-files/api' +import { replyToWorkspaceFileCommentThread } from '@/lib/workspace-files/application/file-comments' +import { fileOperations } from '@/lib/workspace-files/application/operations' + +export const POST = defineInternalJsonRoute({ + contract: replyToWorkspaceFileCommentThreadContract, + auth: internalSessionAuth, + operation: fileOperations.postComment, + rateLimit: fileCommentRateLimits.write, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params, body }) => ({ + fileId: params.fileId, + assertedWorkspaceId: params.id, + threadId: params.threadId, + body: body.body, + }), + useCase: replyToWorkspaceFileCommentThread, + onSuccess: internalFileAnalytics.commentReplied, + present: ({ thread }) => ({ thread: toFileCommentThread(thread) }), +}) diff --git a/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/route.ts b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/route.ts new file mode 100644 index 00000000000..b68c1444a13 --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/[threadId]/route.ts @@ -0,0 +1,27 @@ +import { resolveWorkspaceFileCommentThreadContract } from '@/lib/api/contracts/workspace-file-comments' +import { defineInternalJsonRoute, internalSessionAuth } from '@/lib/api/server/routes' +import { + fileCommentRateLimits, + internalFileAnalytics, + internalFileErrorPolicies, + toFileCommentThread, +} from '@/lib/workspace-files/api' +import { resolveWorkspaceFileCommentThread } from '@/lib/workspace-files/application/file-comments' +import { fileOperations } from '@/lib/workspace-files/application/operations' + +export const PATCH = defineInternalJsonRoute({ + contract: resolveWorkspaceFileCommentThreadContract, + auth: internalSessionAuth, + operation: fileOperations.resolveComment, + rateLimit: fileCommentRateLimits.write, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params, body }) => ({ + fileId: params.fileId, + assertedWorkspaceId: params.id, + threadId: params.threadId, + resolved: body.resolved, + }), + useCase: resolveWorkspaceFileCommentThread, + onSuccess: internalFileAnalytics.commentResolved, + present: ({ thread }) => ({ thread: toFileCommentThread(thread) }), +}) diff --git a/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/route.ts b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/route.ts new file mode 100644 index 00000000000..126b3288402 --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/files/[fileId]/comments/route.ts @@ -0,0 +1,44 @@ +import { + createWorkspaceFileCommentThreadContract, + listWorkspaceFileCommentsContract, +} from '@/lib/api/contracts/workspace-file-comments' +import { defineInternalJsonRoute, internalSessionAuth } from '@/lib/api/server/routes' +import { + fileCommentRateLimits, + internalFileAnalytics, + internalFileErrorPolicies, + toFileCommentThread, +} from '@/lib/workspace-files/api' +import { + createWorkspaceFileCommentThread, + listWorkspaceFileComments, +} from '@/lib/workspace-files/application/file-comments' +import { fileOperations } from '@/lib/workspace-files/application/operations' + +export const GET = defineInternalJsonRoute({ + contract: listWorkspaceFileCommentsContract, + auth: internalSessionAuth, + operation: fileOperations.listComments, + rateLimit: fileCommentRateLimits.read, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params }) => ({ fileId: params.fileId, assertedWorkspaceId: params.id }), + useCase: listWorkspaceFileComments, + present: ({ threads }) => ({ threads: threads.map(toFileCommentThread) }), +}) + +export const POST = defineInternalJsonRoute({ + contract: createWorkspaceFileCommentThreadContract, + auth: internalSessionAuth, + operation: fileOperations.postComment, + rateLimit: fileCommentRateLimits.write, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params, body }) => ({ + fileId: params.fileId, + assertedWorkspaceId: params.id, + anchor: body.anchor, + body: body.body, + }), + useCase: createWorkspaceFileCommentThread, + onSuccess: internalFileAnalytics.commentCreated, + present: ({ thread }) => ({ thread: toFileCommentThread(thread) }), +}) diff --git a/apps/sim/app/api/workspaces/[id]/files/[fileId]/mentions/route.ts b/apps/sim/app/api/workspaces/[id]/files/[fileId]/mentions/route.ts new file mode 100644 index 00000000000..7849e2afb46 --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/files/[fileId]/mentions/route.ts @@ -0,0 +1,26 @@ +import { notifyWorkspaceFileMentionContract } from '@/lib/api/contracts/workspace-file-comments' +import { defineInternalJsonRoute, internalSessionAuth } from '@/lib/api/server/routes' +import { + fileCommentRateLimits, + internalFileAnalytics, + internalFileErrorPolicies, +} from '@/lib/workspace-files/api' +import { notifyWorkspaceFileMention } from '@/lib/workspace-files/application/file-comments' +import { fileOperations } from '@/lib/workspace-files/application/operations' + +export const POST = defineInternalJsonRoute({ + contract: notifyWorkspaceFileMentionContract, + auth: internalSessionAuth, + operation: fileOperations.notifyMention, + rateLimit: fileCommentRateLimits.mention, + errorPolicy: internalFileErrorPolicies.concealResourceAuthorization, + mapInput: ({ params, body }) => ({ + fileId: params.fileId, + assertedWorkspaceId: params.id, + userId: body.userId, + excerpt: body.excerpt, + }), + useCase: notifyWorkspaceFileMention, + onSuccess: internalFileAnalytics.personMentioned, + present: () => ({ notified: true }), +}) diff --git a/apps/sim/app/workspace/[workspaceId]/components/presence/presence-avatars.tsx b/apps/sim/app/workspace/[workspaceId]/components/presence/presence-avatars.tsx index a817448356b..1be7e6ebb18 100644 --- a/apps/sim/app/workspace/[workspaceId]/components/presence/presence-avatars.tsx +++ b/apps/sim/app/workspace/[workspaceId]/components/presence/presence-avatars.tsx @@ -1,7 +1,7 @@ 'use client' -import { Avatar, AvatarFallback, AvatarImage, cn, Tooltip } from '@sim/emcn' -import { getUserColor } from '@/lib/workspaces/colors' +import { Avatar, AvatarFallback, cn, Tooltip } from '@sim/emcn' +import { UserAvatar } from '@/app/workspace/[workspaceId]/components/user-avatar/user-avatar' /** Minimal presence shape the avatar stack renders — shared by workflow and files. */ export interface PresenceAvatarUser { @@ -13,32 +13,20 @@ export interface PresenceAvatarUser { avatarUrl?: string | null } -interface UserAvatarProps { +interface PresenceAvatarProps { user: PresenceAvatarUser index: number } -/** - * A single collaborator avatar: their image, falling back to a colored circle - * with their initial. Wrapped in a name tooltip when the name is known. - */ -function UserAvatar({ user, index }: UserAvatarProps) { - const color = getUserColor(user.userId) - const initials = user.userName ? user.userName.charAt(0).toUpperCase() : '?' - +/** A single collaborator in the stack, wrapped in a name tooltip when the name is known. */ +function PresenceAvatar({ user, index }: PresenceAvatarProps) { const avatarElement = ( - - {user.avatarUrl && ( - - )} - - {initials} - - + ) if (user.userName) { @@ -106,7 +94,7 @@ export function PresenceAvatars({ )} {visibleUsers.map((user, index) => ( - + ))} ) diff --git a/apps/sim/app/workspace/[workspaceId]/components/user-avatar/user-avatar.tsx b/apps/sim/app/workspace/[workspaceId]/components/user-avatar/user-avatar.tsx new file mode 100644 index 00000000000..7bd81caa969 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/components/user-avatar/user-avatar.tsx @@ -0,0 +1,32 @@ +'use client' + +import type { ComponentProps } from 'react' +import { Avatar, AvatarFallback, AvatarImage } from '@sim/emcn' +import { getUserColor } from '@/lib/workspaces/colors' + +interface UserAvatarProps extends Omit, 'children'> { + userId: string + name?: string + image?: string | null + size?: 'xs' | 'sm' | 'md' +} + +/** + * A workspace member as they appear across the product: their profile photo, falling back to their + * initial on the color presence and cursors give them, so a person looks the same everywhere. + * Announced by the person's name whether or not the photo loads, and spreads the rest onto the + * avatar so it works as a tooltip or popover trigger. + */ +export function UserAvatar({ userId, name, image, size = 'xs', ...props }: UserAvatarProps) { + return ( + + {image && } + + {name ? name.charAt(0).toUpperCase() : '?'} + + + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-comments/comment-body.tsx b/apps/sim/app/workspace/[workspaceId]/files/components/file-comments/comment-body.tsx new file mode 100644 index 00000000000..e6b43dc582a --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-comments/comment-body.tsx @@ -0,0 +1,36 @@ +import type { ReactNode } from 'react' +import { parseCommentBody } from '@/lib/workspace-files/comments/format' + +interface CommentBodyProps { + body: string + /** Marks the viewer's own mentions so being tagged stands out. */ + currentUserId: string | null +} + +/** A comment's text, with each person mention shown as `@Name`. */ +export function CommentBody({ body, currentUserId }: CommentBodyProps) { + const parts: ReactNode[] = [] + let offset = 0 + for (const segment of parseCommentBody(body)) { + parts.push( + segment.kind === 'mention' ? ( + + @{segment.text} + + ) : ( + {segment.text} + ) + ) + offset += segment.text.length + 1 + } + return ( +

{parts}

+ ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-comments/comment-composer.tsx b/apps/sim/app/workspace/[workspaceId]/files/components/file-comments/comment-composer.tsx new file mode 100644 index 00000000000..3593721231f --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-comments/comment-composer.tsx @@ -0,0 +1,325 @@ +'use client' + +import { type KeyboardEvent, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { + Button, + ComposerActionButton, + chipFieldSurfaceClass, + chipFieldTextClass, + cn, +} from '@sim/emcn' +import { ArrowUp } from '@sim/emcn/icons' +import { + FILE_COMMENT_BODY_MAX_CHARS, + formatPersonMention, + parseCommentBody, +} from '@/lib/workspace-files/comments/format' +import { UserAvatar } from '@/app/workspace/[workspaceId]/components/user-avatar/user-avatar' +import { + SUGGESTION_ITEM_CLASS, + SUGGESTION_SCROLL_CLASS, + SUGGESTION_SURFACE_CLASS, +} from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/suggestion-menu-chrome' +import { useSuggestionKeyboard } from '@/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-suggestion-keyboard' +import type { WorkspaceMember } from '@/hooks/queries/workspace' + +/** Most people listed under an `@` at once; typing more of a name narrows the rest in. */ +const MAX_SUGGESTIONS = 6 +/** An `@` that starts a word, and what has been typed after it, right before the caret. */ +const MENTION_QUERY_RE = /(^|\s)@([^\s@]{0,40})$/ +/** Tallest the box grows while typing before it scrolls instead. */ +const MAX_INPUT_HEIGHT_PX = 160 + +interface MentionQuery { + /** Index of the `@` in the text. */ + start: number + query: string +} + +/** A person picked from the list, at the `@Name` it occupies in the composer's text. */ +interface PlacedMention { + start: number + name: string + userId: string +} + +function mentionEnd(mention: PlacedMention): number { + return mention.start + mention.name.length + 1 +} + +/** A stored body as the composer shows it: each mention becomes `@Name` at a known position. */ +function toDraft(body: string): { text: string; mentions: PlacedMention[] } { + let text = '' + const mentions: PlacedMention[] = [] + for (const segment of parseCommentBody(body)) { + if (segment.kind === 'mention') { + mentions.push({ start: text.length, name: segment.text, userId: segment.userId }) + text += `@${segment.text}` + } else { + text += segment.text + } + } + return { text, mentions } +} + +/** + * Carries mentions across an edit from `before` to `after`: those wholly before or after the + * changed span keep their place (shifted by the change in length), and any the edit touched are + * dropped, so retyping part of a name turns it back into plain text instead of a stale link. + */ +function carryMentions( + mentions: readonly PlacedMention[], + before: string, + after: string +): PlacedMention[] { + let prefix = 0 + const shortest = Math.min(before.length, after.length) + while (prefix < shortest && before[prefix] === after[prefix]) prefix++ + let suffix = 0 + while ( + suffix < shortest - prefix && + before[before.length - 1 - suffix] === after[after.length - 1 - suffix] + ) { + suffix++ + } + const changedEnd = before.length - suffix + const delta = after.length - before.length + return mentions.flatMap((mention) => { + if (mentionEnd(mention) <= prefix) return [mention] + if (mention.start >= changedEnd) return [{ ...mention, start: mention.start + delta }] + return [] + }) +} + +/** The composer's text as a stored body, with each placed `@Name` written as its mention link. */ +function toBody(text: string, mentions: readonly PlacedMention[]): string { + let body = text + for (const mention of [...mentions].sort((a, b) => b.start - a.start)) { + if (body.slice(mention.start, mentionEnd(mention)) !== `@${mention.name}`) continue + body = + body.slice(0, mention.start) + + formatPersonMention(mention.userId, mention.name) + + body.slice(mentionEnd(mention)) + } + return body.trim() +} + +function findMentionQuery(text: string, caret: number): MentionQuery | null { + const match = MENTION_QUERY_RE.exec(text.slice(0, caret)) + if (!match) return null + return { start: caret - match[2].length - 1, query: match[2] } +} + +interface CommentComposerProps { + members: readonly WorkspaceMember[] + placeholder: string + /** Names the send button for assistive tech, e.g. "Comment" or "Reply". */ + submitLabel: string + initialBody?: string + autoFocus?: boolean + isPending?: boolean + onSubmit: (body: string) => void + onCancel?: () => void + /** Receives the unsent body after every change, so a caller can restore it into a new composer. */ + onDraftChange?: (body: string) => void +} + +/** + * Writes a comment. Typing `@` lists the workspace's members; picking one inserts `@Name`, which is + * saved as a mention of that exact person (two members may share a name) and notifies them. + * One line that grows with the text: Enter sends, Shift-Enter starts a new line, Escape cancels. + * Read-only while sending, since the box clears or closes once the send lands. + */ +export function CommentComposer({ + members, + placeholder, + submitLabel, + initialBody, + autoFocus, + isPending = false, + onSubmit, + onCancel, + onDraftChange, +}: CommentComposerProps) { + const [initial] = useState(() => toDraft(initialBody ?? '')) + const [text, setText] = useState(initial.text) + const [mentions, setMentions] = useState(initial.mentions) + const [query, setQuery] = useState(null) + const textareaRef = useRef(null) + const listRef = useRef(null) + /** Where the caret goes once a picked mention is in the text; placed before any further typing. */ + const pendingCaretRef = useRef(null) + + useLayoutEffect(() => { + const caret = pendingCaretRef.current + if (caret === null) return + pendingCaretRef.current = null + textareaRef.current?.focus() + textareaRef.current?.setSelectionRange(caret, caret) + }) + + const [focusOnMount] = useState(autoFocus) + useLayoutEffect(() => { + if (focusOnMount) textareaRef.current?.focus() + }, [focusOnMount]) + + useLayoutEffect(() => { + const textarea = textareaRef.current + if (!textarea) return + textarea.style.height = 'auto' + textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_INPUT_HEIGHT_PX)}px` + }, [text]) + + const suggestions = useMemo(() => { + if (!query) return [] + const needle = query.query.toLowerCase() + return members + .filter((member) => member.name.toLowerCase().includes(needle)) + .slice(0, MAX_SUGGESTIONS) + }, [members, query]) + + const body = toBody(text, mentions) + const tooLong = body.length > FILE_COMMENT_BODY_MAX_CHARS + const canSubmit = body.length > 0 && !tooLong && !isPending + + const syncQuery = (value: string, caret: number) => setQuery(findMentionQuery(value, caret)) + + const update = (nextText: string, nextMentions: PlacedMention[]) => { + setText(nextText) + setMentions(nextMentions) + onDraftChange?.(toBody(nextText, nextMentions)) + } + + const pick = (member: WorkspaceMember) => { + if (!query) return + const caret = query.start + 1 + query.query.length + const inserted = `@${member.name} ` + const next = text.slice(0, query.start) + inserted + text.slice(caret) + update(next, [ + ...carryMentions(mentions, text, next), + { start: query.start, name: member.name, userId: member.userId }, + ]) + setQuery(null) + pendingCaretRef.current = query.start + inserted.length + } + + const submit = () => { + if (canSubmit) onSubmit(body) + } + + const keyboard = useSuggestionKeyboard(suggestions, pick, listRef) + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.nativeEvent.isComposing) return + if (suggestions.length > 0) { + if (keyboard.onKeyDown({ event: event.nativeEvent })) { + event.preventDefault() + return + } + if (event.key === 'Escape') { + event.preventDefault() + setQuery(null) + return + } + } + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault() + submit() + return + } + if (event.key === 'Escape' && onCancel) { + event.preventDefault() + onCancel() + } + } + + return ( +
+
+
+