feat(chat): support markups, attachments, and timestamps in agent 1-to-1 chat (#368)

* feat(chat): support markups, attachments, and timestamps in agent 1-to-1 chat

* feat(chat): improve message card layout with inline badges and integrated assets

* fix(chat): enable image attachment thumbnails in 1-to-1 chat cards

* fix(chat): address code review feedback on input state, mentions, i18n, and session deletion

* fix(chat): replace ring with border color on selected message card
This commit is contained in:
Yiling-J
2026-08-31 20:11:27 +08:00
committed by GitHub
parent 6e9cf8dfb6
commit e06478df88
36 changed files with 1908 additions and 353 deletions
@@ -0,0 +1,143 @@
// @vitest-environment happy-dom
import React from 'react'
import { cleanup, render, fireEvent, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ChatInput } from './message-input'
import { useMemberStore } from '@/ui/stores/members'
describe('ChatInput mention navigation', () => {
afterEach(() => {
cleanup()
vi.clearAllMocks()
})
it('selects the correct member item when the Agents section is collapsed', async () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
useMemberStore.setState({
members: [
{ id: 'agent-1', name: 'Bot Alice', type: 'agent', role: 'bot' },
{ id: 'agent-2', name: 'Bot Bob', type: 'agent', role: 'bot' },
{ id: 'user-1', name: 'Carol Human', type: 'human', role: 'editor' },
{ id: 'user-2', name: 'David Human', type: 'human', role: 'editor' },
],
loading: false,
fetchMembers: vi.fn(),
fetchProjectMembers: vi.fn(),
})
const mockSendMessage = vi.fn()
const { container, getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatInput projectId="proj-1" allowMentions={true} onSendMessage={mockSendMessage} />
</QueryClientProvider>,
)
const editor = container.querySelector('[contenteditable="true"]') as HTMLDivElement
expect(editor).toBeTruthy()
// Type @ and set cursor selection in DOM
const textNode = document.createTextNode('@')
editor.appendChild(textNode)
const range = document.createRange()
range.setStart(textNode, 1)
range.setEnd(textNode, 1)
const sel = window.getSelection()!
sel.removeAllRanges()
sel.addRange(range)
fireEvent.input(editor)
// Mention list should appear with Agents and Members headers
expect(getByText('Agents')).toBeTruthy()
expect(getByText('Members')).toBeTruthy()
// Collapse the Agents section
const agentsHeaderBtn = getByText('Agents').closest('button')!
fireEvent.click(agentsHeaderBtn)
// Agents should no longer be rendered, but Members should be visible
expect(screen.queryByText('Bot Alice')).toBeNull()
const carolBtn = getByText('Carol Human').closest('button')!
expect(carolBtn).toBeTruthy()
// Carol Human should have data-index="0" because bots are collapsed
expect(carolBtn.getAttribute('data-index')).toBe('0')
// Hover over Carol Human
fireEvent.mouseEnter(carolBtn)
// Press Enter to select Carol Human
fireEvent.keyDown(editor, { key: 'Enter' })
// Editor should now contain the mention badge for Carol Human (user-1)
const mentionNode = editor.querySelector('[data-type="mention"]') as HTMLElement
expect(mentionNode).toBeTruthy()
expect(mentionNode.dataset.id).toBe('user-1')
expect(mentionNode.textContent).toContain('Carol Human')
})
it('navigates with ArrowDown and ArrowUp after clicking to collapse the Agents section', async () => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
useMemberStore.setState({
members: [
{ id: 'agent-1', name: 'Bot Alice', type: 'agent', role: 'bot' },
{ id: 'agent-2', name: 'Bot Bob', type: 'agent', role: 'bot' },
{ id: 'user-1', name: 'Carol Human', type: 'human', role: 'editor' },
{ id: 'user-2', name: 'David Human', type: 'human', role: 'editor' },
],
loading: false,
fetchMembers: vi.fn(),
fetchProjectMembers: vi.fn(),
})
const mockSendMessage = vi.fn()
const { container, getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatInput projectId="proj-1" allowMentions={true} onSendMessage={mockSendMessage} />
</QueryClientProvider>,
)
const editor = container.querySelector('[contenteditable="true"]') as HTMLDivElement
expect(editor).toBeTruthy()
// Type @ and set cursor selection
const textNode = document.createTextNode('@')
editor.appendChild(textNode)
const range = document.createRange()
range.setStart(textNode, 1)
range.setEnd(textNode, 1)
const sel = window.getSelection()!
sel.removeAllRanges()
sel.addRange(range)
fireEvent.input(editor)
// Click collapse on Agents
const agentsHeaderBtn = getByText('Agents').closest('button')!
fireEvent.mouseDown(agentsHeaderBtn)
fireEvent.click(agentsHeaderBtn)
// Now press ArrowDown on editor to move from item 0 (Carol) to item 1 (David)
fireEvent.keyDown(editor, { key: 'ArrowDown' })
const davidBtn = getByText('David Human').closest('button')!
expect(davidBtn.className).toContain('bg-accent')
// Press Enter to select David
fireEvent.keyDown(editor, { key: 'Enter' })
const mentionNode = editor.querySelector('[data-type="mention"]') as HTMLElement
expect(mentionNode).toBeTruthy()
expect(mentionNode.dataset.id).toBe('user-2')
expect(mentionNode.textContent).toContain('David Human')
})
})
+303 -89
View File
@@ -19,6 +19,7 @@ import {
Paperclip,
Redo,
Square,
Trash2,
Undo,
XIcon,
} from 'lucide-react'
@@ -27,10 +28,12 @@ import { Button } from '../ui/button'
import { DrawAnnotation } from '../ui/icons'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { ProgressCircle } from '../ui/progress-circle'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
import { formatTimecode } from '../viewers/video/utils'
import { useUiStore } from '@/ui/stores/ui'
import { isImageFileName } from '@/ui/lib/media'
type UploadingFile = {
export type UploadingFile = {
id: string // A unique ID for the file, e.g., timestamp + name
file: File
progress: number
@@ -38,7 +41,16 @@ type UploadingFile = {
error?: string
}
interface ChatInputProps {
export interface AttachedFileMeta {
id: string
name: string
type: string
url?: string
mediaType?: string
mimeType?: string
}
export interface ChatInputProps {
projectId: string
onSendMessage: (
text: string,
@@ -46,16 +58,51 @@ interface ChatInputProps {
annotations?: Annotation[],
replyToId?: string | null,
second?: number | null,
attachedFilesMeta?: AttachedFileMeta[],
) => void
replyingTo?: CommentInfo | null
onCancelReply?: () => void
placeholder?: string
initialText?: string
hideAnnotationControl?: boolean
value?: string
onChangeText?: (text: string) => void
disabled?: boolean
// Mentions
allowMentions?: boolean
disableMentions?: boolean
// Local file attachments
allowAttachments?: boolean
// Referenced workspace assets
workspaceAssets?: Array<{ id: string; name: string; type: string }>
onRemoveWorkspaceAsset?: (id: string) => void
// Markup / Annotations
allowMarkup?: boolean
hideAnnotationControl?: boolean
canMarkup?: boolean
markupDisabledTooltip?: string
// Timestamps
allowTimestamp?: boolean
currentTime?: number
frameRate?: number
startTimecode?: string
formatTimestamp?: (second: number) => string
// Comment Thread Reply
replyingTo?: CommentInfo | null
onCancelReply?: () => void
// Bottom action bar extras (e.g. Agent Selector)
bottomLeftExtra?: React.ReactNode
// Streaming & Abort
isStreaming?: boolean
onAbort?: () => void
// Callbacks
onTyping?: () => void
}
@@ -80,13 +127,28 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
onSendMessage,
replyingTo,
onCancelReply,
placeholder,
initialText = '',
hideAnnotationControl = false,
value,
onChangeText,
disabled = false,
allowMentions,
disableMentions = false,
allowAttachments = true,
workspaceAssets,
onRemoveWorkspaceAsset,
allowMarkup,
hideAnnotationControl = false,
canMarkup = true,
markupDisabledTooltip,
allowTimestamp = true,
currentTime,
frameRate,
startTimecode,
formatTimestamp,
bottomLeftExtra,
isStreaming = false,
onAbort,
onTyping,
},
ref,
@@ -95,6 +157,10 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const [viewingFile, setViewingFile] = useState<File | null>(null)
const [isTimestampEnabled, setIsTimestampEnabled] = useState(true)
const effectiveAllowMentions = allowMentions ?? !disableMentions
const effectiveAllowMarkup = allowMarkup ?? !hideAnnotationControl
const effectiveAllowTimestamp = allowTimestamp
const { videoTimeDisplayMode } = useUiStore()
const displayTime = React.useMemo(() => {
if (currentTime === undefined) return ''
@@ -145,6 +211,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const paddingLeftClass = React.useMemo(() => {
if (
!isTimestampEnabled ||
!effectiveAllowTimestamp ||
currentTime === undefined ||
(!formatTimestamp && !frameRate) ||
hasContent
@@ -155,12 +222,21 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
return 'pl-[120px]'
}
return 'pl-[85px]'
}, [isTimestampEnabled, currentTime, frameRate, hasContent, videoTimeDisplayMode])
}, [
isTimestampEnabled,
effectiveAllowTimestamp,
currentTime,
frameRate,
hasContent,
videoTimeDisplayMode,
formatTimestamp,
])
const editorRef = useRef<HTMLDivElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const mentionRangeRef = useRef<Range | null>(null)
const mentionListRef = useRef<HTMLDivElement>(null)
const isInternalUpdateRef = useRef(false)
const { mutateAsync: uploadAttachment } = useMutation({
mutationFn: async ({
@@ -180,7 +256,16 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
})
useEffect(() => {
if (initialText && editorRef.current) {
if (value !== undefined && editorRef.current) {
if (isInternalUpdateRef.current) {
isInternalUpdateRef.current = false
return
}
if (editorRef.current.innerText !== value) {
editorRef.current.innerText = value
setHasContent(!!value.trim())
}
} else if (initialText && editorRef.current) {
editorRef.current.innerText = initialText
setHasContent(!!initialText.trim())
// Focus and move cursor to end
@@ -192,7 +277,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
sel?.removeAllRanges()
sel?.addRange(range)
}
}, [initialText])
}, [value, initialText])
// Focus editor when replyingTo becomes truthy
useEffect(() => {
@@ -254,10 +339,13 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const handleInput = () => {
if (!editorRef.current) return
setHasContent(!!editorRef.current.innerText.trim())
const text = editorRef.current.innerText || ''
setHasContent(!!text.trim())
isInternalUpdateRef.current = true
onChangeText?.(text)
onTyping?.()
if (disableMentions) {
if (!effectiveAllowMentions) {
setShowMentionList(false)
mentionRangeRef.current = null
return
@@ -337,13 +425,17 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
setShowMentionList(false)
mentionRangeRef.current = null
setHasContent(true)
const currentText = editorRef.current.innerText || ''
isInternalUpdateRef.current = true
onChangeText?.(currentText)
onTyping?.()
editorRef.current.focus()
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.nativeEvent.isComposing) return
if (showMentionList && filteredEntities.length > 0) {
if (showMentionList && effectiveAllowMentions && filteredEntities.length > 0) {
if (e.key === 'ArrowUp') {
e.preventDefault()
setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredEntities.length - 1))
@@ -444,6 +536,18 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
.map((f) => f.attachmentId)
.filter((id): id is string => !!id)
const successfulAttachedFilesMeta: AttachedFileMeta[] = uploadingFiles
.filter((f) => !f.error && !!f.attachmentId)
.map((f) => ({
id: f.attachmentId!,
name: f.file.name,
type: f.file.type,
url:
f.file.type.startsWith('image/') || isImageFileName(f.file.name)
? URL.createObjectURL(f.file)
: undefined,
}))
// Serialize content
let processedText = ''
editorRef.current.childNodes.forEach((node) => {
@@ -466,20 +570,31 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
processedText = processedText.trim()
// Allow sending if annotations exist, even if text is empty
if (!processedText && successfulAttachmentIds.length === 0 && annotations.length === 0) return
const hasWorkspaceAssets = (workspaceAssets?.length ?? 0) > 0
// Allow sending if annotations, attachments, or workspace assets exist, even if text is empty
if (
!processedText &&
successfulAttachmentIds.length === 0 &&
annotations.length === 0 &&
!hasWorkspaceAssets
)
return
onSendMessage(
processedText,
successfulAttachmentIds,
annotations,
replyingTo?.id,
isTimestampEnabled ? currentTime : undefined,
effectiveAllowTimestamp && isTimestampEnabled ? currentTime : undefined,
successfulAttachedFilesMeta,
)
// Reset editor
editorRef.current.innerHTML = ''
setHasContent(false)
isInternalUpdateRef.current = true
onChangeText?.('')
setUploadingFiles([])
setViewingFile(null)
setIsDrawing(false)
@@ -490,13 +605,18 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
const hasSuccessfulUploads = uploadingFiles.some((f) => !!f.attachmentId)
const canSend = hasContent || hasSuccessfulUploads || annotations.length > 0
const showUpperPart = uploadingFiles.length > 0 || !!replyingTo
const hasWorkspaceAssets = (workspaceAssets?.length ?? 0) > 0
const effectiveDisabled = disabled || isStreaming
const canSend =
(hasContent || hasSuccessfulUploads || annotations.length > 0 || hasWorkspaceAssets) &&
!effectiveDisabled
const showUpperPart =
(workspaceAssets && workspaceAssets.length > 0) || uploadingFiles.length > 0 || !!replyingTo
return (
<div
ref={ref}
className="relative flex flex-col w-full border border-foreground/35 rounded-3xl shadow-sm transition-all duration-200"
className="relative flex flex-col w-full border border-foreground/35 rounded-3xl shadow-sm transition-all duration-200 bg-background"
>
<style>{`
[contenteditable]:empty:before {
@@ -506,8 +626,12 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
}
`}</style>
{showMentionList &&
effectiveAllowMentions &&
(membersLoading || filteredAgents.length > 0 || filteredHumans.length > 0) && (
<div className="absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200">
<div
onMouseDown={(e) => e.preventDefault()}
className="absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200"
>
<div ref={mentionListRef} className="h-64 overflow-y-auto">
{membersLoading ? (
<div className="p-2 space-y-4 animate-pulse">
@@ -545,12 +669,15 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
{filteredAgents.length > 0 && (
<>
<button
type="button"
onMouseDown={(e) => e.preventDefault()}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setCollapsedSections((prev) => ({ ...prev, bots: !prev.bots }))
editorRef.current?.focus()
}}
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border flex items-center justify-between hover:bg-muted transition-colors"
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border flex items-center justify-between hover:bg-muted transition-colors cursor-pointer select-none"
>
<span>Agents</span>
<ChevronDown
@@ -562,11 +689,13 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
const actualIndex = index
return (
<button
type="button"
key={item.data.id}
data-index={actualIndex}
onMouseDown={(e) => e.preventDefault()}
onClick={() => handleSelectEntity(item)}
onMouseEnter={() => setHighlightedIndex(actualIndex)}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left cursor-pointer ${
actualIndex === highlightedIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
@@ -594,12 +723,15 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
{filteredHumans.length > 0 && (
<>
<button
type="button"
onMouseDown={(e) => e.preventDefault()}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setCollapsedSections((prev) => ({ ...prev, users: !prev.users }))
editorRef.current?.focus()
}}
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border flex items-center justify-between hover:bg-muted transition-colors"
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border flex items-center justify-between hover:bg-muted transition-colors cursor-pointer select-none"
>
<span>Members</span>
<ChevronDown
@@ -608,15 +740,17 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
</button>
{!collapsedSections.users &&
filteredHumans.map((item, index) => {
const actualIndex =
(collapsedSections.bots ? 0 : filteredAgents.length) + index
const agentOffset = collapsedSections.bots ? 0 : filteredAgents.length
const actualIndex = index + agentOffset
return (
<button
type="button"
key={item.data.id}
data-index={actualIndex}
onMouseDown={(e) => e.preventDefault()}
onClick={() => handleSelectEntity(item)}
onMouseEnter={() => setHighlightedIndex(actualIndex)}
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left cursor-pointer ${
actualIndex === highlightedIndex
? 'bg-accent text-accent-foreground'
: 'hover:bg-accent/50'
@@ -630,7 +764,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
className="object-cover"
/>
)}
<AvatarFallback className="text-[10px] bg-blue-400 text-black font-semibold">
<AvatarFallback className="text-[10px] bg-purple-400 text-black font-semibold">
{getInitials(item.data.name)}
</AvatarFallback>
</Avatar>
@@ -648,6 +782,35 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
{showUpperPart && (
<div className="flex flex-col gap-2 p-3 pb-0 animate-in fade-in slide-in-from-bottom-2 duration-200">
{/* Referenced Workspace Assets */}
{workspaceAssets && workspaceAssets.length > 0 && (
<div className="flex flex-col gap-1.5 min-h-0 max-h-[160px] overflow-y-auto border border-border/60 rounded-lg bg-muted/20 p-2.5 divide-y divide-border/50">
{workspaceAssets.map((asset) => (
<div
key={asset.id}
className="flex items-center justify-between py-1 text-xs group"
>
<div className="flex items-baseline gap-1.5 min-w-0 pr-2">
<span className="truncate font-medium text-foreground">{asset.name}</span>
<span className="text-[9px] text-muted-foreground uppercase flex-shrink-0">
{asset.type}
</span>
</div>
{onRemoveWorkspaceAsset && (
<button
onClick={() => onRemoveWorkspaceAsset(asset.id)}
className="text-muted-foreground hover:text-destructive transition-colors p-0.5 cursor-pointer"
title={m.remove_from_context?.() || 'Remove from context'}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
)}
</div>
))}
</div>
)}
{/* Replying banner */}
{replyingTo && (
<div className="flex items-center justify-between bg-muted p-2 px-3 rounded-lg border border-border">
<div className="text-xs text-muted-foreground truncate mr-2">
@@ -662,6 +825,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
</div>
)}
{/* Local file uploads thumbnail strip */}
{uploadingFiles.length > 0 && (
<div className="flex gap-3 overflow-x-auto py-2 px-1 scrollbar-hide">
{uploadingFiles.map((upload) => (
@@ -687,7 +851,7 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
</div>
<button
onClick={() => removeFile(upload.id)}
className="absolute -top-1.5 -right-1.5 bg-gray-500 text-white rounded-full p-0.5 shadow-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-500 z-10"
className="absolute -top-1.5 -right-1.5 bg-gray-500 text-white rounded-full p-0.5 shadow-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-500 z-10 cursor-pointer"
>
<XIcon className="w-3 h-3" />
</button>
@@ -705,24 +869,29 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
onClick={() => editorRef.current?.focus()}
className="w-full px-4 pt-1 pb-1 cursor-text flow-root max-h-60 overflow-y-auto"
>
{isTimestampEnabled && currentTime !== undefined && frameRate !== undefined && (
<div
onClick={(e) => {
e.stopPropagation()
editorRef.current?.focus()
}}
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-0.5 mt-3 mr-2 rounded-sm text-xs font-mono font-bold flex items-center gap-1 cursor-text"
>
{displayTime}
</div>
)}
{effectiveAllowTimestamp &&
isTimestampEnabled &&
currentTime !== undefined &&
(frameRate !== undefined || formatTimestamp !== undefined) && (
<div
onClick={(e) => {
e.stopPropagation()
editorRef.current?.focus()
}}
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-0.5 mt-3 mr-2 rounded-sm text-xs font-mono font-bold flex items-center gap-1 cursor-text"
>
{displayTime}
</div>
)}
<div
ref={editorRef}
contentEditable
contentEditable={!disabled && !isStreaming}
suppressContentEditableWarning
onInput={handleInput}
onKeyDown={handleKeyDown}
data-placeholder={replyingTo ? m.reply_placeholder() : m.message_placeholder()}
data-placeholder={
placeholder || (replyingTo ? m.reply_placeholder() : m.message_placeholder())
}
className={`bg-transparent border-none focus:ring-0 resize-none min-h-[40px] leading-relaxed py-2 focus:outline-none block ${paddingLeftClass}`}
/>
</div>
@@ -818,59 +987,104 @@ export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
</button>
</div>
) : (
<div className="flex items-center gap-1">
<input
type="file"
ref={fileInputRef}
className="hidden"
multiple
onChange={handleFileSelect}
/>
{currentTime !== undefined && frameRate !== undefined && (
<Button
onClick={() => setIsTimestampEnabled(!isTimestampEnabled)}
variant={isTimestampEnabled ? 'secondary' : 'ghost'}
size="icon"
className={`p-2 rounded-full cursor-pointer ${isTimestampEnabled ? 'text-blue-600 bg-blue-50 dark:bg-blue-900/20' : ''}`}
title={isTimestampEnabled ? m.disable_timestamp() : m.enable_timestamp()}
>
<Clock className="w-4 h-4" />
</Button>
)}
<Button
onClick={() => fileInputRef.current?.click()}
className="p-2 rounded-full cursor-pointer"
variant="ghost"
size="icon"
title={m.attach_files()}
>
<Paperclip className="w-4 h-4" />
</Button>
{!hideAnnotationControl && (
<Button
onClick={() => setIsDrawing(true)}
variant="ghost"
size="icon"
className="p-2 rounded-full cursor-pointer"
title={m.toggle_annotation()}
>
<DrawAnnotation className="w-4 h-4" />
</Button>
<div className="flex items-center gap-1.5 min-w-0 max-w-[80%]">
{bottomLeftExtra}
{allowAttachments && (
<>
<input
type="file"
ref={fileInputRef}
className="hidden"
multiple
onChange={handleFileSelect}
/>
<Button
onClick={() => fileInputRef.current?.click()}
className="p-2 rounded-full cursor-pointer shrink-0"
variant="ghost"
size="icon"
title={m.attach_files()}
>
<Paperclip className="w-4 h-4" />
</Button>
</>
)}
{effectiveAllowTimestamp &&
currentTime !== undefined &&
(frameRate !== undefined || formatTimestamp !== undefined) && (
<Button
onClick={() => setIsTimestampEnabled(!isTimestampEnabled)}
variant={isTimestampEnabled ? 'secondary' : 'ghost'}
size="icon"
className={`p-2 rounded-full cursor-pointer shrink-0 ${isTimestampEnabled ? 'text-blue-600 bg-blue-50 dark:bg-blue-900/20' : ''}`}
title={isTimestampEnabled ? m.disable_timestamp() : m.enable_timestamp()}
>
<Clock className="w-4 h-4" />
</Button>
)}
{effectiveAllowMarkup &&
(canMarkup ? (
<Button
onClick={() => {
onTyping?.()
setIsDrawing(true)
}}
variant="ghost"
size="icon"
className="p-2 rounded-full cursor-pointer shrink-0"
title={m.toggle_annotation()}
>
<DrawAnnotation className="w-4 h-4" />
</Button>
) : (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-block cursor-not-allowed shrink-0">
<Button
disabled
variant="ghost"
size="icon"
className="p-2 rounded-full opacity-40 cursor-not-allowed pointer-events-none"
>
<DrawAnnotation className="w-4 h-4" />
</Button>
</span>
</TooltipTrigger>
<TooltipContent side="top">
<p className="text-xs">
{markupDisabledTooltip || m.markup_not_supported_for_this_file()}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
))}
</div>
)}
<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'
: 'bg-gray-400 cursor-not-allowed'
}`}
>
<ArrowUp className="w-4 h-4" />
</button>
{isStreaming ? (
<button
onClick={onAbort}
className="p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm bg-destructive text-destructive-foreground hover:bg-destructive/90 transform hover:-translate-y-0.5 cursor-pointer"
title="Stop generation"
>
<div className="h-4 w-4 flex items-center justify-center">
<div className="h-3 w-3 rounded-[2px] bg-white" />
</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>
{viewingFile && (
@@ -6,6 +6,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ChatbotSidebar } from './chatbot-sidebar'
import { useChatbotStore, AGENT_PREFERENCE_STORAGE_KEY } from '@/ui/stores/chatbot'
import { client } from '@/ui/api/client'
import type { ChatMessage } from '@shumai/dtos'
const localStorageMock = (() => {
let store: Record<string, string> = {}
@@ -190,4 +191,281 @@ describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => {
expect(localStorage.getItem(AGENT_PREFERENCE_STORAGE_KEY)).toBeNull()
})
})
it('renders user messages with markup badge, timestamp, and attachments and triggers onSelectMessage on click when matched', async () => {
vi.mocked(client.api.projects[':projectId']['chat-agents'].$get).mockResolvedValue({
ok: true,
json: async () => [{ id: 'agent-1', name: 'Agent 1', type: 'chat', enabled: true }],
} as unknown as Awaited<
ReturnType<(typeof client.api.projects)[':projectId']['chat-agents']['$get']>
>)
const mockSelectMessage = vi.fn()
const mockMessage = {
id: 'msg-1',
role: 'custom',
customType: 'shumai_message',
content: 'Fix the color in this scene',
details: {
annotation: true,
annotations: [{ type: 'rectangle', x: 5, y: 10 }],
position: { type: 'time', seconds: 15 },
currentAsset: { id: 'file-123', name: 'video.mp4', type: 'file' },
attachedFiles: [
{ id: 'att-1', name: 'color-ref.png', type: 'image', mediaType: 'image/png' },
],
},
} as unknown as ChatMessage
useChatbotStore.setState({
messages: [mockMessage],
})
const { getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar
projectId="proj-1"
contextAssetId="file-123"
onSelectMessage={mockSelectMessage}
/>
</QueryClientProvider>,
)
expect(getByText('Fix the color in this scene')).toBeTruthy()
expect(getByText('00:15')).toBeTruthy()
expect(getByText('color-ref.png')).toBeTruthy()
const msgCardInner = getByText('Fix the color in this scene').closest('.bg-primary')
expect(msgCardInner?.className).not.toContain('ring-2')
const msgCard = getByText('Fix the color in this scene').closest('div')
msgCard?.click()
expect(mockSelectMessage).toHaveBeenCalledWith(mockMessage)
})
it('renders selected message card with border-blue-500 instead of ring when selectedMessageId matches', async () => {
const mockMessage = {
id: 'msg-selected',
role: 'custom',
customType: 'shumai_message',
content: 'Selected message content',
details: {
position: { type: 'time', seconds: 10 },
currentAsset: { id: 'file-123', name: 'video.mp4', type: 'file' },
},
} as unknown as ChatMessage
useChatbotStore.setState({
messages: [mockMessage],
})
const { getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar
projectId="proj-1"
contextAssetId="file-123"
selectedMessageId="msg-selected"
/>
</QueryClientProvider>,
)
const cardInner = getByText('Selected message content').closest('.bg-primary')
expect(cardInner?.className).toContain('border-blue-500')
expect(cardInner?.className).not.toContain('ring')
})
it('does not trigger onSelectMessage on click when currentAsset does not match', async () => {
vi.mocked(client.api.projects[':projectId']['chat-agents'].$get).mockResolvedValue({
ok: true,
json: async () => [{ id: 'agent-1', name: 'Agent 1', type: 'chat', enabled: true }],
} as unknown as Awaited<
ReturnType<(typeof client.api.projects)[':projectId']['chat-agents']['$get']>
>)
const mockSelectMessage = vi.fn()
const mockMessage = {
id: 'msg-2',
role: 'custom',
customType: 'shumai_message',
content: 'Other file comment',
details: {
annotation: true,
annotations: [{ type: 'rectangle', x: 5, y: 10 }],
position: { type: 'time', seconds: 20 },
currentAsset: { id: 'other-file-456', name: 'other.mp4', type: 'file' },
},
} as unknown as ChatMessage
useChatbotStore.setState({
messages: [mockMessage],
})
const { getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar
projectId="proj-1"
contextAssetId="file-123"
onSelectMessage={mockSelectMessage}
/>
</QueryClientProvider>,
)
const msgCard = getByText('Other file comment').closest('div')
msgCard?.click()
expect(mockSelectMessage).not.toHaveBeenCalled()
})
it('renders full-width message card with inline badges, attachments and assets sections', async () => {
vi.mocked(client.api.projects[':projectId']['chat-agents'].$get).mockResolvedValue({
ok: true,
json: async () => [{ id: 'agent-1', name: 'Agent 1', type: 'chat', enabled: true }],
} as unknown as Awaited<
ReturnType<(typeof client.api.projects)[':projectId']['chat-agents']['$get']>
>)
const mockMessage = {
id: 'msg-full',
role: 'custom',
customType: 'shumai_message',
content: 'Review this scene carefully',
details: {
annotation: true,
annotations: [
{
type: 'box',
color: '#ff0000',
points: [
[0, 0],
[10, 10],
],
},
],
position: { type: 'time', seconds: 45 },
currentAsset: { id: 'file-123', name: 'clip.mp4', type: 'file' },
attachedFiles: [
{ id: 'att-1', name: 'reference-mood.jpg', type: 'image', mediaType: 'image/jpeg' },
],
referencedAssets: [
{ id: 'asset-ref-1', name: 'Storyboard.pdf', type: 'file' },
{ id: 'asset-ref-2', name: 'Audio Stems', type: 'folder' },
],
},
} as unknown as ChatMessage
useChatbotStore.setState({
messages: [mockMessage],
})
const { getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar projectId="proj-1" contextAssetId="file-123" />
</QueryClientProvider>,
)
// Inline text and timestamp
expect(getByText('Review this scene carefully')).toBeTruthy()
expect(getByText('00:45')).toBeTruthy()
// Attachments section
expect(getByText('Attachments')).toBeTruthy()
expect(getByText('reference-mood.jpg')).toBeTruthy()
// Assets section
expect(getByText('Assets')).toBeTruthy()
expect(getByText('Storyboard.pdf')).toBeTruthy()
expect(getByText('Audio Stems')).toBeTruthy()
// Card should be full width (w-full)
const cardEl = getByText('Review this scene carefully').closest('.bg-primary')
expect(cardEl?.className).toContain('w-full')
})
it('asks for confirmation before deleting a session and deletes when confirmed', async () => {
const mockDeleteSession = vi.fn()
const originalDeleteSession = useChatbotStore.getState().deleteSession
useChatbotStore.setState({
isHistoryMode: true,
historySessions: [
{
id: 'sess-1',
agentId: 'agent-1',
userId: 'user-1',
assetId: 'asset-1',
userCommentId: null,
name: 'Important Chat',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
],
deleteSession: mockDeleteSession,
})
const { useTeamContextStore } = await import('@/ui/stores/team-context')
useTeamContextStore.setState({ teamId: 'team-123' })
window.confirm = vi.fn()
const confirmSpy = vi.spyOn(window, 'confirm')
// 1. User cancels confirmation
confirmSpy.mockReturnValue(false)
const { getByTitle } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar projectId="proj-1" />
</QueryClientProvider>,
)
const deleteBtn = getByTitle('Delete Session')
deleteBtn.click()
expect(confirmSpy).toHaveBeenCalled()
expect(mockDeleteSession).not.toHaveBeenCalled()
// 2. User confirms deletion
confirmSpy.mockReturnValue(true)
deleteBtn.click()
expect(mockDeleteSession).toHaveBeenCalledWith('team-123', 'sess-1')
confirmSpy.mockRestore()
useChatbotStore.setState({ deleteSession: originalDeleteSession })
})
it('renders thinking_level_change messages properly in the chat log', () => {
const mockThinkingChangeMsg = {
id: 'think-1',
role: 'thinking_level_change',
content: 'Thinking level changed to high',
timestamp: Date.now(),
} as unknown as ChatMessage
useChatbotStore.setState({
messages: [mockThinkingChangeMsg],
})
const { getByText } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar projectId="proj-1" />
</QueryClientProvider>,
)
expect(getByText('Thinking level changed to high')).toBeTruthy()
})
it('disables message input when teamId is not available', async () => {
const { useTeamContextStore } = await import('@/ui/stores/team-context')
useTeamContextStore.setState({ teamId: null, projectTeamMap: {} })
useChatbotStore.setState({ selectedAgentId: 'agent-1' })
const { container } = render(
<QueryClientProvider client={queryClient}>
<ChatbotSidebar projectId="proj-1" />
</QueryClientProvider>,
)
const inputArea = container.querySelector('[contenteditable="false"]')
expect(inputArea).toBeTruthy()
expect(inputArea?.getAttribute('contenteditable')).toBe('false')
})
})
+382 -210
View File
@@ -11,31 +11,58 @@ import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { useChatbotStore } from '@/ui/stores/chatbot'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useUiStore } from '@/ui/stores/ui'
import { useDroppable } from '@dnd-kit/react'
import type { ChatMessage, ShumaiMessageContext } from '@shumai/dtos'
import type { AssetInfo, ChatMessage, ShumaiMessageContext } from '@shumai/dtos'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
ArrowLeft,
ArrowUp,
Bot,
Brain,
ChevronDown,
Download,
FileIcon,
Folder,
History,
Loader2,
Plus,
Trash2,
Wrench,
XIcon,
} from 'lucide-react'
import { useCallback, useEffect, useRef } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import Markdown from 'react-markdown'
import { formatTimeAgo } from '../lib/time'
import { ChatInput } from './chat/message-input'
import { DrawAnnotation } from './ui/icons'
import { formatTimecode } from './viewers/video/utils'
import { isImageFileName } from '@/ui/lib/media'
interface ChatbotSidebarProps {
projectId: string
contextAssetId?: string
file?: AssetInfo | null
currentTime?: number
frameRate?: number
startTimecode?: string
formatTimestamp?: (second: number) => string
onTyping?: () => void
onSelectMessage?: (message: ChatMessage) => void
selectedMessageId?: string | null
}
export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProps) {
export function ChatbotSidebar({
projectId,
contextAssetId,
file,
currentTime,
frameRate,
startTimecode,
formatTimestamp,
onTyping,
onSelectMessage,
selectedMessageId,
}: ChatbotSidebarProps) {
const {
isHistoryMode,
setIsHistoryMode,
@@ -58,6 +85,8 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
} = useChatbotStore()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const { videoTimeDisplayMode } = useUiStore()
const [previewImage, setPreviewImage] = useState<{ url: string; name: string } | null>(null)
useEffect(() => {
if (projectId) {
@@ -187,21 +216,6 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
queryClient.invalidateQueries({ queryKey: ['projects'] })
}, [queryClient])
const handleSend = () => {
if (!inputText.trim() || isStreaming || !teamId) return
sendMessage(teamId, inputText, projectId, contextAssetId, handleAssetMutation)
setInputText('')
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.nativeEvent.isComposing) return
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSend()
}
}
const getMessageText = (content: unknown): string => {
if (typeof content === 'string') return content
if (Array.isArray(content)) {
@@ -224,29 +238,221 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
const renderMessage = (msg: ChatMessage) => {
switch (msg.role as string) {
case 'user': {
case 'user':
case 'custom': {
const msgObj = msg as unknown as Record<string, unknown>
return (
<div key={msg.id} className="flex justify-end w-full">
<div className="bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[85%] text-sm whitespace-pre-wrap shadow-xs break-words">
{getMessageText(msgObj.content)}
if (msg.role === 'custom' && msgObj.customType === 'context_display_info') {
const details = msgObj.details as
| { assets?: Array<{ id: string; name: string; type: string }> }
| undefined
const assets = details?.assets || []
if (assets.length === 0) return null
return (
<div
key={msg.id}
className="text-xs text-muted-foreground bg-muted/40 p-2.5 rounded-lg border border-border/50 space-y-1 my-1"
>
<div className="font-semibold">{m.assets_added_to_context()}</div>
<ul className="list-disc list-inside space-y-0.5">
{assets.map((asset) => (
<li key={asset.id} className="truncate">
{asset.name} <span className="text-muted-foreground/70">({asset.type})</span>
</li>
))}
</ul>
</div>
)
}
if (msg.role === 'user' || msgObj.customType === 'shumai_message') {
const details = msgObj.details as ShumaiMessageContext | undefined
const referencedAssets = details?.referencedAssets || []
const attachedFiles = details?.attachedFiles || []
const position = details?.position
const hasAnnotations =
details?.annotation || (details?.annotations && details.annotations.length > 0)
const isCurrentAssetMatch =
!details?.currentAsset?.id ||
(contextAssetId && details.currentAsset.id === contextAssetId) ||
(file?.id && details.currentAsset.id === file.id)
const isSelected = selectedMessageId === msg.id
let timeStr = ''
if (position?.type === 'time') {
if (formatTimestamp) {
timeStr = formatTimestamp(position.seconds)
} else if (frameRate) {
const frameIndex = Math.round(position.seconds * frameRate)
timeStr = formatTimecode(frameIndex, frameRate, videoTimeDisplayMode, startTimecode)
} else {
const mins = Math.floor(position.seconds / 60)
const secs = Math.floor(position.seconds % 60)
timeStr = `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}
} else if (position?.type === 'page') {
timeStr = m.page_prefix({ page: position.page })
}
const messageText = getMessageText(msgObj.content)
const hasAttachmentsOrAssets = attachedFiles.length > 0 || referencedAssets.length > 0
const handleCardClick = () => {
if (isCurrentAssetMatch && onSelectMessage) {
onSelectMessage(msg)
}
}
return (
<div
key={msg.id}
onClick={handleCardClick}
className={cn(
'flex flex-col items-end w-full group transition-all duration-150',
isCurrentAssetMatch && (hasAnnotations || position) && 'cursor-pointer',
)}
>
<div
className={cn(
'bg-primary text-primary-foreground rounded-lg px-3 py-2 text-sm whitespace-pre-wrap shadow-xs break-words transition-all border',
hasAttachmentsOrAssets ? 'w-full' : 'max-w-[85%]',
isSelected ? 'border-blue-500 dark:border-blue-400' : 'border-transparent',
)}
>
<div className="text-sm leading-relaxed whitespace-pre-wrap break-words">
{hasAnnotations && (
<span
className="inline-flex items-center align-middle mr-1.5 p-0.5 rounded bg-primary-foreground/20 text-primary-foreground"
title={m.contains_drawing_annotations()}
>
<DrawAnnotation className="w-3.5 h-3.5" />
</span>
)}
{position && (
<span className="inline-flex items-center align-middle mr-1.5 px-1.5 py-0.5 rounded text-xs font-mono font-bold bg-primary-foreground/20 text-primary-foreground">
{timeStr}
</span>
)}
{messageText && <span>{messageText}</span>}
</div>
{attachedFiles.length > 0 && (
<div className="mt-2.5 w-full">
<div className="text-xs font-medium text-primary-foreground/70 mb-1">
{m.attachments()}
</div>
<div className="flex flex-col gap-1.5 w-full">
{attachedFiles.map((att) => {
const name = att.name || 'file'
const isImage =
isImageFileName(name) ||
att.mediaType === 'image' ||
att.mimeType?.startsWith('image/')
return (
<div
key={att.id}
className={cn(
'group/att relative flex items-center w-full max-w-full rounded-lg border border-primary-foreground/15 bg-primary-foreground/10 hover:bg-primary-foreground/15 transition-colors overflow-hidden',
isImage ? 'h-18 p-1.5 gap-2.5 cursor-pointer' : 'h-9 px-2.5 gap-2.5',
)}
onClick={(e) => {
e.stopPropagation()
if (att.url) {
if (isImage) {
setPreviewImage({ url: att.url, name })
} else {
window.open(att.url, '_blank', 'noreferrer')
}
}
}}
>
{isImage && att.url ? (
<div className="h-full aspect-square rounded-md overflow-hidden bg-black/20 shrink-0">
<img
src={att.url}
alt={name}
className="w-full h-full object-cover group-hover/att:scale-105 transition-transform duration-200"
/>
</div>
) : (
<FileIcon className="w-4 h-4 text-primary-foreground/70 shrink-0" />
)}
<div className="min-w-0 flex-1 overflow-hidden">
<p
className="text-xs font-medium text-primary-foreground truncate block w-full"
title={name}
>
{name}
</p>
</div>
{att.url && (
<a
href={att.url}
target="_blank"
rel="noreferrer"
download={name}
className="p-1 text-primary-foreground/70 hover:text-primary-foreground shrink-0 rounded-md hover:bg-primary-foreground/20 transition-colors opacity-0 group-hover/att:opacity-100"
onClick={(e) => e.stopPropagation()}
title={m.download()}
>
<Download className="w-3.5 h-3.5" />
</a>
)}
</div>
)
})}
</div>
</div>
)}
{referencedAssets.length > 0 && (
<div className="mt-2.5 w-full">
<div className="text-xs font-medium text-primary-foreground/70 mb-1">
{m.assets()}
</div>
<div className="flex flex-col gap-1.5 w-full">
{referencedAssets.map((asset) => (
<div
key={asset.id}
className="flex items-center justify-between w-full h-9 px-2.5 rounded-lg border border-primary-foreground/15 bg-primary-foreground/10 hover:bg-primary-foreground/15 transition-colors overflow-hidden"
>
<div className="flex items-center gap-2.5 min-w-0 flex-1">
{asset.type === 'folder' ? (
<Folder className="w-4 h-4 text-primary-foreground/70 shrink-0" />
) : (
<FileIcon className="w-4 h-4 text-primary-foreground/70 shrink-0" />
)}
<span
className="text-xs font-medium truncate text-primary-foreground"
title={asset.name}
>
{asset.name}
</span>
</div>
<span className="text-[10px] text-primary-foreground/60 uppercase shrink-0 font-mono ml-2">
{asset.type}
</span>
</div>
))}
</div>
</div>
)}
</div>
</div>
)
}
const systemContent = msgObj.content || ''
return (
<div
key={msg.id}
className="text-center text-xs text-muted-foreground italic bg-muted/20 py-1.5 rounded"
>
{getMessageText(systemContent)}
</div>
)
}
case 'assistant': {
const msgObj = msg as unknown as Record<string, unknown>
const content = msgObj.content as unknown[]
if (!content) return null
const renderedBlocks: React.ReactNode[] = []
content.forEach((block: unknown, idx: number) => {
if (!block || typeof block !== 'object') return
const b = block as unknown as Record<string, unknown>
switch (b.type) {
case 'text': {
const text = b.text
@@ -357,9 +563,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
}
}
})
if (renderedBlocks.length === 0) return null
let shouldShowFooter = false
if (content.length > 0) {
const lastBlock = content[content.length - 1]
@@ -372,7 +576,6 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
}
}
}
return (
<div key={msg.id} className="flex flex-col w-full space-y-1">
<div className="space-y-2 w-full">{renderedBlocks}</div>
@@ -384,7 +587,6 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
</div>
)
}
case 'toolResult': {
return (
<div
@@ -397,58 +599,8 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
</div>
)
}
case 'thinking_level_change':
case 'custom': {
case 'thinking_level_change': {
const msgObj = msg as unknown as Record<string, unknown>
if (msgObj.customType === 'shumai_message') {
const details = msgObj.details as ShumaiMessageContext | undefined
const referencedAssets = details?.referencedAssets || []
return (
<div key={msg.id} className="flex flex-col items-end w-full space-y-1">
{referencedAssets.length > 0 && (
<div className="text-xs text-muted-foreground bg-muted/40 p-2.5 rounded-lg border border-border/50 space-y-1 my-1 w-full">
<div className="font-semibold">{m.assets_added_to_context()}</div>
<ul className="list-disc list-inside space-y-0.5">
{referencedAssets.map((asset) => (
<li key={asset.id} className="truncate">
{asset.name}{' '}
<span className="text-muted-foreground/70">({asset.type})</span>
</li>
))}
</ul>
</div>
)}
<div className="bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[85%] text-sm whitespace-pre-wrap shadow-xs break-words">
{getMessageText(msgObj.content)}
</div>
</div>
)
}
if (msgObj.customType === 'context_display_info') {
const details = msgObj.details as
| { assets?: Array<{ id: string; name: string; type: string }> }
| undefined
const assets = details?.assets || []
if (assets.length === 0) return null
return (
<div
key={msg.id}
className="text-xs text-muted-foreground bg-muted/40 p-2.5 rounded-lg border border-border/50 space-y-1 my-1"
>
<div className="font-semibold">{m.assets_added_to_context()}</div>
<ul className="list-disc list-inside space-y-0.5">
{assets.map((asset) => (
<li key={asset.id} className="truncate">
{asset.name} <span className="text-muted-foreground/70">({asset.type})</span>
</li>
))}
</ul>
</div>
)
}
const systemContent = msgObj.content || ''
return (
<div
@@ -459,7 +611,6 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
</div>
)
}
default:
return null
}
@@ -477,92 +628,106 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
<div className="bg-background/95 text-foreground px-4 py-3 rounded-xl border border-border/80 flex flex-col items-center gap-2 shadow-lg max-w-[80%] animate-in zoom-in-95 duration-150">
<Bot className="h-6 w-6 text-primary animate-bounce" />
<span className="text-sm font-semibold text-foreground">
{m.chatbot_drag_drop_hint() || 'Drop assets here'}
{m.chatbot_drag_drop_hint()}
</span>
</div>
</div>
)}
{/* Header section */}
<div className="flex items-center justify-between p-4 pt-[0.7rem] flex-shrink-0">
{isHistoryMode ? (
<>
<div className="flex items-center gap-2 font-semibold">
<span>{m.history()}</span>
</div>
{/* Header */}
<div className="h-12 border-b border-border flex items-center justify-between px-4 flex-shrink-0 bg-background/50 backdrop-blur-sm">
<div className="flex items-center gap-2">
{isHistoryMode && (
<button
onClick={() => setIsHistoryMode(false)}
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
title="Close History"
className="p-1 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
title={m.back_to_chat()}
>
<ArrowLeft className="h-4 w-4" />
</button>
</>
) : (
<>
<div className="flex items-center gap-2 font-semibold">
<span>{m.shumai_agent()}</span>
</div>
<div className="flex items-center gap-1">
)}
<Bot className="h-5 w-5 text-primary" />
<span className="font-semibold text-sm">
{isHistoryMode ? m.history() : m.shumai_agent()}
</span>
</div>
<div className="flex items-center gap-1">
{!isHistoryMode ? (
<>
<button
onClick={startNewSession}
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
title={m.new_chat()}
>
<Plus className="h-4 w-4" />
</button>
<button
onClick={() => setIsHistoryMode(true)}
className="p-1.5 hover:bg-accent rounded-md text-muted-foreground hover:text-foreground transition-colors"
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
title={m.history()}
>
<History className="h-4 w-4" />
</button>
</div>
</>
)}
</>
) : (
<button
onClick={() => {
startNewSession()
setIsHistoryMode(false)
}}
className="flex items-center gap-1 text-xs bg-primary text-primary-foreground px-2.5 py-1 rounded-md hover:bg-primary/90 transition-colors shadow-xs cursor-pointer"
>
<Plus className="h-3.5 w-3.5" />
<span>{m.new_chat()}</span>
</button>
)}
</div>
</div>
{/* Main body view */}
{/* Body */}
{isHistoryMode ? (
<ScrollArea className="flex-1 p-4 min-h-0">
<ScrollArea className="flex-1 p-3">
{historySessions.length === 0 ? (
<div className="flex flex-col items-center justify-center h-48 text-muted-foreground p-4 text-center">
<History className="h-8 w-8 mb-2 opacity-50 text-muted-foreground" />
<p className="text-sm">{m.no_history_sessions()}</p>
<div className="text-center text-xs text-muted-foreground py-8">
{m.no_history_sessions()}
</div>
) : (
<div className="space-y-2 pb-4">
{historySessions.map((sess) => {
const isActive = sess.id === currentSessionId
<div className="space-y-1">
{historySessions.map((session) => {
const isCurrent = session.id === currentSessionId
return (
<div
key={sess.id}
key={session.id}
onClick={() => {
if (teamId) {
loadSession(teamId, session.id)
setIsHistoryMode(false)
}
}}
className={cn(
'group relative flex items-center justify-between p-3 border rounded-lg transition-all cursor-pointer bg-card',
isActive ? 'border-primary' : 'border-border hover:bg-accent/30',
'group flex items-center justify-between p-2.5 rounded-lg text-xs cursor-pointer transition-all border border-transparent',
isCurrent
? 'bg-accent/80 text-accent-foreground font-medium border-border/40'
: 'hover:bg-muted/60 text-muted-foreground hover:text-foreground',
)}
>
<div
onClick={() => teamId && loadSession(teamId, sess.id)}
className="flex-1 min-w-0 pr-6"
>
<div className="text-sm font-semibold text-foreground truncate">
{sess.name || m.new_chat()}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{formatTimeAgo(sess.createdAt)}
</div>
<div className="flex flex-col min-w-0 pr-2">
<span className="truncate text-foreground font-medium text-xs">
{session.name || m.untitled_session()}
</span>
<span className="text-[10px] text-muted-foreground">
{formatTimeAgo(session.updatedAt)}
</span>
</div>
<button
onClick={(e) => {
e.stopPropagation()
if (teamId && confirm(m.delete_session_confirm())) {
deleteSession(teamId, sess.id)
if (teamId && window.confirm(m.delete_session_confirm())) {
deleteSession(teamId, session.id)
}
}}
className="absolute right-3 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity text-muted-foreground hover:text-destructive p-1 rounded hover:bg-muted"
title="Delete Session"
className="opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity text-muted-foreground hover:text-destructive p-1 rounded hover:bg-muted cursor-pointer"
title={m.delete_session()}
>
<Trash2 className="h-4 w-4" />
</button>
@@ -574,7 +739,6 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
</ScrollArea>
) : (
<>
{/* Active Chat view */}
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4 min-h-0 [&>div>div]:!block">
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-48 border-2 border-dashed border-border rounded-lg text-muted-foreground p-4 text-center">
@@ -594,7 +758,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
).customType === 'shumai_message') && (
<div className="flex items-center gap-1.5 text-xs text-muted-foreground italic">
<Loader2 className="h-3 w-3 animate-spin text-primary" />
<span>Thinking...</span>
<span>{m.thinking_status()}</span>
</div>
)}
<div ref={messagesEndRef} />
@@ -602,62 +766,74 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
)}
</ScrollArea>
{/* Input Area (nested inside the border exactly like comment input) */}
<div className="p-2 flex-shrink-0 bg-background">
<div className="relative flex flex-col w-full border border-foreground/20 rounded-2xl shadow-xs transition-all duration-200 focus-within:ring-2 focus-within:ring-primary focus-within:border-transparent bg-background overflow-hidden">
{/* Context assets list at the top inside the border */}
{chatAssets.length > 0 && (
<div className="flex flex-col gap-1.5 min-h-0 max-h-[160px] overflow-y-auto border-b border-border bg-muted/5 p-3 divide-y divide-border/50">
{chatAssets.map((asset) => (
<div
key={asset.id}
className="flex items-center justify-between py-1.5 text-xs group"
>
<div className="flex items-baseline gap-1.5 min-w-0 pr-2">
<span className="truncate font-medium text-foreground">{asset.name}</span>
<span className="text-[9px] text-muted-foreground uppercase flex-shrink-0">
{asset.type}
</span>
</div>
<button
onClick={() => removeAsset(asset.id)}
className="text-muted-foreground hover:text-destructive transition-colors p-0.5"
title={m.remove_from_context()}
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
))}
</div>
)}
{/* Textarea inside the border */}
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type a message..."
rows={2}
className="w-full bg-transparent border-none focus:ring-0 focus:outline-hidden resize-none min-h-[44px] max-h-[120px] px-3 py-2 text-sm focus-visible:outline-hidden focus:ring-transparent focus:border-transparent focus-visible:ring-0"
disabled={isStreaming}
/>
{/* Bottom row inside the border containing the agent selector and send button */}
<div className="flex justify-between items-center px-3 pb-2 pt-1">
{/* Agent selector */}
<div className="flex items-center gap-1.5 min-w-0 max-w-[70%]">
<ChatInput
projectId={projectId}
value={inputText}
onChangeText={setInputText}
placeholder={m.type_a_message()}
disabled={!selectedAgentId || !teamId}
isStreaming={isStreaming}
onAbort={() => {
if (teamId) {
abortActiveSession(teamId)
}
}}
allowMentions={false}
allowAttachments={true}
workspaceAssets={chatAssets}
onRemoveWorkspaceAsset={removeAsset}
allowMarkup={true}
canMarkup={!!file && ['image', 'video', 'pdf'].includes(file.proxyType || '')}
markupDisabledTooltip={
!file ? m.open_file_to_add_markup() : m.markup_not_supported_for_this_file()
}
allowTimestamp={file?.proxyType === 'video' || file?.proxyType === 'pdf'}
currentTime={currentTime}
frameRate={frameRate || file?.media?.metadata?.frameRate || 30}
startTimecode={startTimecode || file?.media?.metadata?.startTimecode}
formatTimestamp={
formatTimestamp ||
(file?.proxyType === 'pdf'
? (sec: number) => m.page_prefix({ page: Math.round(sec) })
: undefined)
}
onTyping={onTyping}
onSendMessage={(
text,
attachmentIds,
annotations,
_replyToId,
second,
attachedFilesMeta,
) => {
if (!teamId) return
sendMessage(
teamId,
text,
projectId,
contextAssetId,
handleAssetMutation,
attachmentIds,
annotations,
second,
attachedFilesMeta,
)
}}
bottomLeftExtra={
<div className="flex items-center gap-1.5 min-w-0 max-w-full">
{chatAgents.length > 0 ? (
<Select
value={selectedAgentId || ''}
onValueChange={(val) => setSelectedAgentId(val)}
disabled={isStreaming}
>
<SelectTrigger className="h-8 border-none bg-transparent hover:bg-muted text-muted-foreground hover:text-foreground focus:ring-0 focus:ring-offset-0 px-2 py-0 gap-1.5 text-xs shrink-0 select-none shadow-none max-w-full">
<SelectTrigger className="h-8 border-none bg-transparent hover:bg-muted text-muted-foreground hover:text-foreground focus:ring-0 focus:ring-offset-0 px-2 py-0 gap-1.5 text-xs shrink-0 select-none shadow-none max-w-full cursor-pointer">
<SelectValue placeholder={m.select_agent()} />
</SelectTrigger>
<SelectContent>
{chatAgents.map((agent) => (
<SelectItem key={agent.id} value={agent.id}>
<SelectItem key={agent.id} value={agent.id} className="cursor-pointer">
<div className="flex items-center gap-2">
{agent.avatar ? (
<img
@@ -680,40 +856,36 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp
</div>
)}
</div>
{isStreaming ? (
<button
onClick={() => {
if (teamId) {
abortActiveSession(teamId)
}
}}
className="p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm bg-destructive text-destructive-foreground hover:bg-destructive/90 transform hover:-translate-y-0.5"
title="Stop generation"
>
<div className="h-4 w-4 flex items-center justify-center">
<div className="h-3 w-3 bg-current rounded-[2px] bg-white" />
</div>
</button>
) : (
<button
onClick={handleSend}
disabled={!inputText.trim() || !selectedAgentId}
className={cn(
'p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm',
inputText.trim() && selectedAgentId
? 'bg-primary text-primary-foreground hover:bg-primary/95 transform hover:-translate-y-0.5'
: 'bg-muted text-muted-foreground cursor-not-allowed opacity-50',
)}
>
<ArrowUp className="h-4 w-4" />
</button>
)}
</div>
</div>
}
/>
</div>
</>
)}
{previewImage && (
<div
className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200"
onClick={() => setPreviewImage(null)}
>
<button className="absolute top-4 right-4 text-white/70 hover:text-white hover:bg-white/20 rounded-full p-2 transition-colors z-50 cursor-pointer">
<XIcon className="w-8 h-8" />
</button>
<div className="w-full h-full flex items-center justify-center p-2">
<img
src={previewImage.url}
alt={previewImage.name}
className="max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out"
onClick={(e) => {
e.stopPropagation()
setPreviewImage(null)
}}
/>
</div>
<div className="absolute bottom-6 text-white text-sm font-medium bg-black/50 px-4 py-2 rounded-full backdrop-blur-sm">
{previewImage.name}
</div>
</div>
)}
</div>
)
}