feat(comments): add internal comments and author comment editing (#552)

* feat(comments): add internal comments and author comment editing

* chore(i18n): add Korean comment translations and update AGENTS.md i18n rule

* style(comments): refine visibility selector corner radius and align send button height

* fix(webui): avoid ResizeObserver loop when resizing file browser
This commit is contained in:
Yiling-J
2026-11-26 14:54:45 +08:00
committed by GitHub
parent 1066900c78
commit fee6f39828
43 changed files with 2751 additions and 301 deletions
@@ -0,0 +1,127 @@
import React from 'react'
import { Check, ChevronDown, Globe, Lock } from 'lucide-react'
import { m } from '@/ui/paraglide/messages.js'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
export interface CommentVisibilitySelectorProps {
isInternal: boolean
onChange: (isInternal: boolean) => void
disabled?: boolean
disabledTooltip?: string
align?: 'start' | 'center' | 'end'
side?: 'top' | 'bottom'
}
export const CommentVisibilitySelector: React.FC<CommentVisibilitySelectorProps> = ({
isInternal,
onChange,
disabled = false,
disabledTooltip,
align = 'end',
side = 'top',
}) => {
const pillClasses = `inline-flex h-7 items-center gap-1 rounded-md border px-2 text-xs font-medium transition-colors shrink-0 select-none ${
isInternal
? 'border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300'
: 'border-border bg-muted/40 text-muted-foreground hover:text-foreground hover:bg-muted/80'
} ${disabled ? 'opacity-70 cursor-not-allowed' : 'cursor-pointer'}`
const pillContent = (
<>
{isInternal ? <Lock className="w-3 h-3 shrink-0" /> : <Globe className="w-3 h-3 shrink-0" />}
<span>{isInternal ? m.internal_comment_label() : m.public_comment_label()}</span>
{!disabled && <ChevronDown className="w-3 h-3 shrink-0 opacity-70" />}
</>
)
if (disabled) {
const button = (
<button
type="button"
disabled
data-testid="comment-visibility-trigger"
className={pillClasses}
onClick={(e) => e.stopPropagation()}
>
{pillContent}
</button>
)
if (!disabledTooltip) return button
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex shrink-0">{button}</span>
</TooltipTrigger>
<TooltipContent side="top">
<p className="text-xs">{disabledTooltip}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
type="button"
data-testid="comment-visibility-trigger"
className={pillClasses}
onClick={(e) => e.stopPropagation()}
>
{pillContent}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
align={align}
side={side}
className="w-60"
onClick={(e) => e.stopPropagation()}
>
<DropdownMenuItem
data-testid="comment-visibility-public"
className="flex items-start gap-2.5 py-2 cursor-pointer"
onClick={(e) => {
e.stopPropagation()
onChange(false)
}}
>
<Globe className="w-4 h-4 mt-0.5 shrink-0 text-muted-foreground" />
<div className="flex-1 min-w-0">
<div className="text-xs font-medium text-foreground">{m.public_comment()}</div>
<div className="text-[11px] text-muted-foreground leading-snug">
{m.public_comment_description()}
</div>
</div>
{!isInternal && <Check className="w-4 h-4 mt-0.5 shrink-0 text-primary" />}
</DropdownMenuItem>
<DropdownMenuItem
data-testid="comment-visibility-internal"
className="flex items-start gap-2.5 py-2 cursor-pointer"
onClick={(e) => {
e.stopPropagation()
onChange(true)
}}
>
<Lock className="w-4 h-4 mt-0.5 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex-1 min-w-0">
<div className="text-xs font-medium text-foreground">{m.internal_comment()}</div>
<div className="text-[11px] text-muted-foreground leading-snug">
{m.internal_comment_description()}
</div>
</div>
{isInternal && <Check className="w-4 h-4 mt-0.5 shrink-0 text-primary" />}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -0,0 +1,59 @@
export const MENTION_CHIP_CLASS =
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
export function createMentionNode(user: { id: string; name: string }): HTMLSpanElement {
const mentionNode = document.createElement('span')
mentionNode.contentEditable = 'false'
mentionNode.dataset.type = 'mention'
mentionNode.dataset.id = user.id
mentionNode.className = MENTION_CHIP_CLASS
mentionNode.innerText = `@${user.name}`
return mentionNode
}
function serializeChildNodes(parent: Node): string {
let result = ''
parent.childNodes.forEach((node) => {
if (node.nodeType === Node.TEXT_NODE) {
result += node.textContent ?? ''
} else if (node.nodeType === Node.ELEMENT_NODE) {
const el = node as HTMLElement
if (el.dataset.type === 'mention') {
result += `<@${el.dataset.id}>`
} else if (el.tagName === 'BR') {
result += '\n'
} else if (el.tagName === 'DIV' || el.tagName === 'P') {
result += '\n' + serializeChildNodes(el)
} else {
result += serializeChildNodes(el)
}
}
})
return result
}
export function serializeEditableContent(editor: HTMLElement): string {
return serializeChildNodes(editor)
.replace(/\u00A0/g, ' ')
.trim()
}
export function hydrateEditableWithMentions(
editor: HTMLElement,
text: string,
resolveUserName: (userId: string) => string,
): void {
editor.innerHTML = ''
if (!text) return
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
for (const part of parts) {
if (!part) continue
if (/^<@[a-zA-Z0-9_-]+>$/.test(part)) {
const userId = part.slice(2, -1)
editor.appendChild(createMentionNode({ id: userId, name: resolveUserName(userId) }))
} else {
editor.appendChild(document.createTextNode(part))
}
}
}
@@ -21,6 +21,19 @@ vi.mock('@/ui/api/client', () => ({
},
},
},
projects: {
':projectId': {
attachments: {
$post: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
id: 'att-new-asset',
uploadUrl: 'https://upload.example.com/new.txt',
}),
}),
},
},
},
comments: {
':commentId': {
complete: {
@@ -39,6 +52,10 @@ vi.mock('@/ui/api/client', () => ({
json: async () => ({ success: true }),
}),
},
$patch: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ id: 'msg-edit', message: 'Updated text', isInternal: true }),
}),
$delete: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
@@ -98,6 +115,7 @@ describe('MessageCard component', () => {
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
@@ -158,6 +176,7 @@ describe('MessageCard component', () => {
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [
{
@@ -234,6 +253,7 @@ describe('MessageCard component', () => {
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [
{
@@ -262,4 +282,189 @@ describe('MessageCard component', () => {
fireEvent.click(partyBadge!)
expect(client.api.comments[':commentId'].reactions.$post).not.toHaveBeenCalled()
})
it('displays lock icon for internal comments and hides it for public comments', () => {
const baseMessage: CommentInfo = {
id: 'msg-internal',
assetId: 'asset-1',
message: 'Private review note',
annotations: null,
second: null,
creator: { id: 'u-1', name: 'Bob Reviewer' },
replies: [],
attachments: [],
mentions: [],
createdAt: '2026-08-20T10:30:00.000Z',
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: true,
completionLastChangedBy: null,
reactionCounts: [],
}
const { rerender } = render(
<MessageCard
teamId="team-1"
projectId="proj-1"
message={baseMessage}
getUser={() => ({ id: 'u-1', name: 'Bob Reviewer', role: 'reviewer' })}
onReply={vi.fn()}
/>,
{ wrapper: createWrapper() },
)
expect(screen.getByTestId('internal-comment-icon')).toBeDefined()
rerender(
<MessageCard
teamId="team-1"
projectId="proj-1"
message={{ ...baseMessage, isInternal: false }}
getUser={() => ({ id: 'u-1', name: 'Bob Reviewer', role: 'reviewer' })}
onReply={vi.fn()}
/>,
)
expect(screen.queryByTestId('internal-comment-icon')).toBeNull()
})
it('allows author to edit text (preserving mentions), remove timestamp, remove attachment, toggle internal, and save', async () => {
const mockMessage: CommentInfo = {
id: 'msg-edit',
assetId: 'asset-1',
message: 'Hey <@u-2> check this frame',
annotations: null,
second: 5,
creator: { id: 'u-1', name: 'Bob Reviewer' },
replies: [],
attachments: [
{
id: 'join-1',
assetId: 'att-asset-1',
url: 'https://example.com/spec.pdf',
proxyType: null,
},
{
id: 'join-2',
assetId: 'att-asset-2',
url: 'https://example.com/keep.png',
proxyType: 'image',
},
],
mentions: [{ id: 'u-2', name: 'Alice' }],
createdAt: '2026-08-20T10:30:00.000Z',
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
render(
<MessageCard
teamId="team-1"
projectId="proj-1"
message={mockMessage}
frameRate={30}
getUser={(id) =>
id === 'u-2'
? { id: 'u-2', name: 'Alice', role: 'editor' }
: { id, name: 'Unknown', role: 'unknown' }
}
onReply={vi.fn()}
/>,
{ wrapper: createWrapper() },
)
// Wait for team me query so author menu renders
const moreBtn = await screen.findByRole('button', { name: /more options/i })
fireEvent.pointerDown(moreBtn)
fireEvent.click(moreBtn)
const editMenuItem = await screen.findByText('Edit')
fireEvent.click(editMenuItem)
// Edit form should appear with hydrated mention chip, timestamp badge, and 2 attachments
expect(screen.getByTestId('comment-edit-form')).toBeDefined()
const mentionSpan = document.querySelector(
'[data-testid="edit-comment-input"] span[data-type="mention"]',
)
expect(mentionSpan?.getAttribute('data-id')).toBe('u-2')
expect(mentionSpan?.textContent).toBe('@Alice')
// Remove timestamp
fireEvent.click(screen.getByTestId('edit-comment-remove-timestamp'))
expect(screen.queryByTestId('edit-comment-timestamp')).toBeNull()
// Remove first attachment
fireEvent.click(screen.getByTestId('edit-remove-attachment-att-asset-1'))
expect(screen.getAllByTestId('edit-existing-attachment')).toHaveLength(1)
// Toggle Public -> Internal
const visTrigger = screen.getByTestId('comment-visibility-trigger')
fireEvent.pointerDown(visTrigger)
fireEvent.click(visTrigger)
fireEvent.click(await screen.findByTestId('comment-visibility-internal'))
// Save
fireEvent.click(screen.getByTestId('edit-comment-save'))
await waitFor(() => {
expect(client.api.comments[':commentId'].$patch).toHaveBeenCalledWith({
param: { commentId: 'msg-edit' },
json: {
message: 'Hey <@u-2> check this frame',
isInternal: true,
second: null,
attachmentIds: ['att-asset-2'],
},
})
})
})
it('does not show Edit menu item to non-author even if they are team owner', async () => {
vi.mocked(client.api.teams[':teamId'].me.$get).mockResolvedValueOnce({
ok: true,
json: async () => ({ id: 'u-owner', name: 'Owner', role: 'owner' }),
} as never)
const mockMessage: CommentInfo = {
id: 'msg-other',
assetId: 'asset-1',
message: 'Another user comment',
annotations: null,
second: null,
creator: { id: 'u-1', name: 'Bob Reviewer' },
replies: [],
attachments: [],
mentions: [],
createdAt: '2026-08-20T10:30:00.000Z',
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
render(
<MessageCard
teamId="team-1"
projectId="proj-1"
message={mockMessage}
getUser={() => ({ id: 'u-1', name: 'Bob Reviewer', role: 'reviewer' })}
onReply={vi.fn()}
/>,
{ wrapper: createWrapper() },
)
const moreBtn = await screen.findByRole('button', { name: /more options/i })
fireEvent.pointerDown(moreBtn)
fireEvent.click(moreBtn)
await screen.findByText('Delete')
expect(screen.queryByText('Edit')).toBeNull()
})
})
+264 -202
View File
@@ -20,7 +20,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/component
import type { CommentInfo, CommentReactionCount, UserInfo } from '@shumai/dtos'
import type { MemberInfo } from '@/ui/stores/members'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Download, FileText, MoreHorizontal, Smile, Trash2 } from 'lucide-react'
import { Download, FileText, Lock, MoreHorizontal, Pencil, Smile, Trash2 } from 'lucide-react'
import React from 'react'
import Markdown from 'react-markdown'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
@@ -33,11 +33,14 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/
import { AgentSessionLogsDialog } from '../agent/agent-session-logs-dialog'
import { isImageFileName } from '@/ui/lib/media'
import { EmojiPickerPopover } from '../ui/emoji-picker'
import { MessageEditForm } from './message-edit-form'
interface MessageCardProps {
teamId?: string
projectId?: string
message: CommentInfo
isReply?: boolean
parentIsInternal?: boolean
hasReplies?: boolean
isLastReply?: boolean
getUser: (id: string) => MemberInfo | UserInfo
@@ -186,8 +189,10 @@ function updateCommentTreeReactions(
export const MessageCard: React.FC<MessageCardProps> = ({
teamId,
projectId,
message: initialMessage,
isReply,
parentIsInternal,
hasReplies,
isLastReply,
getUser,
@@ -210,6 +215,7 @@ export const MessageCard: React.FC<MessageCardProps> = ({
const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...'
const [isLogsOpen, setIsLogsOpen] = React.useState(false)
const [isEditing, setIsEditing] = React.useState(false)
const [previewImage, setPreviewImage] = React.useState<{ url: string; name: string } | null>(null)
const { videoTimeDisplayMode } = useUiStore()
@@ -377,12 +383,17 @@ export const MessageCard: React.FC<MessageCardProps> = ({
},
})
const canEdit = React.useMemo(() => {
if (isReadOnly || !me || message.sessionId) return false
return message.creator?.id === me.id
}, [isReadOnly, me, message.creator?.id, message.sessionId])
const canDelete = React.useMemo(() => {
if (!me) return false
if (isReadOnly || !me) return false
if (me.role === 'owner') return true
if (message.creator?.id === me.id) return true
return false
}, [me, message.creator?.id])
}, [isReadOnly, me, message.creator?.id])
const renderFormattedMessage = (text: string) => {
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
@@ -410,7 +421,9 @@ export const MessageCard: React.FC<MessageCardProps> = ({
return (
<div
onClick={onSelect}
onClick={() => {
if (!isEditing) onSelect?.()
}}
className={`relative flex gap-4 ${isReply ? 'mt-[-1px]' : 'mt-3'} mr-3 group p-3 py-4 border transition-all duration-200 cursor-pointer ${
isReply
? isLastReply
@@ -458,8 +471,26 @@ export const MessageCard: React.FC<MessageCardProps> = ({
minute: '2-digit',
})}
</span>
{message.isInternal && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span
className="inline-flex items-center text-muted-foreground"
data-testid="internal-comment-icon"
aria-label={m.internal_comment_tooltip()}
>
<Lock className="w-3.5 h-3.5" />
</span>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">{m.internal_comment_tooltip()}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
{canDelete && (
{(canEdit || canDelete) && !isEditing && (
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
@@ -468,231 +499,262 @@ export const MessageCard: React.FC<MessageCardProps> = ({
variant="ghost"
className="h-6 w-6 cursor-pointer"
onClick={(e) => e.stopPropagation()}
aria-label={m.more_options()}
>
<MoreHorizontal className="h-4 w-4 text-foreground/70" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer"
onClick={(e) => {
e.stopPropagation()
setIsDeleteDialogOpen(true)
}}
>
<Trash2 className="mr-2 h-4 w-4" />
<span>{m.delete()}</span>
</DropdownMenuItem>
{canEdit && (
<DropdownMenuItem
className="cursor-pointer"
onClick={(e) => {
e.stopPropagation()
setIsEditing(true)
}}
>
<Pencil className="mr-2 h-4 w-4" />
<span>{m.edit()}</span>
</DropdownMenuItem>
)}
{canDelete && (
<DropdownMenuItem
className="text-destructive focus:text-destructive cursor-pointer"
onClick={(e) => {
e.stopPropagation()
setIsDeleteDialogOpen(true)
}}
>
<Trash2 className="mr-2 h-4 w-4" />
<span>{m.delete()}</span>
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
<div className="flow-root mt-1">
{message.second !== null && message.second !== undefined && frameRate && (
<div className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-mono font-bold flex items-center gap-1">
{displayTime}
</div>
)}
{hasDrawInfo && (
<div
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-bold flex items-center gap-1"
title="Contains drawing annotations"
>
<DrawAnnotation className="w-3.5 h-3.5" />
</div>
)}
{showSkeleton ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<span className="text-xs text-muted-foreground animate-pulse">{loadingText}</span>
</div>
) : message.sessionId ? (
<div className="text-sm leading-[1.8] prose prose-sm dark:prose-invert max-w-none break-words">
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
</div>
) : (
<div className="text-sm leading-[1.8] whitespace-pre-wrap break-words text-wrap break-all">
{renderFormattedMessage(message.message!)}
</div>
)}
</div>
{/* Attachments */}
{message.attachments && message.attachments.length > 0 && (
<div className="flex flex-col gap-1.5 mt-3 w-full max-w-full overflow-hidden">
{message.attachments.map((att) => {
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
const name = decodeURIComponent(rawName)
const isImage = isImageFileName(name)
return (
<div
key={att.id}
className={`group relative flex items-center w-full max-w-full rounded-lg border border-border bg-card hover:bg-muted/40 transition-colors overflow-hidden ${
isImage ? 'h-18 p-1.5 gap-2.5 cursor-pointer' : 'h-9 px-2.5 gap-2.5'
}`}
onClick={() => {
if (isImage) {
setPreviewImage({ url: att.url, name })
} else {
window.open(att.url, '_blank', 'noreferrer')
}
}}
>
{isImage ? (
<div className="h-full aspect-square rounded-md overflow-hidden bg-muted/40 shrink-0">
<img
src={att.url}
alt={name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
/>
</div>
) : (
<FileText className="w-4 h-4 text-muted-foreground shrink-0" />
)}
<div className="min-w-0 flex-1 overflow-hidden">
<p
className="text-xs font-medium text-foreground truncate block w-full"
title={name}
>
{name}
</p>
</div>
<a
href={att.url}
target="_blank"
rel="noreferrer"
download={name}
className="p-1 text-muted-foreground hover:text-foreground shrink-0 rounded-md hover:bg-muted transition-colors opacity-0 group-hover:opacity-100"
onClick={(e) => e.stopPropagation()}
title={m.download()}
>
<Download className="w-3.5 h-3.5" />
</a>
{isEditing ? (
<MessageEditForm
projectId={projectId}
teamId={teamId}
message={message}
parentIsInternal={parentIsInternal}
getUser={getUser}
displayTime={displayTime}
hasDrawInfo={hasDrawInfo}
onCancel={() => setIsEditing(false)}
onSaved={() => setIsEditing(false)}
/>
) : (
<>
<div className="flow-root mt-1">
{message.second !== null && message.second !== undefined && frameRate && (
<div className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-mono font-bold flex items-center gap-1">
{displayTime}
</div>
)
})}
</div>
)}
)}
{/* Agent Footer */}
{message.sessionId && (
<div className="mt-3 pt-2 border-t border-foreground/5 flex items-center justify-between text-xs text-muted-foreground/60">
<span className="flex items-center gap-1.5 font-medium text-muted-foreground/80">
Created by Agent
</span>
{isAdmin && (
<Button
variant="outline"
size="xs"
onClick={() => setIsLogsOpen(true)}
className="cursor-pointer border-violet-500/20 text-violet-600 dark:text-violet-400 hover:bg-violet-500/10 hover:text-violet-700 hover:border-violet-500/30 font-semibold"
>
Logs
</Button>
{hasDrawInfo && (
<div
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-bold flex items-center gap-1"
title="Contains drawing annotations"
>
<DrawAnnotation className="w-3.5 h-3.5" />
</div>
)}
{showSkeleton ? (
<div className="space-y-2">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<span className="text-xs text-muted-foreground animate-pulse">{loadingText}</span>
</div>
) : message.sessionId ? (
<div className="text-sm leading-[1.8] prose prose-sm dark:prose-invert max-w-none break-words">
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
</div>
) : (
<div className="text-sm leading-[1.8] whitespace-pre-wrap break-words text-wrap break-all">
{renderFormattedMessage(message.message!)}
</div>
)}
</div>
{/* Attachments */}
{message.attachments && message.attachments.length > 0 && (
<div className="flex flex-col gap-1.5 mt-3 w-full max-w-full overflow-hidden">
{message.attachments.map((att) => {
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
const name = decodeURIComponent(rawName)
const isImage = isImageFileName(name)
return (
<div
key={att.id}
className={`group relative flex items-center w-full max-w-full rounded-lg border border-border bg-card hover:bg-muted/40 transition-colors overflow-hidden ${
isImage ? 'h-18 p-1.5 gap-2.5 cursor-pointer' : 'h-9 px-2.5 gap-2.5'
}`}
onClick={() => {
if (isImage) {
setPreviewImage({ url: att.url, name })
} else {
window.open(att.url, '_blank', 'noreferrer')
}
}}
>
{isImage ? (
<div className="h-full aspect-square rounded-md overflow-hidden bg-muted/40 shrink-0">
<img
src={att.url}
alt={name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
/>
</div>
) : (
<FileText className="w-4 h-4 text-muted-foreground shrink-0" />
)}
<div className="min-w-0 flex-1 overflow-hidden">
<p
className="text-xs font-medium text-foreground truncate block w-full"
title={name}
>
{name}
</p>
</div>
<a
href={att.url}
target="_blank"
rel="noreferrer"
download={name}
className="p-1 text-muted-foreground hover:text-foreground shrink-0 rounded-md hover:bg-muted transition-colors opacity-0 group-hover:opacity-100"
onClick={(e) => e.stopPropagation()}
title={m.download()}
>
<Download className="w-3.5 h-3.5" />
</a>
</div>
)
})}
</div>
)}
</div>
)}
{/* Reactions */}
{message.reactionCounts && message.reactionCounts.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 mt-2">
{message.reactionCounts.map((reaction) => {
const tooltipText = getReactionTooltip(reaction)
return (
<TooltipProvider key={reaction.code}>
{/* Agent Footer */}
{message.sessionId && (
<div className="mt-3 pt-2 border-t border-foreground/5 flex items-center justify-between text-xs text-muted-foreground/60">
<span className="flex items-center gap-1.5 font-medium text-muted-foreground/80">
Created by Agent
</span>
{isAdmin && (
<Button
variant="outline"
size="xs"
onClick={() => setIsLogsOpen(true)}
className="cursor-pointer border-violet-500/20 text-violet-600 dark:text-violet-400 hover:bg-violet-500/10 hover:text-violet-700 hover:border-violet-500/30 font-semibold"
>
Logs
</Button>
)}
</div>
)}
{/* Reactions */}
{message.reactionCounts && message.reactionCounts.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 mt-2">
{message.reactionCounts.map((reaction) => {
const tooltipText = getReactionTooltip(reaction)
return (
<TooltipProvider key={reaction.code}>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
disabled={isReadOnly}
onClick={(e) => {
e.stopPropagation()
handleToggleReaction(reaction.code)
}}
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-colors select-none ${
isReadOnly ? 'cursor-default' : 'cursor-pointer'
} ${
reaction.requestingUserReacted
? 'border-primary/40 bg-primary/10 font-medium'
: 'border-border/60 bg-muted/40 hover:bg-muted'
}`}
>
<span className="text-sm leading-none">{reaction.code}</span>
<span className="text-xs font-semibold text-foreground">
{reaction.count}
</span>
</button>
</TooltipTrigger>
<TooltipContent>{tooltipText}</TooltipContent>
</Tooltip>
</TooltipProvider>
)
})}
</div>
)}
{/* Actions */}
<div className="mt-2 flex items-center justify-between w-full">
<button
onClick={handleReply}
className="text-xs font-medium text-gray-500 hover:text-blue-600 flex items-center gap-1 cursor-pointer"
>
{m.reply()}
</button>
<div className="flex items-center gap-1">
{!isReadOnly && (
<EmojiPickerPopover
onEmojiSelect={(emoji) => handleToggleReaction(emoji)}
align="end"
side="top"
>
<button
type="button"
onClick={(e) => e.stopPropagation()}
className="flex items-center justify-center p-1 rounded-full text-gray-400 hover:text-foreground hover:bg-muted/80 transition-colors cursor-pointer"
title={m.add_reaction()}
>
<Smile className="w-5 h-5" />
</button>
</EmojiPickerPopover>
)}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
disabled={isReadOnly}
onClick={(e) => {
e.stopPropagation()
handleToggleReaction(reaction.code)
toggleComplete()
}}
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-colors select-none ${
isReadOnly ? 'cursor-default' : 'cursor-pointer'
} ${
reaction.requestingUserReacted
? 'border-primary/40 bg-primary/10 font-medium'
: 'border-border/60 bg-muted/40 hover:bg-muted'
className={`flex items-center justify-center p-1 rounded-full transition-colors cursor-pointer ${
message.isCompleted
? 'text-green-500 hover:text-green-600 hover:bg-green-500/10'
: 'text-gray-400 hover:text-green-500 hover:bg-green-500/10'
}`}
>
<span className="text-sm leading-none">{reaction.code}</span>
<span className="text-xs font-semibold text-foreground">
{reaction.count}
</span>
{message.isCompleted ? (
<FilledCircleCheck className="w-5 h-5" />
) : (
<UnfilledCircleCheck className="w-5 h-5" />
)}
</button>
</TooltipTrigger>
<TooltipContent>{tooltipText}</TooltipContent>
<TooltipContent>
{message.isCompleted ? m.mark_as_incomplete() : m.mark_as_complete()}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
})}
</div>
</div>
</div>
</>
)}
{/* Actions */}
<div className="mt-2 flex items-center justify-between w-full">
<button
onClick={handleReply}
className="text-xs font-medium text-gray-500 hover:text-blue-600 flex items-center gap-1 cursor-pointer"
>
{m.reply()}
</button>
<div className="flex items-center gap-1">
{!isReadOnly && (
<EmojiPickerPopover
onEmojiSelect={(emoji) => handleToggleReaction(emoji)}
align="end"
side="top"
>
<button
type="button"
onClick={(e) => e.stopPropagation()}
className="flex items-center justify-center p-1 rounded-full text-gray-400 hover:text-foreground hover:bg-muted/80 transition-colors cursor-pointer"
title={m.add_reaction()}
>
<Smile className="w-5 h-5" />
</button>
</EmojiPickerPopover>
)}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<button
onClick={(e) => {
e.stopPropagation()
toggleComplete()
}}
className={`flex items-center justify-center p-1 rounded-full transition-colors cursor-pointer ${
message.isCompleted
? 'text-green-500 hover:text-green-600 hover:bg-green-500/10'
: 'text-gray-400 hover:text-green-500 hover:bg-green-500/10'
}`}
>
{message.isCompleted ? (
<FilledCircleCheck className="w-5 h-5" />
) : (
<UnfilledCircleCheck className="w-5 h-5" />
)}
</button>
</TooltipTrigger>
<TooltipContent>
{message.isCompleted ? m.mark_as_incomplete() : m.mark_as_complete()}
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</div>
</div>
{/* Logs Dialog */}
@@ -0,0 +1,644 @@
import React, { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type {
AttachmentInfo,
CommentInfo,
PostAttachmentRequest,
PostAttachmentResponse,
UserInfo,
} from '@shumai/dtos'
import { FileIcon, FileText, Paperclip, XIcon } from 'lucide-react'
import { toast } from 'sonner'
import { client } from '@/ui/api/client'
import { isImageFileName } from '@/ui/lib/media'
import { m } from '@/ui/paraglide/messages.js'
import { useMemberStore, type MemberInfo } from '@/ui/stores/members'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
import { Button } from '../ui/button'
import { DrawAnnotation } from '../ui/icons'
import { ProgressCircle } from '../ui/progress-circle'
import { Skeleton } from '../ui/skeleton'
import { CommentVisibilitySelector } from './comment-visibility-selector'
import {
createMentionNode,
hydrateEditableWithMentions,
serializeEditableContent,
} from './mention-utils'
import type { UploadingFile } from './message-input'
export interface MessageEditFormProps {
projectId?: string
teamId?: string
message: CommentInfo
parentIsInternal?: boolean
getUser: (id: string) => MemberInfo | UserInfo
displayTime: string
hasDrawInfo: boolean
onCancel: () => void
onSaved: () => void
}
type MentionEntity = { type: 'user'; data: MemberInfo }
export const MessageEditForm: React.FC<MessageEditFormProps> = ({
projectId,
teamId: propTeamId,
message,
parentIsInternal = false,
getUser,
displayTime,
hasDrawInfo,
onCancel,
onSaved,
}) => {
const queryClient = useQueryClient()
const editorRef = useRef<HTMLDivElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const mentionRangeRef = useRef<Range | null>(null)
const mentionListRef = useRef<HTMLDivElement>(null)
const [editedIsInternal, setEditedIsInternal] = useState<boolean>(
parentIsInternal ? true : Boolean(message.isInternal),
)
const [editedSecond, setEditedSecond] = useState<number | null>(message.second ?? null)
const [keptAttachments, setKeptAttachments] = useState<AttachmentInfo[]>(
() => message.attachments ?? [],
)
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
const [hasText, setHasText] = useState<boolean>(() => Boolean((message.message ?? '').trim()))
const [showMentionList, setShowMentionList] = useState(false)
const [mentionQuery, setMentionQuery] = useState('')
const [highlightedIndex, setHighlightedIndex] = useState(0)
const { teamId: storeTeamId, ensureTeamIdForProject } = useTeamContextStore()
const effectiveTeamId = propTeamId || storeTeamId
const {
members: storeMembers,
loading: membersLoading,
fetchMembers,
fetchProjectMembers,
} = useMemberStore()
useEffect(() => {
if (projectId && !effectiveTeamId) {
ensureTeamIdForProject(projectId)
}
}, [projectId, effectiveTeamId, ensureTeamIdForProject])
// Hydrate editor once on mount so background comment polling never overwrites draft edits.
useEffect(() => {
const editor = editorRef.current
if (!editor) return
const resolveUserName = (userId: string) => {
const fromMentions = message.mentions?.find((u) => u.id === userId)
if (fromMentions?.name) return fromMentions.name
const fromStore = getUser(userId)
return fromStore?.name || 'Unknown'
}
hydrateEditableWithMentions(editor, message.message ?? '', resolveUserName)
setHasText(Boolean(serializeEditableContent(editor)))
editor.focus()
const range = document.createRange()
const sel = window.getSelection()
range.selectNodeContents(editor)
range.collapse(false)
sel?.removeAllRanges()
sel?.addRange(range)
}, [])
const { mutateAsync: uploadAttachment } = useMutation({
mutationFn: async ({
targetProjectId,
data,
}: {
targetProjectId: string
data: PostAttachmentRequest
}) => {
const res = await client.api.projects[':projectId'].attachments.$post({
param: { projectId: targetProjectId },
json: data,
})
if (!res.ok) throw new Error('Failed to create attachment')
return (await res.json()) as PostAttachmentResponse
},
})
const { mutate: updateComment, isPending: isSaving } = useMutation({
mutationFn: async (payload: {
message: string
isInternal: boolean
second: number | null
attachmentIds: string[]
}) => {
const res = await client.api.comments[':commentId'].$patch({
param: { commentId: message.id },
json: payload,
})
if (!res.ok) throw new Error('Failed to update comment')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
predicate: (query) => query.queryKey.includes('comments'),
})
onSaved()
},
onError: () => {
toast.error(m.failed_to_update_comment())
},
})
const filteredEntities: MentionEntity[] = storeMembers
.filter((u) => u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()))
.map((u) => ({ type: 'user' as const, data: u }))
useEffect(() => {
setHighlightedIndex(0)
}, [mentionQuery, showMentionList])
useEffect(() => {
mentionListRef.current
?.querySelector<HTMLElement>(`[data-index="${highlightedIndex}"]`)
?.scrollIntoView({ block: 'nearest' })
}, [highlightedIndex])
const getInitials = (name: string) =>
name
.split(' ')
.map((n) => n[0])
.slice(0, 2)
.join('')
.toUpperCase()
const handleInput = () => {
if (!editorRef.current) return
setHasText(Boolean(serializeEditableContent(editorRef.current)))
const sel = window.getSelection()
if (!sel || sel.rangeCount === 0) return
const range = sel.getRangeAt(0)
const node = range.startContainer
const offset = range.startOffset
if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.textContent || ''
const textBeforeCursor = textContent.slice(0, offset)
const lastAtPos = textBeforeCursor.lastIndexOf('@')
if (lastAtPos !== -1) {
const isStartOfLine = lastAtPos === 0
const charBeforeAt = textBeforeCursor[lastAtPos - 1]
const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt)
if (hasSpaceBefore) {
const query = textBeforeCursor.slice(lastAtPos + 1)
if (!/\s/.test(query)) {
setMentionQuery(query)
setShowMentionList(true)
if (projectId) {
fetchProjectMembers(projectId, true, true)
} else if (effectiveTeamId) {
fetchMembers(effectiveTeamId, true, true)
}
const mentionRange = document.createRange()
mentionRange.setStart(node, lastAtPos)
mentionRange.setEnd(node, offset)
mentionRangeRef.current = mentionRange
return
}
}
}
}
setShowMentionList(false)
mentionRangeRef.current = null
}
const handleSelectEntity = (entity: MentionEntity) => {
if (!mentionRangeRef.current || !editorRef.current) return
const range = mentionRangeRef.current
range.deleteContents()
const mentionNode = createMentionNode({ id: entity.data.id, name: entity.data.name })
range.insertNode(mentionNode)
const spaceNode = document.createTextNode('\u00A0')
mentionNode.after(spaceNode)
const newRange = document.createRange()
const sel = window.getSelection()
newRange.setStartAfter(spaceNode)
newRange.collapse(true)
sel?.removeAllRanges()
sel?.addRange(newRange)
setShowMentionList(false)
mentionRangeRef.current = null
setHasText(true)
editorRef.current.focus()
}
const handlePaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
e.preventDefault()
const text = e.clipboardData.getData('text/plain')
if (!text) return
const success =
typeof document.execCommand === 'function' &&
document.queryCommandSupported?.('insertText') &&
document.execCommand('insertText', false, text)
if (!success) {
const sel = window.getSelection()
if (sel && sel.rangeCount > 0) {
const range = sel.getRangeAt(0)
range.deleteContents()
const textNode = document.createTextNode(text)
range.insertNode(textNode)
range.setStartAfter(textNode)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
} else if (editorRef.current) {
editorRef.current.innerText += text
}
}
handleInput()
}
const handleFileSelect = useCallback(
async (e: ChangeEvent<HTMLInputElement>) => {
if (!e.target.files || !projectId) return
const newFiles = Array.from(e.target.files)
for (const file of newFiles) {
const tempId = `${Date.now()}-${Math.random()}-${file.name}`
setUploadingFiles((prev) => [...prev, { id: tempId, file, progress: 0 }])
try {
const data = await uploadAttachment({
targetProjectId: projectId,
data: {
fileName: file.name,
contentType: file.type,
size: file.size,
},
})
if (data.uploadUrl && data.id) {
await fetch(data.uploadUrl, {
method: 'PUT',
body: file,
headers: {
'Content-Type': file.type,
},
})
setUploadingFiles((prev) =>
prev.map((uf) =>
uf.id === tempId ? { ...uf, progress: 100, attachmentId: data.id } : uf,
),
)
}
} catch (error) {
setUploadingFiles((prev) =>
prev.map((uf) =>
uf.id === tempId
? {
...uf,
error: error instanceof Error ? error.message : 'Upload failed',
}
: uf,
),
)
}
}
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
},
[projectId, uploadAttachment],
)
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
const uploadedAttachmentIds = uploadingFiles
.map((f) => f.attachmentId)
.filter((id): id is string => Boolean(id))
const effectiveIsInternal = parentIsInternal ? true : editedIsInternal
const canSave =
!isSaving &&
!isUploading &&
(hasText || keptAttachments.length > 0 || uploadedAttachmentIds.length > 0 || hasDrawInfo)
const handleSave = () => {
if (!editorRef.current || !canSave) return
const serialized = serializeEditableContent(editorRef.current)
const attachmentIds = [...keptAttachments.map((att) => att.assetId), ...uploadedAttachmentIds]
if (!serialized && attachmentIds.length === 0 && !hasDrawInfo) return
updateComment({
message: serialized,
isInternal: effectiveIsInternal,
second: editedSecond,
attachmentIds,
})
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.nativeEvent.isComposing) return
if (showMentionList && filteredEntities.length > 0) {
if (e.key === 'ArrowUp') {
e.preventDefault()
setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredEntities.length - 1))
return
}
if (e.key === 'ArrowDown') {
e.preventDefault()
setHighlightedIndex((prev) => (prev < filteredEntities.length - 1 ? prev + 1 : 0))
return
}
if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault()
handleSelectEntity(filteredEntities[highlightedIndex])
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowMentionList(false)
return
}
}
if (e.key === 'Escape') {
e.preventDefault()
onCancel()
return
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSave()
}
}
return (
<div
className="relative mt-1.5 flex flex-col gap-2"
data-testid="comment-edit-form"
onClick={(e) => e.stopPropagation()}
>
{/* Mention dropdown */}
{showMentionList && (membersLoading || filteredEntities.length > 0) && (
<div
onMouseDown={(e) => e.preventDefault()}
className="absolute bottom-full left-0 mb-2 w-60 rounded-xl shadow-lg border border-border overflow-hidden z-30 bg-popover text-popover-foreground"
>
<div ref={mentionListRef} className="max-h-48 overflow-y-auto">
{membersLoading ? (
<div className="p-2 space-y-2 animate-pulse">
<div className="flex items-center gap-2 px-2 py-1">
<Skeleton className="w-6 h-6 rounded-full" />
<Skeleton className="h-4 w-28" />
</div>
</div>
) : (
filteredEntities.map((item, index) => (
<button
type="button"
key={item.data.id}
data-index={index}
onMouseDown={(e) => e.preventDefault()}
onClick={() => handleSelectEntity(item)}
onMouseEnter={() => setHighlightedIndex(index)}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left cursor-pointer ${
index === highlightedIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
}`}
>
<Avatar className="w-6 h-6">
{item.data.image && (
<AvatarImage
src={item.data.image}
alt={item.data.name}
className="object-cover"
/>
)}
<AvatarFallback className="text-[10px] bg-purple-400 text-black font-semibold">
{getInitials(item.data.name)}
</AvatarFallback>
</Avatar>
<span className="text-sm truncate">{item.data.name}</span>
</button>
))
)}
</div>
</div>
)}
{/* Timestamp & Draw badges */}
{((editedSecond !== null && displayTime) || hasDrawInfo) && (
<div className="flex flex-wrap items-center gap-1.5">
{editedSecond !== null && displayTime && (
<div
data-testid="edit-comment-timestamp"
className="inline-flex items-center gap-1 select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 pl-2 pr-1 py-0.5 rounded-sm text-xs leading-none font-mono font-bold"
>
<span>{displayTime}</span>
<button
type="button"
onClick={() => setEditedSecond(null)}
className="p-0.5 rounded hover:bg-blue-200/70 dark:hover:bg-blue-800/70 cursor-pointer"
title={m.remove_timestamp()}
aria-label={m.remove_timestamp()}
data-testid="edit-comment-remove-timestamp"
>
<XIcon className="w-3 h-3" />
</button>
</div>
)}
{hasDrawInfo && (
<div
className="inline-flex items-center bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-0.5 rounded-sm text-xs leading-none font-bold"
title={m.contains_drawing_annotations()}
>
<DrawAnnotation className="w-3.5 h-3.5" />
</div>
)}
</div>
)}
{/* Editable text box */}
<div
ref={editorRef}
contentEditable={!isSaving}
suppressContentEditableWarning
onInput={handleInput}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
data-testid="edit-comment-input"
className="w-full min-h-[56px] max-h-48 overflow-y-auto rounded-lg border border-border bg-background px-2.5 py-2 text-sm leading-relaxed focus:outline-none focus:ring-1 focus:ring-ring whitespace-pre-wrap break-words"
/>
{/* Existing & Newly Uploaded Attachments */}
{(keptAttachments.length > 0 || uploadingFiles.length > 0) && (
<div className="flex flex-col gap-1.5 w-full max-w-full overflow-hidden">
{keptAttachments.map((att) => {
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
const name = decodeURIComponent(rawName)
const isImage = isImageFileName(name)
return (
<div
key={att.id}
data-testid="edit-existing-attachment"
className="flex items-center gap-2 rounded-lg border border-border bg-card px-2 py-1.5"
>
{isImage ? (
<img
src={att.url}
alt={name}
className="w-8 h-8 rounded object-cover shrink-0 bg-muted/40"
/>
) : (
<FileText className="w-4 h-4 text-muted-foreground shrink-0" />
)}
<span className="text-xs font-medium text-foreground truncate flex-1 min-w-0">
{name}
</span>
<button
type="button"
onClick={() =>
setKeptAttachments((prev) => prev.filter((item) => item.id !== att.id))
}
className="p-1 text-muted-foreground hover:text-destructive rounded hover:bg-muted transition-colors cursor-pointer shrink-0"
aria-label={`${m.delete()} ${name}`}
data-testid={`edit-remove-attachment-${att.assetId}`}
>
<XIcon className="w-3.5 h-3.5" />
</button>
</div>
)
})}
{uploadingFiles.map((upload) => (
<div
key={upload.id}
data-testid="edit-new-attachment"
className="flex items-center gap-2 rounded-lg border border-border bg-card px-2 py-1.5"
>
{upload.file.type.startsWith('image/') ? (
<div className="relative w-8 h-8 rounded overflow-hidden shrink-0 bg-muted/40">
<img
src={URL.createObjectURL(upload.file)}
alt={upload.file.name}
className={`w-full h-full object-cover ${!upload.attachmentId ? 'opacity-50' : ''}`}
/>
{!upload.attachmentId && !upload.error && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40">
<ProgressCircle progress={upload.progress} className="w-5 h-5" />
</div>
)}
</div>
) : (
<FileIcon className="w-4 h-4 text-muted-foreground shrink-0" />
)}
<div className="flex-1 min-w-0">
<span className="text-xs font-medium text-foreground truncate block">
{upload.file.name}
</span>
{upload.error && (
<span className="text-[10px] text-destructive block truncate">
{upload.error}
</span>
)}
</div>
<button
type="button"
onClick={() =>
setUploadingFiles((prev) => prev.filter((item) => item.id !== upload.id))
}
className="p-1 text-muted-foreground hover:text-destructive rounded hover:bg-muted transition-colors cursor-pointer shrink-0"
aria-label={`${m.delete()} ${upload.file.name}`}
>
<XIcon className="w-3.5 h-3.5" />
</button>
</div>
))}
</div>
)}
{/* Action bar: attach + visibility on left, cancel + save on right */}
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
<div className="flex items-center gap-1.5">
{projectId && (
<>
<input
type="file"
ref={fileInputRef}
className="hidden"
multiple
onChange={handleFileSelect}
data-testid="edit-comment-file-input"
/>
<Button
type="button"
variant="ghost"
size="icon-xs"
className="h-7 w-7 rounded-full cursor-pointer"
onClick={() => fileInputRef.current?.click()}
title={m.attach_files()}
aria-label={m.attach_files()}
>
<Paperclip className="w-3.5 h-3.5" />
</Button>
</>
)}
<CommentVisibilitySelector
isInternal={effectiveIsInternal}
onChange={setEditedIsInternal}
disabled={parentIsInternal}
disabledTooltip={m.internal_reply_locked_tooltip()}
align="start"
side="bottom"
/>
</div>
<div className="flex items-center gap-1.5">
<Button
type="button"
variant="ghost"
size="xs"
disabled={isSaving}
onClick={onCancel}
className="cursor-pointer"
>
{m.cancel()}
</Button>
<Button
type="button"
size="xs"
disabled={!canSave}
onClick={handleSave}
className="cursor-pointer"
data-testid="edit-comment-save"
>
{m.save()}
</Button>
</div>
</div>
</div>
)
}
@@ -44,6 +44,7 @@ describe('ChatInput auto-mention on reply', () => {
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
@@ -89,6 +90,7 @@ describe('ChatInput auto-mention on reply', () => {
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
@@ -124,6 +126,7 @@ describe('ChatInput auto-mention on reply', () => {
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
@@ -142,6 +145,7 @@ describe('ChatInput auto-mention on reply', () => {
updatedAt: '2026-08-20T10:31:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
}
@@ -164,4 +168,110 @@ describe('ChatInput auto-mention on reply', () => {
expect(mentionSpans).toHaveLength(2)
expect(mentionSpans[1].getAttribute('data-id')).toBe('user-bob')
})
it('hides visibility selector when allowInternalComments is false', () => {
const onSendMessage = vi.fn()
render(<ChatInput projectId="proj-1" onSendMessage={onSendMessage} />, {
wrapper: createWrapper(),
})
expect(document.querySelector('[data-testid="comment-visibility-trigger"]')).toBeNull()
})
it('defaults to Public, switches to Internal via dropdown pill, and resets after send', () => {
const onSendMessage = vi.fn()
render(
<ChatInput projectId="proj-1" onSendMessage={onSendMessage} allowInternalComments={true} />,
{ wrapper: createWrapper() },
)
const trigger = document.querySelector(
'[data-testid="comment-visibility-trigger"]',
) as HTMLButtonElement
expect(trigger).not.toBeNull()
expect(trigger.textContent).toContain('Public')
// Open dropdown and choose Internal
fireEvent.pointerDown(trigger)
fireEvent.click(trigger)
const internalOption = document.querySelector(
'[data-testid="comment-visibility-internal"]',
) as HTMLElement
expect(internalOption).not.toBeNull()
fireEvent.click(internalOption)
expect(trigger.textContent).toContain('Internal')
// Type message and send
const editor = document.querySelector('[contenteditable="true"]') as HTMLDivElement
editor.innerText = 'Internal discussion'
fireEvent.input(editor)
const sendButton = document.querySelector('button .lucide-arrow-up')?.closest('button')
fireEvent.click(sendButton as HTMLButtonElement)
expect(onSendMessage).toHaveBeenCalledWith(
'Internal discussion',
[],
[],
undefined,
undefined,
[],
true,
)
// Resets back to Public default after send
expect(trigger.textContent).toContain('Public')
})
it('locks visibility to Internal when replying to an internal comment', () => {
const internalComment: CommentInfo = {
id: 'comment-int',
assetId: 'asset-1',
message: 'Private thread',
annotations: null,
second: null,
creator: { id: 'user-alice', name: 'Alice Smith' },
replies: [],
attachments: [],
mentions: [],
createdAt: '2026-08-20T10:30:00.000Z',
updatedAt: '2026-08-20T10:30:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: true,
completionLastChangedBy: null,
reactionCounts: [],
}
const onSendMessage = vi.fn()
render(
<ChatInput
projectId="proj-1"
onSendMessage={onSendMessage}
replyingTo={internalComment}
allowInternalComments={true}
/>,
{ wrapper: createWrapper() },
)
const trigger = document.querySelector(
'[data-testid="comment-visibility-trigger"]',
) as HTMLButtonElement
expect(trigger).not.toBeNull()
expect(trigger.textContent).toContain('Internal')
expect(trigger.disabled).toBe(true)
const sendButton = document.querySelector('button .lucide-arrow-up')?.closest('button')
fireEvent.click(sendButton as HTMLButtonElement)
expect(onSendMessage).toHaveBeenCalledWith(
'<@user-alice>',
[],
[],
'comment-int',
undefined,
[],
true,
)
})
})
@@ -32,6 +32,8 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/
import { formatTimecode } from '../viewers/video/utils'
import { useUiStore } from '@/ui/stores/ui'
import { isImageFileName } from '@/ui/lib/media'
import { CommentVisibilitySelector } from './comment-visibility-selector'
import { createMentionNode, serializeEditableContent } from './mention-utils'
export type UploadingFile = {
id: string // A unique ID for the file, e.g., timestamp + name
@@ -59,6 +61,7 @@ export interface ChatInputProps {
replyToId?: string | null,
second?: number | null,
attachedFilesMeta?: AttachedFileMeta[],
isInternal?: boolean,
) => void
placeholder?: string
@@ -95,6 +98,9 @@ export interface ChatInputProps {
replyingTo?: CommentInfo | null
onCancelReply?: () => void
// Internal Comments (hidden from public share links)
allowInternalComments?: boolean
// Bottom action bar extras (e.g. Agent Selector)
bottomLeftExtra?: React.ReactNode
@@ -127,6 +133,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
onSendMessage,
replyingTo,
onCancelReply,
allowInternalComments = false,
placeholder,
initialText = '',
value,
@@ -156,6 +163,14 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
const [viewingFile, setViewingFile] = useState<File | null>(null)
const [isTimestampEnabled, setIsTimestampEnabled] = useState(true)
const [isInternal, setIsInternal] = useState(false)
const isReplyLockedInternal = Boolean(allowInternalComments && replyingTo?.isInternal)
const effectiveIsInternal = allowInternalComments
? isReplyLockedInternal
? true
: isInternal
: false
const effectiveAllowMentions = allowMentions ?? !disableMentions
const effectiveAllowMarkup = allowMarkup ?? !hideAnnotationControl
@@ -285,14 +300,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
(user: { id: string; name: string }) => {
if (!editorRef.current) return
const mentionNode = document.createElement('span')
mentionNode.contentEditable = 'false'
mentionNode.dataset.type = 'mention'
mentionNode.dataset.id = user.id
mentionNode.className =
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
mentionNode.innerText = `@${user.name}`
const mentionNode = createMentionNode(user)
const spaceNode = document.createTextNode('\u00A0')
editorRef.current.appendChild(mentionNode)
@@ -457,13 +465,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const range = mentionRangeRef.current
range.deleteContents()
const mentionNode = document.createElement('span')
mentionNode.contentEditable = 'false'
mentionNode.dataset.type = 'mention'
mentionNode.dataset.id = entity.data.id
mentionNode.className =
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
mentionNode.innerText = `@${entity.data.name}`
const mentionNode = createMentionNode({ id: entity.data.id, name: entity.data.name })
range.insertNode(mentionNode)
@@ -652,26 +654,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
}))
// Serialize content
let processedText = ''
editorRef.current.childNodes.forEach((node) => {
if (node.nodeType === Node.TEXT_NODE) {
processedText += node.textContent
} else if (node.nodeType === Node.ELEMENT_NODE) {
const el = node as HTMLElement
if (el.dataset.type === 'mention') {
processedText += `<@${el.dataset.id}>`
} else if (el.tagName === 'BR') {
processedText += '\n'
} else if (el.tagName === 'DIV' || el.tagName === 'P') {
// contentEditable often uses div/p for new lines
processedText += '\n' + el.innerText
} else {
processedText += el.innerText
}
}
})
processedText = processedText.trim()
const processedText = serializeEditableContent(editorRef.current)
const hasWorkspaceAssets = (workspaceAssets?.length ?? 0) > 0
@@ -684,14 +667,26 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
)
return
onSendMessage(
processedText,
successfulAttachmentIds,
annotations,
replyingTo?.id,
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
successfulAttachedFilesMeta,
)
if (allowInternalComments) {
onSendMessage(
processedText,
successfulAttachmentIds,
annotations,
replyingTo?.id,
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
successfulAttachedFilesMeta,
effectiveIsInternal,
)
} else {
onSendMessage(
processedText,
successfulAttachmentIds,
annotations,
replyingTo?.id,
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
successfulAttachedFilesMeta,
)
}
// Reset editor
editorRef.current.innerHTML = ''
@@ -703,6 +698,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
setIsDrawing(false)
resetAnnotations()
setShowMentionList(false)
setIsInternal(false)
if (onCancelReply) onCancelReply()
}
@@ -1177,17 +1173,27 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
</div>
</button>
) : (
<button
onClick={handleSend}
disabled={!canSend || isUploading}
className={`p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${
canSend && !isUploading
? 'bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5 cursor-pointer'
: 'bg-gray-400 cursor-not-allowed opacity-50'
}`}
>
<ArrowUp className="w-4 h-4" />
</button>
<div className="flex items-center gap-1.5 shrink-0">
{allowInternalComments && !isDrawing && (
<CommentVisibilitySelector
isInternal={effectiveIsInternal}
onChange={setIsInternal}
disabled={isReplyLockedInternal}
disabledTooltip={m.internal_reply_locked_tooltip()}
/>
)}
<button
onClick={handleSend}
disabled={!canSend || isUploading}
className={`h-7 w-7 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${
canSend && !isUploading
? 'bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5 cursor-pointer'
: 'bg-gray-400 cursor-not-allowed opacity-50'
}`}
>
<ArrowUp className="w-3.5 h-3.5" />
</button>
</div>
)}
</div>
@@ -118,9 +118,10 @@ export function FileBrowserGridView({
useEffect(() => {
let resizeFrame = 0
const observeTarget = scrollContainerRef.current ?? containerRef.current
const updateCols = () => {
if (!containerRef.current) return
const width = containerRef.current.offsetWidth
const width = containerRef.current?.offsetWidth ?? scrollContainerRef.current?.clientWidth
if (!width) return
if (width < 640) setCols(2)
else if (width < 768) setCols(2)
else if (width < 1024) setCols(3)
@@ -134,12 +135,12 @@ export function FileBrowserGridView({
cancelAnimationFrame(resizeFrame)
resizeFrame = requestAnimationFrame(updateCols)
})
if (containerRef.current) observer.observe(containerRef.current)
if (observeTarget) observer.observe(observeTarget)
return () => {
observer.disconnect()
cancelAnimationFrame(resizeFrame)
}
}, [])
}, [scrollContainerRef])
const rows = useMemo(() => {
const list: (
@@ -191,6 +192,7 @@ export function FileBrowserGridView({
),
overscan: 5,
paddingEnd: 240,
useFlushSync: false,
})
const virtualItems = rowVirtualizer.getVirtualItems()
@@ -333,6 +333,7 @@ export function FileBrowserListView({
),
overscan: 10,
paddingEnd: 240,
useFlushSync: false,
})
const virtualItems = rowVirtualizer.getVirtualItems()
@@ -209,12 +209,14 @@ export function FileViewerRightSidebar({
annotations,
replyToId,
second,
isInternal,
}: {
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
second?: number | null
isInternal?: boolean
}) => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
@@ -246,6 +248,7 @@ export function FileViewerRightSidebar({
replyToId: replyToId ?? undefined,
annotations: annotations,
second: second ?? undefined,
isInternal: isInternal ?? false,
},
})
if (!res.ok) throw new Error('Failed to create comment')
@@ -297,6 +300,8 @@ export function FileViewerRightSidebar({
annotations?: Annotation[],
replyToId?: string | null,
second?: number | null,
_attachedFilesMeta?: unknown,
isInternal?: boolean,
) => {
if (!file?.id) return
@@ -321,7 +326,7 @@ export function FileViewerRightSidebar({
createComment({ text, attachmentIds, annotations, replyToId, second })
}
} else {
createComment({ text, attachmentIds, annotations, replyToId, second })
createComment({ text, attachmentIds, annotations, replyToId, second, isInternal })
}
setReplyingTo(null)
}
@@ -418,6 +423,7 @@ export function FileViewerRightSidebar({
<div key={comment.id}>
<MessageCard
teamId={teamId}
projectId={projectId}
message={comment}
getUser={getUser}
onReply={setReplyingTo}
@@ -444,7 +450,9 @@ export function FileViewerRightSidebar({
<div key={reply.id}>
<MessageCard
teamId={teamId}
projectId={projectId}
isReply={true}
parentIsInternal={comment.isInternal}
message={reply}
getUser={getUser}
onReply={setReplyingTo}
@@ -488,6 +496,7 @@ export function FileViewerRightSidebar({
onSendMessage={handleSendMessage}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
allowInternalComments={!isPublic}
hideAnnotationControl={hideAnnotationControl}
disableMentions={isPublic}
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
@@ -171,12 +171,14 @@ export function MobileFileBottomSheet({
annotations,
replyToId,
second,
isInternal,
}: {
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
second?: number | null
isInternal?: boolean
}) => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
@@ -208,6 +210,7 @@ export function MobileFileBottomSheet({
replyToId: replyToId ?? undefined,
annotations: annotations,
second: second ?? undefined,
isInternal: isInternal ?? false,
},
})
if (!res.ok) throw new Error('Failed to create comment')
@@ -267,6 +270,8 @@ export function MobileFileBottomSheet({
annotations: Annotation[] = [],
replyToId?: string | null,
second?: number | null,
_attachedFilesMeta?: unknown,
isInternal?: boolean,
) => {
if (!text.trim() && attachmentIds.length === 0 && annotations.length === 0) return
@@ -286,7 +291,14 @@ export function MobileFileBottomSheet({
})
}
} else {
createComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, second })
createComment({
text,
attachmentIds,
annotations,
replyToId: actualReplyToId,
second,
isInternal,
})
}
setReplyingTo(null)
}
@@ -372,6 +384,7 @@ export function MobileFileBottomSheet({
<div key={comment.id}>
<MessageCard
teamId={teamId}
projectId={projectId}
message={comment}
getUser={getUser}
onReply={setReplyingTo}
@@ -398,7 +411,9 @@ export function MobileFileBottomSheet({
<div key={reply.id}>
<MessageCard
teamId={teamId}
projectId={projectId}
isReply={true}
parentIsInternal={comment.isInternal}
message={reply}
getUser={getUser}
onReply={setReplyingTo}
@@ -445,6 +460,7 @@ export function MobileFileBottomSheet({
onSendMessage={handleSendMessage}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
allowInternalComments={!isPublic}
hideAnnotationControl={hideAnnotationControl}
disableMentions={isPublic}
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
@@ -25,6 +25,7 @@ function makeComment(overrides: Partial<CommentInfo> = {}): CommentInfo {
updatedAt: '2026-11-25T14:53:00.000Z',
sessionId: null,
isCompleted: false,
isInternal: false,
completionLastChangedBy: null,
reactionCounts: [],
...overrides,
@@ -498,4 +499,29 @@ describe('PrintCommentsView', () => {
'0 0 200 267',
)
})
it('renders a lock indicator for internal comments', () => {
render(
<PrintCommentsView
asset={{
id: 'asset-1',
name: 'video.mp4',
sizeByte: 100,
fileCount: 1,
type: 'file',
status: 'processed',
proxyType: 'video',
createdAt: '2026-11-25T14:53:00.000Z',
updatedAt: '2026-11-25T14:53:00.000Z',
}}
breadcrumbs={['Project']}
comments={[
makeComment({ id: 'c-pub', isInternal: false }),
makeComment({ id: 'c-int', isInternal: true }),
]}
/>,
)
expect(screen.getAllByTestId('print-comment-internal')).toHaveLength(1)
})
})
@@ -14,6 +14,7 @@ import {
FileIcon,
FileText,
Loader2,
Lock,
Printer,
} from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
@@ -399,6 +400,16 @@ export const PrintCommentsView: React.FC<PrintCommentsViewProps> = ({
<span className="whitespace-nowrap text-xs text-muted-foreground">
{formatCommentDateTime(comment.createdAt)}
</span>
{comment.isInternal && (
<span
className="inline-flex items-center text-muted-foreground"
title={m.internal_comment_tooltip()}
aria-label={m.internal_comment_tooltip()}
data-testid="print-comment-internal"
>
<Lock className="h-3.5 w-3.5" />
</span>
)}
</div>
<div className="flex shrink-0 items-center gap-2">
{comment.isCompleted && (