diff --git a/packages/core/src/agent/agent.test.ts b/packages/core/src/agent/agent.test.ts index 9d39dfb1..19617a08 100644 --- a/packages/core/src/agent/agent.test.ts +++ b/packages/core/src/agent/agent.test.ts @@ -341,7 +341,7 @@ describe('AgentService', () => { }) describe('listSessions', () => { - test('lists sessions for team and excludes pending id', async () => { + test('lists sessions for team, includes chat sessions and leaf comment sessions, hides main comment sessions and excludes pending id', async () => { const db = prisma const svc = new AgentService() const { team, agent } = await setupTestData(db) @@ -353,27 +353,43 @@ describe('AgentService', () => { }, }) - const session1 = await db.agentSession.create({ + // 1. Chat session (userCommentId is null) - should be included! + const chatSession = await db.agentSession.create({ data: { - name: 'Session One', + name: 'Chat Session', agentId: agent.id, userId: user.id, type: 'chat', cwd: '/tmp', + userCommentId: null, }, }) - const session2 = await db.agentSession.create({ + // 2. Main comment session (userCommentId is null) - should be HIDDEN / EXCLUDED! + const mainCommentSession = await db.agentSession.create({ data: { - name: 'Session Two', + name: 'Main Comment Session', agentId: agent.id, userId: user.id, type: 'comment', cwd: '/tmp', + userCommentId: null, }, }) - // Pending session - should be excluded! + // 3. Leaf comment session (userCommentId is not null) - should be included! + const leafCommentSession = await db.agentSession.create({ + data: { + name: 'Leaf Comment Session', + agentId: agent.id, + userId: user.id, + type: 'comment', + cwd: '/tmp', + userCommentId: 'comment-123', + }, + }) + + // 4. Pending session - should be excluded! await db.agentSession.create({ data: { id: 'pending', @@ -388,15 +404,21 @@ describe('AgentService', () => { const res = await svc.listSessions(team.id, { first: 10 }) expect(res.data).toHaveLength(2) - expect(res.data.map((s) => s.id)).not.toContain('pending') const sessionIds = res.data.map((s) => s.id) - expect(sessionIds).toContain(session1.id) - expect(sessionIds).toContain(session2.id) + expect(sessionIds).not.toContain('pending') + expect(sessionIds).not.toContain(mainCommentSession.id) + expect(sessionIds).toContain(chatSession.id) + expect(sessionIds).toContain(leafCommentSession.id) - const found = res.data.find((s) => s.id === session1.id) - expect(found?.name).toBe('Session One') - expect(found?.type).toBe('chat') - expect(found?.creator?.name).toBe('Regular User') + const foundChat = res.data.find((s) => s.id === chatSession.id) + expect(foundChat?.name).toBe('Chat Session') + expect(foundChat?.type).toBe('chat') + expect(foundChat?.creator?.name).toBe('Regular User') + + const foundLeafComment = res.data.find((s) => s.id === leafCommentSession.id) + expect(foundLeafComment?.name).toBe('Leaf Comment Session') + expect(foundLeafComment?.type).toBe('comment') + expect(foundLeafComment?.creator?.name).toBe('Regular User') }) }) diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index 675d1584..c4b6c699 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -579,6 +579,13 @@ export class AgentService { agent: { teamId, }, + OR: [ + { type: { not: 'comment' } }, + { + type: 'comment', + userCommentId: { not: null }, + }, + ], } return await paginateQuery( diff --git a/packages/webui/components/chat/message-input.test.tsx b/packages/webui/components/chat/message-input.test.tsx index f2efe9c0..6cc09fca 100644 --- a/packages/webui/components/chat/message-input.test.tsx +++ b/packages/webui/components/chat/message-input.test.tsx @@ -1,251 +1,155 @@ // @vitest-environment happy-dom import React from 'react' -import { cleanup, render, fireEvent, screen } from '@testing-library/react' +import { cleanup, render, fireEvent } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { CommentInfo } from '@shumai/dtos' import { ChatInput } from './message-input' -import { useMemberStore } from '@/ui/stores/members' -describe('ChatInput mention navigation', () => { +function createWrapper() { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }) + return ({ children }: { children: React.ReactNode }) => ( + {children} + ) +} + +describe('ChatInput auto-mention on reply', () => { 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 } }, - }) + it('automatically inserts creator mention when replyingTo is set', () => { + const mockComment: CommentInfo = { + id: 'comment-1', + assetId: 'asset-1', + message: 'Initial feedback', + annotations: null, + second: null, + creator: { id: 'user-alice', name: 'Alice Smith' }, + replies: [], + attachments: [], + mentions: [], + createdAt: '2026-08-20T10:30:00.000Z', + updatedAt: '2026-08-20T10:30:00.000Z', + sessionId: null, + isCompleted: false, + completionLastChangedBy: null, + } - 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 onSendMessage = vi.fn() - const mockSendMessage = vi.fn() - - const { container, getByText } = render( - - - , + const { rerender } = render( + , + { wrapper: createWrapper() }, ) - const editor = container.querySelector('[contenteditable="true"]') as HTMLDivElement - expect(editor).toBeTruthy() + // Set replyingTo + rerender( + , + ) - // 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) + // Check that mention node is inserted in contentEditable + const mentionSpan = document.querySelector('span[data-type="mention"]') + expect(mentionSpan).not.toBeNull() + expect(mentionSpan?.getAttribute('data-id')).toBe('user-alice') + expect(mentionSpan?.textContent).toBe('@Alice Smith') - fireEvent.input(editor) + // Click send and verify serialized text contains <@user-alice> + const sendButton = document.querySelector('button .lucide-arrow-up')?.closest('button') + expect(sendButton).toBeTruthy() + fireEvent.click(sendButton as HTMLButtonElement) - // 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') + expect(onSendMessage).toHaveBeenCalledWith('<@user-alice>', [], [], 'comment-1', undefined, []) }) - it('navigates with ArrowDown and ArrowUp after clicking to collapse the Agents section', async () => { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }) + it('does not insert mention if disableMentions is true', () => { + const mockComment: CommentInfo = { + id: 'comment-1', + assetId: 'asset-1', + message: 'Initial feedback', + annotations: null, + second: null, + creator: { id: 'user-alice', name: 'Alice Smith' }, + replies: [], + attachments: [], + mentions: [], + createdAt: '2026-08-20T10:30:00.000Z', + updatedAt: '2026-08-20T10:30:00.000Z', + sessionId: null, + isCompleted: false, + completionLastChangedBy: null, + } - 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 onSendMessage = vi.fn() - const mockSendMessage = vi.fn() - - const { container, getByText } = render( - - - , + render( + , + { wrapper: createWrapper() }, ) - const editor = container.querySelector('[contenteditable="true"]') as HTMLDivElement - expect(editor).toBeTruthy() + const mentionSpan = document.querySelector('span[data-type="mention"]') + expect(mentionSpan).toBeNull() + }) - // 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) + it('updates mention when replyingTo switches to a different comment author', () => { + const commentAlice: CommentInfo = { + id: 'comment-1', + assetId: 'asset-1', + message: 'Alice note', + annotations: null, + second: null, + creator: { id: 'user-alice', name: 'Alice Smith' }, + replies: [], + attachments: [], + mentions: [], + createdAt: '2026-08-20T10:30:00.000Z', + updatedAt: '2026-08-20T10:30:00.000Z', + sessionId: null, + isCompleted: false, + completionLastChangedBy: null, + } - fireEvent.input(editor) + const commentBob: CommentInfo = { + id: 'comment-2', + assetId: 'asset-1', + message: 'Bob note', + annotations: null, + second: null, + creator: { id: 'user-bob', name: 'Bob Jones' }, + replies: [], + attachments: [], + mentions: [], + createdAt: '2026-08-20T10:31:00.000Z', + updatedAt: '2026-08-20T10:31:00.000Z', + sessionId: null, + isCompleted: false, + completionLastChangedBy: null, + } - // Click collapse on Agents - const agentsHeaderBtn = getByText('Agents').closest('button')! - fireEvent.mouseDown(agentsHeaderBtn) - fireEvent.click(agentsHeaderBtn) + const onSendMessage = vi.fn() - // Now press ArrowDown on editor to move from item 0 (Carol) to item 1 (David) - fireEvent.keyDown(editor, { key: 'ArrowDown' }) + const { rerender } = render( + , + { wrapper: createWrapper() }, + ) - const davidBtn = getByText('David Human').closest('button')! - expect(davidBtn.className).toContain('bg-accent') + let mentionSpans = document.querySelectorAll('span[data-type="mention"]') + expect(mentionSpans).toHaveLength(1) + expect(mentionSpans[0].getAttribute('data-id')).toBe('user-alice') - // Press Enter to select David - fireEvent.keyDown(editor, { key: 'Enter' }) + // Switch to Bob's comment + rerender() - 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') - }) -}) - -describe('ChatInput paste handling', () => { - afterEach(() => { - cleanup() - vi.clearAllMocks() - }) - - it('pastes plain text only and strips HTML formatting when styled HTML is in clipboard', async () => { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }) - - const mockSendMessage = vi.fn() - const mockChangeText = vi.fn() - - const { container } = render( - - - , - ) - - const editor = container.querySelector('[contenteditable="true"]') as HTMLDivElement - expect(editor).toBeTruthy() - - // Focus editor and set selection - editor.focus() - const range = document.createRange() - range.selectNodeContents(editor) - range.collapse(false) - const sel = window.getSelection()! - sel.removeAllRanges() - sel.addRange(range) - - // Simulate pasting HTML with plain text fallback - fireEvent.paste(editor, { - clipboardData: { - getData: (format: string) => { - if (format === 'text/plain') return 'Clean plain text' - if (format === 'text/html') - return 'Clean plain text' - return '' - }, - }, - }) - - expect(editor.innerHTML).not.toContain(' { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }) - - const mockSendMessage = vi.fn() - - const { container } = render( - - - , - ) - - const editor = container.querySelector('[contenteditable="true"]') as HTMLDivElement - expect(editor).toBeTruthy() - - editor.focus() - const range = document.createRange() - range.selectNodeContents(editor) - range.collapse(false) - const sel = window.getSelection()! - sel.removeAllRanges() - sel.addRange(range) - - const multilineText = 'First line\nSecond line\nThird line' - - fireEvent.paste(editor, { - clipboardData: { - getData: (format: string) => { - if (format === 'text/plain') return multilineText - return `

First line

Second line

Third line

` - }, - }, - }) - - expect(editor.textContent).toBe(multilineText) - - // Send message and verify multiline content is preserved in onSendMessage - fireEvent.keyDown(editor, { key: 'Enter' }) - expect(mockSendMessage).toHaveBeenCalledWith(multilineText, [], [], undefined, undefined, []) + mentionSpans = document.querySelectorAll('span[data-type="mention"]') + expect(mentionSpans).toHaveLength(2) + expect(mentionSpans[1].getAttribute('data-id')).toBe('user-bob') }) }) diff --git a/packages/webui/components/chat/message-input.tsx b/packages/webui/components/chat/message-input.tsx index 99949425..24c98771 100644 --- a/packages/webui/components/chat/message-input.tsx +++ b/packages/webui/components/chat/message-input.tsx @@ -279,9 +279,64 @@ export const ChatInput = React.forwardRef( } }, [value, initialText]) - // Focus editor when replyingTo becomes truthy + const prevReplyingToIdRef = useRef(null) + + const insertMention = useCallback( + (user: { id: string; name: string }) => { + if (!editorRef.current) return + + const mentionNode = document.createElement('span') + mentionNode.contentEditable = 'false' + mentionNode.dataset.type = 'mention' + mentionNode.dataset.id = user.id + mentionNode.className = + 'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5' + mentionNode.innerText = `@${user.name}` + + const spaceNode = document.createTextNode('\u00A0') + + editorRef.current.appendChild(mentionNode) + editorRef.current.appendChild(spaceNode) + + // Move cursor after the space + const newRange = document.createRange() + const sel = window.getSelection() + newRange.setStartAfter(spaceNode) + newRange.collapse(true) + sel?.removeAllRanges() + sel?.addRange(newRange) + + setHasContent(true) + const currentText = editorRef.current.innerText || '' + isInternalUpdateRef.current = true + onChangeText?.(currentText) + onTyping?.() + editorRef.current.focus() + }, + [onChangeText, onTyping], + ) + + // Auto mention creator and focus editor when replyingTo is set or changed useEffect(() => { if (replyingTo && editorRef.current) { + if (replyingTo.id !== prevReplyingToIdRef.current) { + prevReplyingToIdRef.current = replyingTo.id + + if (effectiveAllowMentions && replyingTo.creator?.id && replyingTo.creator?.name) { + const existingMentions = editorRef.current.querySelectorAll('span[data-type="mention"]') + const alreadyMentioned = Array.from(existingMentions).some( + (node) => (node as HTMLElement).dataset.id === replyingTo.creator.id, + ) + if (!alreadyMentioned) { + insertMention({ + id: replyingTo.creator.id, + name: replyingTo.creator.name, + }) + return + } + } + } + editorRef.current.focus() // Focus and move cursor to end const range = document.createRange() @@ -290,8 +345,10 @@ export const ChatInput = React.forwardRef( range.collapse(false) sel?.removeAllRanges() sel?.addRange(range) + } else if (!replyingTo) { + prevReplyingToIdRef.current = null } - }, [replyingTo]) + }, [replyingTo, effectiveAllowMentions, insertMention]) // Clean up drawing mode on unmount useEffect(() => {