mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 16:28:42 +00:00
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:
@@ -811,7 +811,12 @@ export async function initializeAgentSessionActivity(params: {
|
||||
const commentDetails: ShumaiMessageContext = {
|
||||
...(userObj ? { user: userObj } : {}),
|
||||
...(position ? { position } : {}),
|
||||
...(annotation ? { annotation: true } : {}),
|
||||
...(annotation
|
||||
? {
|
||||
annotation: true,
|
||||
annotations: c.annotation as unknown as ShumaiMessageContext['annotations'],
|
||||
}
|
||||
: {}),
|
||||
...(attachedFiles.length > 0 ? { attachedFiles } : {}),
|
||||
}
|
||||
|
||||
@@ -1190,6 +1195,7 @@ export async function getAssetActivity(assetId: string) {
|
||||
},
|
||||
})
|
||||
|
||||
let resolvedAsset = asset
|
||||
if (asset && asset.type === AssetType.version_stack) {
|
||||
const latestVersion = await prisma.asset.findFirst({
|
||||
where: { parentId: asset.id, isDeleted: false },
|
||||
@@ -1205,18 +1211,36 @@ export async function getAssetActivity(assetId: string) {
|
||||
})
|
||||
|
||||
if (latestVersion) {
|
||||
return {
|
||||
resolvedAsset = {
|
||||
...latestVersion,
|
||||
project: latestVersion.project ?? asset.project,
|
||||
}
|
||||
} as typeof asset
|
||||
}
|
||||
}
|
||||
|
||||
return asset
|
||||
if (!resolvedAsset) return null
|
||||
|
||||
let url: string | undefined
|
||||
if (resolvedAsset.storageKey?.key) {
|
||||
try {
|
||||
url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
resolvedAsset.storageKey.key,
|
||||
'GET',
|
||||
)
|
||||
} catch {
|
||||
// Ignore presign errors
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...resolvedAsset,
|
||||
url,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCommentActivity(commentId: string) {
|
||||
return prisma.assetComment.findUnique({
|
||||
const comment = await prisma.assetComment.findUnique({
|
||||
where: { id: commentId },
|
||||
include: {
|
||||
attachments: {
|
||||
@@ -1224,6 +1248,34 @@ export async function getCommentActivity(commentId: string) {
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!comment) return null
|
||||
|
||||
const attachmentsWithUrl = await Promise.all(
|
||||
comment.attachments.map(async (att) => {
|
||||
let url: string | undefined
|
||||
if (att.asset?.storageKey?.key) {
|
||||
try {
|
||||
url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
att.asset.storageKey.key,
|
||||
'GET',
|
||||
)
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
return {
|
||||
...att,
|
||||
asset: att.asset ? { ...att.asset, url } : null,
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
...comment,
|
||||
attachments: attachmentsWithUrl,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProjectAutofillFieldsActivity(projectId: string) {
|
||||
|
||||
@@ -735,4 +735,35 @@ describe('Agent Chat Workflow', () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should include annotations and second in direct chat messageContext', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: {
|
||||
prompt: 'Look at the highlighted zone',
|
||||
agentId: 'b1',
|
||||
sessionId: 'session-markup-1',
|
||||
second: 14.2,
|
||||
annotations: [{ type: 'rectangle', x: 20, y: 30, width: 40, height: 50 }],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
messageContext: expect.objectContaining({
|
||||
position: { type: 'time', seconds: 14.2 },
|
||||
annotations: [{ type: 'rectangle', x: 20, y: 30, width: 40, height: 50 }],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -61,6 +61,8 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
let commentAnnotation = false
|
||||
let commentCreatorId: string | undefined
|
||||
|
||||
let commentAnnotations: unknown[] | undefined
|
||||
|
||||
if (userCommentId) {
|
||||
userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
if (!userComment) {
|
||||
@@ -77,6 +79,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
userComment.annotation.length > 0
|
||||
) {
|
||||
commentAnnotation = true
|
||||
commentAnnotations = userComment.annotation
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
@@ -101,6 +104,17 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
} else {
|
||||
prompt = payload.agent?.prompt || ''
|
||||
attachmentImageUrls = payload.agent?.imageUrls || []
|
||||
if (payload.agent?.second !== null && payload.agent?.second !== undefined) {
|
||||
commentTimestamp = payload.agent.second
|
||||
}
|
||||
if (
|
||||
payload.agent?.annotations &&
|
||||
Array.isArray(payload.agent.annotations) &&
|
||||
payload.agent.annotations.length > 0
|
||||
) {
|
||||
commentAnnotation = true
|
||||
commentAnnotations = payload.agent.annotations
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Get Asset
|
||||
@@ -181,6 +195,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
mediaType: attProxyType as ShumaiAttachedFileContext['mediaType'],
|
||||
mimeType: att.asset.mediaType || undefined,
|
||||
path: filePath || undefined,
|
||||
url: (att.asset as { url?: string }).url || undefined,
|
||||
})
|
||||
attachedAssets.push({ id: att.asset.id, name: att.asset.name, type: att.asset.type })
|
||||
}
|
||||
@@ -205,6 +220,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
mediaType: fileProxyType as ShumaiAttachedFileContext['mediaType'],
|
||||
mimeType: file.mediaType || undefined,
|
||||
path: filePath || undefined,
|
||||
url: (file as { url?: string }).url || undefined,
|
||||
})
|
||||
attachedAssets.push({ id: file.id, name: file.name, type: file.type })
|
||||
}
|
||||
@@ -233,6 +249,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
mediaType: refProxyType as ShumaiAttachedFileContext['mediaType'],
|
||||
mimeType: referencedAsset.mediaType || undefined,
|
||||
path: filePath || undefined,
|
||||
url: (referencedAsset as { url?: string }).url || undefined,
|
||||
})
|
||||
attachedAssets.push({
|
||||
id: referencedAsset.id,
|
||||
@@ -286,7 +303,12 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
: {}),
|
||||
currentAsset: currentAssetContext,
|
||||
...(mediaPosition ? { position: mediaPosition } : {}),
|
||||
...(commentAnnotation ? { annotation: true } : {}),
|
||||
...(commentAnnotation
|
||||
? {
|
||||
annotation: true,
|
||||
annotations: commentAnnotations as ShumaiMessageContext['annotations'],
|
||||
}
|
||||
: {}),
|
||||
...(attachedFiles.length > 0 ? { attachedFiles } : {}),
|
||||
...(referencedAssets.length > 0 ? { referencedAssets } : {}),
|
||||
}
|
||||
|
||||
@@ -148,6 +148,48 @@ describe('Chat API', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('accepts chat request with annotations, second, and attachmentIds', async () => {
|
||||
vi.mocked(chatService.startOrContinueChat).mockResolvedValue({
|
||||
sessionId: 'session1',
|
||||
taskId: 'task1',
|
||||
})
|
||||
|
||||
vi.mocked(chatService.getNewSessionMessages).mockResolvedValue({
|
||||
messages: [],
|
||||
lastEntryId: null,
|
||||
})
|
||||
|
||||
vi.mocked(chatService.getChatWorkflowStatus).mockResolvedValue({
|
||||
status: 'completed',
|
||||
output: {},
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
agentId: 'agent1',
|
||||
textPrompt: 'Review annotation',
|
||||
attachedFiles: ['att1'],
|
||||
annotations: [{ type: 'rectangle', x: 10, y: 20 }],
|
||||
second: 5.5,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(chatService.startOrContinueChat).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'user1' }),
|
||||
'team1',
|
||||
expect.objectContaining({
|
||||
agentId: 'agent1',
|
||||
textPrompt: 'Review annotation',
|
||||
attachedFiles: ['att1'],
|
||||
annotations: [{ type: 'rectangle', x: 10, y: 20 }],
|
||||
second: 5.5,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('sends ping keep-alive SSE events when there are no new messages', async () => {
|
||||
vi.mocked(chatService.startOrContinueChat).mockResolvedValue({
|
||||
sessionId: 'session1',
|
||||
|
||||
@@ -988,5 +988,29 @@ describe('ChatService', () => {
|
||||
const msg2 = mapEntryToMessage(emptyEntry)
|
||||
expect(msg2).toBeNull()
|
||||
})
|
||||
|
||||
it('should forward annotations and second to workflow task payload', async () => {
|
||||
const { user, team, project } = await setupBasicData()
|
||||
|
||||
const { sessionId, taskId } = await chatService.startOrContinueChat(user, team.id, {
|
||||
agentId: 'test-agent-id',
|
||||
textPrompt: 'Check out this area',
|
||||
projectId: project.id,
|
||||
annotations: [{ type: 'rectangle', x: 10, y: 20, width: 30, height: 40 }],
|
||||
second: 8.5,
|
||||
})
|
||||
|
||||
expect(sessionId).toBeDefined()
|
||||
expect(taskId).toBeDefined()
|
||||
|
||||
const task = await prisma.workflowTask.findUnique({
|
||||
where: { id: taskId },
|
||||
})
|
||||
expect(task).toBeDefined()
|
||||
expect(task?.payload?.agent?.second).toBe(8.5)
|
||||
expect(task?.payload?.agent?.annotations).toEqual([
|
||||
{ type: 'rectangle', x: 10, y: 20, width: 30, height: 40 },
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -199,6 +199,8 @@ export class ChatService {
|
||||
sessionId: passedSessionId,
|
||||
contextAssetId,
|
||||
projectId: passedProjectId,
|
||||
second,
|
||||
annotations,
|
||||
} = req
|
||||
|
||||
// 1. Permissions verification
|
||||
@@ -401,6 +403,8 @@ export class ChatService {
|
||||
userId: user.id,
|
||||
isNewChat: !passedSessionId,
|
||||
hasAssetChanged,
|
||||
second: second ?? undefined,
|
||||
annotations: annotations ?? undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -305,6 +305,8 @@ declare global {
|
||||
assetIds?: string[]
|
||||
isNewChat?: boolean
|
||||
hasAssetChanged?: boolean
|
||||
second?: number | null
|
||||
annotations?: Record<string, unknown>[]
|
||||
context?: import('@shumai/dtos').ShumaiMessageContext
|
||||
}
|
||||
|
||||
|
||||
@@ -10,15 +10,19 @@ export const chatRequestSchema = z
|
||||
sessionId: z.string().optional(), // ID of existing session (to continue)
|
||||
contextAssetId: z.string().optional(), // Active page context asset ID
|
||||
projectId: z.string().optional(), // Target project ID
|
||||
second: z.number().nullable().optional(),
|
||||
annotations: z.array(z.record(z.string(), z.unknown())).optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
const hasPrompt = data.textPrompt && data.textPrompt.trim().length > 0
|
||||
const hasFiles = data.attachedFiles && data.attachedFiles.length > 0
|
||||
const hasAssets = data.assetIds && data.assetIds.length > 0
|
||||
if (!hasPrompt && !hasFiles && !hasAssets) {
|
||||
const hasAnnotations = data.annotations && data.annotations.length > 0
|
||||
if (!hasPrompt && !hasFiles && !hasAssets && !hasAnnotations) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'At least one of textPrompt, attachedFiles, or assetIds must be provided.',
|
||||
message:
|
||||
'At least one of textPrompt, attachedFiles, assetIds, or annotations must be provided.',
|
||||
path: ['textPrompt'],
|
||||
})
|
||||
}
|
||||
@@ -63,6 +67,7 @@ export const shumaiAttachedFileContextSchema = z.object({
|
||||
mediaType: z.enum(['image', 'video', 'pdf', 'audio', 'other']).optional(),
|
||||
mimeType: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
})
|
||||
|
||||
export type ShumaiAttachedFileContext = z.infer<typeof shumaiAttachedFileContextSchema>
|
||||
@@ -85,6 +90,7 @@ export const shumaiMessageContextSchema = z.object({
|
||||
currentAsset: shumaiAssetContextSchema.optional(),
|
||||
position: shumaiMediaPositionSchema.optional(),
|
||||
annotation: z.boolean().optional(),
|
||||
annotations: z.array(z.record(z.string(), z.unknown())).optional(),
|
||||
attachedFiles: z.array(shumaiAttachedFileContextSchema).optional(),
|
||||
referencedAssets: z.array(shumaiAttachedFileContextSchema).optional(),
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -662,6 +662,7 @@
|
||||
|
||||
"select_source_folder": "Select Source Folder",
|
||||
"assets": "Assets",
|
||||
"attachments": "Attachments",
|
||||
"filter": "Filter",
|
||||
"project_members": "Project Members",
|
||||
|
||||
@@ -916,6 +917,9 @@
|
||||
"enable_timestamp": "Enable Timestamp",
|
||||
"attach_files": "Attach files",
|
||||
"toggle_annotation": "Toggle Annotation",
|
||||
"markup_not_supported_for_this_file": "Markup is not supported for this file type",
|
||||
"open_file_to_add_markup": "Open a supported file to add markup",
|
||||
"type_a_message": "Type a message...",
|
||||
|
||||
"loop": "Loop",
|
||||
"click_toggle_time_frames": "Click to toggle Time/Frames",
|
||||
@@ -1313,5 +1317,10 @@
|
||||
"playback_speed": "Playback Speed",
|
||||
"settings": "Settings",
|
||||
"failed_to_post_comment": "Failed to post comment",
|
||||
"entry_id": "Entry ID"
|
||||
"entry_id": "Entry ID",
|
||||
"back_to_chat": "Back to Chat",
|
||||
"delete_session": "Delete Session",
|
||||
"thinking_status": "Thinking...",
|
||||
"contains_drawing_annotations": "Contains drawing annotations",
|
||||
"page_prefix": "Page {page}"
|
||||
}
|
||||
|
||||
@@ -662,6 +662,7 @@
|
||||
|
||||
"select_source_folder": "选择来源文件夹",
|
||||
"assets": "资源",
|
||||
"attachments": "附件",
|
||||
"filter": "筛选",
|
||||
"project_members": "项目成员",
|
||||
|
||||
@@ -916,6 +917,9 @@
|
||||
"enable_timestamp": "启用时间戳",
|
||||
"attach_files": "附加文件",
|
||||
"toggle_annotation": "切换标注",
|
||||
"markup_not_supported_for_this_file": "此文件类型不支持标注",
|
||||
"open_file_to_add_markup": "打开支持的文件以添加标注",
|
||||
"type_a_message": "输入消息...",
|
||||
|
||||
"loop": "循环",
|
||||
"click_toggle_time_frames": "点击切换时间/帧",
|
||||
@@ -1313,5 +1317,10 @@
|
||||
"playback_speed": "播放速度",
|
||||
"settings": "设置",
|
||||
"failed_to_post_comment": "发送评论失败",
|
||||
"entry_id": "条目 ID"
|
||||
"entry_id": "条目 ID",
|
||||
"back_to_chat": "返回聊天",
|
||||
"delete_session": "删除会话",
|
||||
"thinking_status": "思考中...",
|
||||
"contains_drawing_annotations": "包含标注绘图",
|
||||
"page_prefix": "第 {page} 页"
|
||||
}
|
||||
|
||||
+8
@@ -632,6 +632,7 @@ export * from "./count_overflow_assets.js";
|
||||
export * from "./count_overflow_folders.js";
|
||||
export * from "./select_source_folder.js";
|
||||
export * from "./assets.js";
|
||||
export * from "./attachments.js";
|
||||
export * from "./filter.js";
|
||||
export * from "./project_members.js";
|
||||
export * from "./upload_file.js";
|
||||
@@ -868,6 +869,9 @@ export * from "./disable_timestamp.js";
|
||||
export * from "./enable_timestamp.js";
|
||||
export * from "./attach_files.js";
|
||||
export * from "./toggle_annotation.js";
|
||||
export * from "./markup_not_supported_for_this_file.js";
|
||||
export * from "./open_file_to_add_markup.js";
|
||||
export * from "./type_a_message.js";
|
||||
export * from "./loop.js";
|
||||
export * from "./click_toggle_time_frames.js";
|
||||
export * from "./quality.js";
|
||||
@@ -1251,4 +1255,8 @@ export * from "./timecode.js";
|
||||
export * from "./playback_speed.js";
|
||||
export * from "./failed_to_post_comment.js";
|
||||
export * from "./entry_id.js";
|
||||
export * from "./back_to_chat.js";
|
||||
export * from "./delete_session.js";
|
||||
export * from "./thinking_status.js";
|
||||
export * from "./page_prefix.js";
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
|
||||
+9
-1
@@ -634,6 +634,7 @@ export * from './count_overflow_assets.js'
|
||||
export * from './count_overflow_folders.js'
|
||||
export * from './select_source_folder.js'
|
||||
export * from './assets.js'
|
||||
export * from './attachments.js'
|
||||
export * from './filter.js'
|
||||
export * from './project_members.js'
|
||||
export * from './upload_file.js'
|
||||
@@ -870,6 +871,9 @@ export * from './disable_timestamp.js'
|
||||
export * from './enable_timestamp.js'
|
||||
export * from './attach_files.js'
|
||||
export * from './toggle_annotation.js'
|
||||
export * from './markup_not_supported_for_this_file.js'
|
||||
export * from './open_file_to_add_markup.js'
|
||||
export * from './type_a_message.js'
|
||||
export * from './loop.js'
|
||||
export * from './click_toggle_time_frames.js'
|
||||
export * from './quality.js'
|
||||
@@ -1252,4 +1256,8 @@ export * from './frames.js'
|
||||
export * from './timecode.js'
|
||||
export * from './playback_speed.js'
|
||||
export * from './failed_to_post_comment.js'
|
||||
export * from './entry_id.js'
|
||||
export * from './entry_id.js'
|
||||
export * from './back_to_chat.js'
|
||||
export * from './delete_session.js'
|
||||
export * from './thinking_status.js'
|
||||
export * from './page_prefix.js'
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Attachments" |
|
||||
*
|
||||
* @param {AttachmentsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const attachments: ((inputs?: AttachmentsInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<AttachmentsInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type AttachmentsInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} AttachmentsInputs */
|
||||
|
||||
const en_attachments = /** @type {(inputs: AttachmentsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Attachments`)
|
||||
};
|
||||
|
||||
const zh_attachments = /** @type {(inputs: AttachmentsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`附件`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Attachments" |
|
||||
*
|
||||
* @param {AttachmentsInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const attachments = /** @type {((inputs?: AttachmentsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<AttachmentsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_attachments(inputs)
|
||||
return zh_attachments(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Back to Chat" |
|
||||
*
|
||||
* @param {Back_To_ChatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const back_to_chat: ((inputs?: Back_To_ChatInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Back_To_ChatInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Back_To_ChatInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Back_To_ChatInputs */
|
||||
|
||||
const en_back_to_chat = /** @type {(inputs: Back_To_ChatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Back to Chat`)
|
||||
};
|
||||
|
||||
const zh_back_to_chat = /** @type {(inputs: Back_To_ChatInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`返回聊天`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Back to Chat" |
|
||||
*
|
||||
* @param {Back_To_ChatInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const back_to_chat = /** @type {((inputs?: Back_To_ChatInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Back_To_ChatInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_back_to_chat(inputs)
|
||||
return zh_back_to_chat(inputs)
|
||||
});
|
||||
@@ -10,7 +10,7 @@ const en_contains_drawing_annotations = /** @type {(inputs: Contains_Drawing_Ann
|
||||
};
|
||||
|
||||
const zh_contains_drawing_annotations = /** @type {(inputs: Contains_Drawing_AnnotationsInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`包含绘图标注`)
|
||||
return /** @type {LocalizedString} */ (`包含标注绘图`)
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Delete Session" |
|
||||
*
|
||||
* @param {Delete_SessionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_session: ((inputs?: Delete_SessionInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Delete_SessionInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Delete_SessionInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Delete_SessionInputs */
|
||||
|
||||
const en_delete_session = /** @type {(inputs: Delete_SessionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Delete Session`)
|
||||
};
|
||||
|
||||
const zh_delete_session = /** @type {(inputs: Delete_SessionInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`删除会话`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Delete Session" |
|
||||
*
|
||||
* @param {Delete_SessionInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const delete_session = /** @type {((inputs?: Delete_SessionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Delete_SessionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_delete_session(inputs)
|
||||
return zh_delete_session(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Markup is not supported for this file type" |
|
||||
*
|
||||
* @param {Markup_Not_Supported_For_This_FileInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const markup_not_supported_for_this_file: ((inputs?: Markup_Not_Supported_For_This_FileInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Markup_Not_Supported_For_This_FileInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Markup_Not_Supported_For_This_FileInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Markup_Not_Supported_For_This_FileInputs */
|
||||
|
||||
const en_markup_not_supported_for_this_file = /** @type {(inputs: Markup_Not_Supported_For_This_FileInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Markup is not supported for this file type`)
|
||||
};
|
||||
|
||||
const zh_markup_not_supported_for_this_file = /** @type {(inputs: Markup_Not_Supported_For_This_FileInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`此文件类型不支持标注`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Markup is not supported for this file type" |
|
||||
*
|
||||
* @param {Markup_Not_Supported_For_This_FileInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const markup_not_supported_for_this_file = /** @type {((inputs?: Markup_Not_Supported_For_This_FileInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Markup_Not_Supported_For_This_FileInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_markup_not_supported_for_this_file(inputs)
|
||||
return zh_markup_not_supported_for_this_file(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Open a supported file to add markup" |
|
||||
*
|
||||
* @param {Open_File_To_Add_MarkupInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const open_file_to_add_markup: ((inputs?: Open_File_To_Add_MarkupInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Open_File_To_Add_MarkupInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Open_File_To_Add_MarkupInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Open_File_To_Add_MarkupInputs */
|
||||
|
||||
const en_open_file_to_add_markup = /** @type {(inputs: Open_File_To_Add_MarkupInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Open a supported file to add markup`)
|
||||
};
|
||||
|
||||
const zh_open_file_to_add_markup = /** @type {(inputs: Open_File_To_Add_MarkupInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`打开支持的文件以添加标注`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Open a supported file to add markup" |
|
||||
*
|
||||
* @param {Open_File_To_Add_MarkupInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const open_file_to_add_markup = /** @type {((inputs?: Open_File_To_Add_MarkupInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Open_File_To_Add_MarkupInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_open_file_to_add_markup(inputs)
|
||||
return zh_open_file_to_add_markup(inputs)
|
||||
});
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Page {page}" |
|
||||
*
|
||||
* @param {Page_PrefixInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const page_prefix: ((inputs: Page_PrefixInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Page_PrefixInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Page_PrefixInputs = {
|
||||
page: NonNullable<unknown>;
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{ page: NonNullable<unknown> }} Page_PrefixInputs */
|
||||
|
||||
const en_page_prefix = /** @type {(inputs: Page_PrefixInputs) => LocalizedString} */ (i) => {
|
||||
return /** @type {LocalizedString} */ (`Page ${i?.page}`)
|
||||
};
|
||||
|
||||
const zh_page_prefix = /** @type {(inputs: Page_PrefixInputs) => LocalizedString} */ (i) => {
|
||||
return /** @type {LocalizedString} */ (`第 ${i?.page} 页`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Page {page}" |
|
||||
*
|
||||
* @param {Page_PrefixInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const page_prefix = /** @type {((inputs: Page_PrefixInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Page_PrefixInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_page_prefix(inputs)
|
||||
return zh_page_prefix(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Thinking..." |
|
||||
*
|
||||
* @param {Thinking_StatusInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const thinking_status: ((inputs?: Thinking_StatusInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Thinking_StatusInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Thinking_StatusInputs = {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Thinking_StatusInputs */
|
||||
|
||||
const en_thinking_status = /** @type {(inputs: Thinking_StatusInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Thinking...`)
|
||||
};
|
||||
|
||||
const zh_thinking_status = /** @type {(inputs: Thinking_StatusInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`思考中...`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Thinking..." |
|
||||
*
|
||||
* @param {Thinking_StatusInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const thinking_status = /** @type {((inputs?: Thinking_StatusInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Thinking_StatusInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_thinking_status(inputs)
|
||||
return zh_thinking_status(inputs)
|
||||
});
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Type a message..." |
|
||||
*
|
||||
* @param {Type_A_MessageInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const type_a_message: ((inputs?: Type_A_MessageInputs, options?: {
|
||||
locale?: "en" | "zh";
|
||||
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Type_A_MessageInputs, {
|
||||
locale?: "en" | "zh";
|
||||
}, {}>;
|
||||
export type LocalizedString = import("../runtime.js").LocalizedString;
|
||||
export type Type_A_MessageInputs = {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/* eslint-disable */
|
||||
import { getLocale, experimentalStaticLocale } from '../runtime.js';
|
||||
|
||||
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
|
||||
|
||||
/** @typedef {{}} Type_A_MessageInputs */
|
||||
|
||||
const en_type_a_message = /** @type {(inputs: Type_A_MessageInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`Type a message...`)
|
||||
};
|
||||
|
||||
const zh_type_a_message = /** @type {(inputs: Type_A_MessageInputs) => LocalizedString} */ () => {
|
||||
return /** @type {LocalizedString} */ (`输入消息...`)
|
||||
};
|
||||
|
||||
/**
|
||||
* | output |
|
||||
* | --- |
|
||||
* | "Type a message..." |
|
||||
*
|
||||
* @param {Type_A_MessageInputs} inputs
|
||||
* @param {{ locale?: "en" | "zh" }} options
|
||||
* @returns {LocalizedString}
|
||||
*/
|
||||
export const type_a_message = /** @type {((inputs?: Type_A_MessageInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Type_A_MessageInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
|
||||
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
|
||||
if (locale === "en") return en_type_a_message(inputs)
|
||||
return zh_type_a_message(inputs)
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import { useIsMobile } from '@/ui/hooks/use-mobile'
|
||||
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
|
||||
import { ResizeHandle } from '@/ui/components/resize-handle'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import { useChatbotStore } from '@/ui/stores/chatbot'
|
||||
import { useMemberStore } from '@/ui/stores/members'
|
||||
import { useTeamContextStore } from '@/ui/stores/team-context'
|
||||
@@ -42,7 +43,13 @@ import { Input } from '@/ui/components/ui/input'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import { toast } from 'sonner'
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
import type { AssetInfo, AssetInfoPaginatedList, CommentInfo } from '@shumai/dtos'
|
||||
import type {
|
||||
AssetInfo,
|
||||
AssetInfoPaginatedList,
|
||||
ChatMessage,
|
||||
CommentInfo,
|
||||
ShumaiMessageContext,
|
||||
} from '@shumai/dtos'
|
||||
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
@@ -482,6 +489,13 @@ function FileViewPage() {
|
||||
setAnnotations([])
|
||||
}, [compareActiveAsset?.id])
|
||||
|
||||
useEffect(() => {
|
||||
useAnnotationStore.getState().reset()
|
||||
useAnnotationStore.getState().setIsDrawing(false)
|
||||
setAnnotations([])
|
||||
setSelectedCommentId(null)
|
||||
}, [activeFileId])
|
||||
|
||||
if (isLoading && !fileData) {
|
||||
return <FileDetailSkeleton />
|
||||
}
|
||||
@@ -553,6 +567,39 @@ function FileViewPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleChatMessageSelect = (msg: ChatMessage) => {
|
||||
setSelectedCommentId(msg.id || null)
|
||||
const msgObj = msg as unknown as Record<string, unknown>
|
||||
const details = msgObj.details as ShumaiMessageContext | undefined
|
||||
const rawAnnotations = details?.annotations as Annotation[] | undefined
|
||||
if (rawAnnotations && rawAnnotations.length > 0) {
|
||||
setAnnotations(rawAnnotations)
|
||||
} else {
|
||||
setAnnotations([])
|
||||
}
|
||||
|
||||
const second =
|
||||
details?.position?.type === 'time'
|
||||
? details.position.seconds
|
||||
: details?.position?.type === 'page'
|
||||
? details.position.page
|
||||
: undefined
|
||||
|
||||
if (isCompareMode) {
|
||||
if (second !== undefined) {
|
||||
setSeekRequest({ second, nonce: Date.now() })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (second !== undefined) {
|
||||
mediaControllerRef.current?.seekTo(second)
|
||||
mediaControllerRef.current?.pause()
|
||||
} else if (rawAnnotations && rawAnnotations.length > 0) {
|
||||
mediaControllerRef.current?.pause()
|
||||
}
|
||||
}
|
||||
|
||||
const handlePlay = () => {
|
||||
setAnnotations([])
|
||||
setSelectedCommentId(null)
|
||||
@@ -679,7 +726,20 @@ function FileViewPage() {
|
||||
className="flex-shrink-0 bg-background flex flex-col"
|
||||
>
|
||||
{isChatbotOpen ? (
|
||||
<ChatbotSidebar projectId={projectId} contextAssetId={activeFileId} />
|
||||
<ChatbotSidebar
|
||||
projectId={projectId}
|
||||
contextAssetId={activeFileId}
|
||||
file={sidebarFile}
|
||||
currentTime={currentTime}
|
||||
frameRate={sidebarFile?.media?.metadata?.frameRate || 30}
|
||||
startTimecode={sidebarFile?.media?.metadata?.startTimecode}
|
||||
onTyping={() => {
|
||||
if (isCompareMode) return
|
||||
mediaControllerRef.current?.pause()
|
||||
}}
|
||||
onSelectMessage={handleChatMessageSelect}
|
||||
selectedMessageId={selectedCommentId}
|
||||
/>
|
||||
) : (
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
|
||||
@@ -181,9 +181,7 @@ describe('useChatbotStore', () => {
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
expect(stateWithOptimistic.messages).toHaveLength(1)
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-')
|
||||
expect((stateWithOptimistic.messages[0] as { content: unknown }).content).toEqual([
|
||||
{ type: 'text', text: 'hello' },
|
||||
])
|
||||
expect((stateWithOptimistic.messages[0] as { content: unknown }).content).toBe('hello')
|
||||
expect(stateWithOptimistic.isStreaming).toBe(true)
|
||||
|
||||
await sendPromise
|
||||
@@ -301,28 +299,24 @@ describe('useChatbotStore', () => {
|
||||
|
||||
const sendPromise = useChatbotStore.getState().sendMessage('team-123', 'hello', 'proj-123')
|
||||
|
||||
// 3. Verify that both the optimistic context message and user message are present immediately
|
||||
// 3. Verify that the optimistic message includes referencedAssets
|
||||
const stateWithOptimistic = useChatbotStore.getState()
|
||||
expect(stateWithOptimistic.messages).toHaveLength(2)
|
||||
expect(stateWithOptimistic.messages).toHaveLength(1)
|
||||
|
||||
// First message should be the optimistic context_display_info
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-context-')
|
||||
// Message should be the optimistic shumai_message with referencedAssets in details
|
||||
expect(stateWithOptimistic.messages[0].id).toContain('temp-')
|
||||
expect(stateWithOptimistic.messages[0].role).toBe('custom')
|
||||
expect((stateWithOptimistic.messages[0] as { customType?: string }).customType).toBe(
|
||||
'context_display_info',
|
||||
'shumai_message',
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((stateWithOptimistic.messages[0] as any).details).toEqual({
|
||||
assets: [{ id: 'asset-1', name: 'File 1.txt', type: 'file' }],
|
||||
})
|
||||
|
||||
// Second message should be the optimistic user message
|
||||
expect(stateWithOptimistic.messages[1].id).toContain('temp-')
|
||||
expect(stateWithOptimistic.messages[1].role).toBe('user')
|
||||
expect((stateWithOptimistic.messages[0] as any).details.referencedAssets).toEqual([
|
||||
{ id: 'asset-1', name: 'File 1.txt', type: 'file' },
|
||||
])
|
||||
|
||||
await sendPromise
|
||||
|
||||
// 4. Verify they are replaced correctly by the real backend entries
|
||||
// 4. Verify message list after streaming completes
|
||||
const finalState = useChatbotStore.getState()
|
||||
expect(finalState.messages).toHaveLength(2)
|
||||
expect(finalState.messages[0].id).toBe('context-display-ulid')
|
||||
@@ -418,4 +412,93 @@ describe('useChatbotStore', () => {
|
||||
expect((finalState.messages[0] as { customType?: string }).customType).toBe('shumai_message')
|
||||
expect(finalState.messages[1].id).toBe('assistant-msg-ulid')
|
||||
})
|
||||
|
||||
it('should include attachments, annotations, and second in optimistic message and API call', async () => {
|
||||
const mockEvents = [
|
||||
'data: {"type":"session","sessionId":"sess-456"}\n\n',
|
||||
'data: {"type":"done","status":"completed"}\n\n',
|
||||
]
|
||||
let eventIdx = 0
|
||||
const mockReader = {
|
||||
read: vi.fn(async () => {
|
||||
if (eventIdx < mockEvents.length) {
|
||||
const value = new TextEncoder().encode(mockEvents[eventIdx++])
|
||||
return { done: false, value }
|
||||
}
|
||||
return { done: true, value: undefined }
|
||||
}),
|
||||
}
|
||||
const mockResponse = {
|
||||
ok: true,
|
||||
headers: {
|
||||
get: vi.fn(() => 'sess-456'),
|
||||
},
|
||||
body: {
|
||||
getReader: () => mockReader,
|
||||
},
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(client.api.teams[':teamId'].chat.$post).mockResolvedValue(mockResponse as any)
|
||||
|
||||
const sendPromise = useChatbotStore.getState().sendMessage(
|
||||
'team-123',
|
||||
'Look at this frame',
|
||||
'proj-123',
|
||||
'file-asset-1',
|
||||
undefined,
|
||||
['att-1'],
|
||||
[
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[10, 20],
|
||||
[30, 40],
|
||||
],
|
||||
},
|
||||
],
|
||||
12.5,
|
||||
[{ id: 'att-1', name: 'screenshot.png', type: 'image', mediaType: 'image/png' }],
|
||||
)
|
||||
|
||||
// Check optimistic message has annotations, second position, and attachedFiles
|
||||
const optimisticState = useChatbotStore.getState()
|
||||
expect(optimisticState.messages).toHaveLength(1)
|
||||
const optMsg = optimisticState.messages[0] as unknown as Record<string, unknown>
|
||||
expect(optMsg.customType).toBe('shumai_message')
|
||||
const details = optMsg.details as Record<string, unknown>
|
||||
expect(details.annotation).toBe(true)
|
||||
expect(details.annotations).toHaveLength(1)
|
||||
expect(details.position).toEqual({ type: 'time', seconds: 12.5 })
|
||||
expect(details.attachedFiles).toEqual([
|
||||
{ id: 'att-1', name: 'screenshot.png', type: 'image', mediaType: 'image/png' },
|
||||
])
|
||||
|
||||
await sendPromise
|
||||
|
||||
expect(client.api.teams[':teamId'].chat.$post).toHaveBeenCalledWith({
|
||||
param: { teamId: 'team-123' },
|
||||
json: {
|
||||
agentId: 'agent-1',
|
||||
textPrompt: 'Look at this frame',
|
||||
attachedFiles: ['att-1'],
|
||||
assetIds: undefined,
|
||||
sessionId: undefined,
|
||||
contextAssetId: 'file-asset-1',
|
||||
projectId: 'proj-123',
|
||||
second: 12.5,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[10, 20],
|
||||
[30, 40],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { create } from 'zustand'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { ChatMessage, ChatSessionInfo } from '@shumai/dtos'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const AGENT_PREFERENCE_STORAGE_KEY = 'shumai_selected_agent_id'
|
||||
@@ -18,6 +19,15 @@ export interface ChatAsset {
|
||||
type: 'file' | 'folder'
|
||||
}
|
||||
|
||||
export interface AttachedFileMeta {
|
||||
id: string
|
||||
name: string
|
||||
type: string
|
||||
url?: string
|
||||
mediaType?: string
|
||||
mimeType?: string
|
||||
}
|
||||
|
||||
interface ChatbotState {
|
||||
isChatbotOpen: boolean
|
||||
setIsChatbotOpen: (open: boolean) => void
|
||||
@@ -54,6 +64,10 @@ interface ChatbotState {
|
||||
projectId: string,
|
||||
contextAssetId?: string,
|
||||
onAssetMutation?: () => void,
|
||||
attachmentIds?: string[],
|
||||
annotations?: Annotation[],
|
||||
second?: number | null,
|
||||
attachedFilesMeta?: AttachedFileMeta[],
|
||||
) => Promise<void>
|
||||
abortActiveSession: (teamId: string) => Promise<void>
|
||||
}
|
||||
@@ -177,37 +191,43 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
})
|
||||
},
|
||||
|
||||
sendMessage: async (teamId, text, projectId, contextAssetId, onAssetMutation) => {
|
||||
sendMessage: async (
|
||||
teamId,
|
||||
text,
|
||||
projectId,
|
||||
contextAssetId,
|
||||
onAssetMutation,
|
||||
attachmentIds,
|
||||
annotations,
|
||||
second,
|
||||
attachedFilesMeta,
|
||||
) => {
|
||||
const state = useChatbotStore.getState()
|
||||
if (state.isStreaming) return
|
||||
|
||||
const tempId = `temp-${Date.now()}`
|
||||
const optimisticMsg = {
|
||||
id: tempId,
|
||||
role: 'user' as const,
|
||||
content: [{ type: 'text', text }],
|
||||
role: 'custom' as const,
|
||||
customType: 'shumai_message',
|
||||
content: text,
|
||||
display: true,
|
||||
details: {
|
||||
currentAsset: contextAssetId ? { id: contextAssetId, name: '', type: 'file' } : undefined,
|
||||
position:
|
||||
second !== undefined && second !== null ? { type: 'time', seconds: second } : undefined,
|
||||
annotation: !!(annotations && annotations.length > 0),
|
||||
annotations: annotations || undefined,
|
||||
attachedFiles: attachedFilesMeta || undefined,
|
||||
referencedAssets:
|
||||
state.chatAssets.length > 0
|
||||
? state.chatAssets.map((a) => ({ id: a.id, name: a.name, type: a.type }))
|
||||
: undefined,
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
} as unknown as ChatMessage
|
||||
|
||||
const newMessages = [...state.messages]
|
||||
if (state.chatAssets.length > 0) {
|
||||
const tempContextId = `temp-context-${Date.now()}`
|
||||
const optimisticContextMsg = {
|
||||
id: tempContextId,
|
||||
role: 'custom' as const,
|
||||
customType: 'context_display_info',
|
||||
details: {
|
||||
assets: state.chatAssets.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
})),
|
||||
},
|
||||
timestamp: Date.now() - 1,
|
||||
} as unknown as ChatMessage
|
||||
newMessages.push(optimisticContextMsg)
|
||||
}
|
||||
newMessages.push(optimisticMsg)
|
||||
const newMessages = [...state.messages, optimisticMsg]
|
||||
|
||||
set({
|
||||
messages: newMessages,
|
||||
@@ -229,11 +249,17 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
|
||||
param: { teamId },
|
||||
json: {
|
||||
agentId,
|
||||
textPrompt: text,
|
||||
assetIds,
|
||||
textPrompt: text || undefined,
|
||||
attachedFiles: attachmentIds && attachmentIds.length > 0 ? attachmentIds : undefined,
|
||||
assetIds: assetIds && assetIds.length > 0 ? assetIds : undefined,
|
||||
sessionId: state.currentSessionId || undefined,
|
||||
contextAssetId,
|
||||
projectId,
|
||||
second: second ?? undefined,
|
||||
annotations:
|
||||
annotations && annotations.length > 0
|
||||
? (annotations as unknown as Record<string, unknown>[])
|
||||
: undefined,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user