feat(chat): 访客与客服聊天界面、历史拉取与断线重连

聊天页支持发送确认、历史补拉和重连;刷新后不重复展示已确认消息。
This commit is contained in:
WangShen007 committed 2026-09-27 21:10:00 +08:00
1 parent db48cac9e0
commit 4388e1d203
19 files changed
+6252

No files matched your search

@@ -0,0 +1,53 @@
/*
Copyright 2024-2026 ChatterMate
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import HandlerBadge from '@/components/conversations/HandlerBadge.vue'
const mountBadge = (props: Record<string, unknown>) =>
mount(HandlerBadge, {
props,
global: { stubs: { 'font-awesome-icon': true } },
})
describe('HandlerBadge', () => {
it('labels an AI-handled chat', () => {
const badge = mountBadge({ chat: { status: 'open', user_id: null } })
expect(badge.text()).toBe('AI')
expect(badge.find('.handler-ai').exists()).toBe(true)
})
it('labels a chat queued for a human', () => {
const badge = mountBadge({ chat: { status: 'transferred', user_id: null } })
expect(badge.text()).toBe('等待人工客服')
expect(badge.find('.handler-waiting').exists()).toBe(true)
})
it('names the human holding the chat', () => {
const badge = mountBadge({
chat: { status: 'open', user_id: 'u1', user_name: 'Priya' },
currentUserId: 'u2',
})
expect(badge.text()).toBe('Priya')
expect(badge.find('.handler-human').exists()).toBe(true)
})
it('renders nothing for a closed chat, which the status pill already states', () => {
const badge = mountBadge({ chat: { status: 'closed', user_id: 'u1' } })
expect(badge.find('.handler-badge').exists()).toBe(false)
})
})
@@ -0,0 +1,48 @@
/*
Copyright 2024-2026 ChatterMate
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import MessageStatusTicks from '@/components/conversations/MessageStatusTicks.vue'
const stubs = { global: { stubs: { 'font-awesome-icon': true } } }
describe('MessageStatusTicks', () => {
it.each([
['sent', '已发送'],
['delivered', '已送达'],
['read', '已读'],
])('labels a %s message', (status, label) => {
const ticks = mount(MessageStatusTicks, { props: { status }, ...stubs })
expect(ticks.find('.status-ticks').attributes('aria-label')).toBe(label)
expect(ticks.find(`.status-ticks--${status}`).exists()).toBe(true)
})
it.each([null, undefined, 'failed', 'unknown'])(
'shows nothing for %s — a failure has its own notice',
(status) => {
const ticks = mount(MessageStatusTicks, { props: { status }, ...stubs })
expect(ticks.find('.status-ticks').exists()).toBe(false)
},
)
})
describe('MessageStatusTicks on an accent bubble', () => {
it('marks read with the inverted badge', () => {
const ticks = mount(MessageStatusTicks, { props: { status: 'read', onAccent: true }, ...stubs })
expect(ticks.find('.status-ticks--on-accent.status-ticks--read').exists()).toBe(true)
})
})
@@ -0,0 +1,54 @@
/*
Copyright 2024-2026 ChatterMate
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import QuickReplyChips from '@/components/conversations/QuickReplyChips.vue'
import MessageTag from '@/components/conversations/MessageTag.vue'
const sent = (asText = false) => ({
as_text: asText,
choices: [{ id: 'qr_0', text: 'Today' }, { id: 'qr_1', text: 'Tomorrow' }]
})
describe('QuickReplyChips', () => {
it('lists the choices that were sent, in order', () => {
const chips = mount(QuickReplyChips, { props: { sent: sent() } })
expect(chips.findAll('.quick-reply-chip').map((c) => c.text())).toEqual(['Today', 'Tomorrow'])
expect(chips.find('.quick-reply-chips').attributes('aria-label')).toBe('已发送的选项')
})
it('says when the choices went out as a numbered list', () => {
const chips = mount(QuickReplyChips, { props: { sent: sent(true) } })
expect(chips.find('.quick-reply-chips').attributes('aria-label')).toContain('编号列表')
})
it('renders nothing without a record', () => {
expect(mount(QuickReplyChips, { props: { sent: null } }).find('.quick-reply-chips').exists()).toBe(false)
expect(mount(QuickReplyChips, { props: { sent: { choices: [] } } }).find('.quick-reply-chips').exists()).toBe(false)
})
})
describe('MessageTag', () => {
it('shows its icon and label', () => {
const tag = mount(MessageTag, {
props: { icon: 'fa-solid fa-plug', label: 'Sent by CoachIQ' },
global: { stubs: { 'font-awesome-icon': true } }
})
expect(tag.text()).toBe('Sent by CoachIQ')
expect(tag.find('font-awesome-icon-stub').attributes('icon')).toBe('fa-solid fa-plug')
})
})
@@ -0,0 +1,59 @@
/*
Copyright 2024-2026 ChatterMate
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { routeChatToHuman } from '@/utils/chatActions'
import { chatService } from '@/services/chat'
vi.mock('@/services/chat', () => ({
chatService: { routeToHuman: vi.fn() },
}))
const toastSuccess = vi.fn()
const toastError = vi.fn()
vi.mock('vue-sonner', () => ({
toast: {
success: (...args: unknown[]) => toastSuccess(...args),
error: (...args: unknown[]) => toastError(...args),
},
}))
describe('routeChatToHuman', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns the updated chat the endpoint sends back', async () => {
const updated = { session_id: 's1', status: 'transferred', user_id: null }
vi.mocked(chatService.routeToHuman).mockResolvedValue(updated as never)
await expect(routeChatToHuman('s1')).resolves.toBe(updated)
expect(toastSuccess).toHaveBeenCalled()
expect(toastError).not.toHaveBeenCalled()
})
it('surfaces the server reason and returns null on failure', async () => {
vi.mocked(chatService.routeToHuman).mockRejectedValue({
response: { data: { detail: 'A human is already handling this chat' } },
})
await expect(routeChatToHuman('s1')).resolves.toBeNull()
expect(toastError).toHaveBeenCalledWith(
'转交会话失败',
expect.objectContaining({ description: 'A human is already handling this chat' })
)
})
})
@@ -0,0 +1,56 @@
/*
Copyright 2024-2026 ChatterMate
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { describe, expect, it } from 'vitest'
import { presenceLine } from '@/utils/widgetPresence'
describe('presenceLine', () => {
it('promises instant replies only while the AI is answering', () => {
const line = presenceLine({ mode: 'ai', available: true })
expect(line).toEqual({ text: '在线 · 立即回复', online: true })
})
it('ignores business hours for an AI agent — it answers at 3am too', () => {
expect(presenceLine({ mode: 'ai', available: false }).online).toBe(true)
})
it('sets a softer expectation when a person has to reply', () => {
const line = presenceLine({ mode: 'human', available: true })
expect(line.text).toBe('在线 · 通常几分钟内回复')
expect(line.online).toBe(true)
})
it('says away outside business hours instead of claiming to be online', () => {
const line = presenceLine({ mode: 'human', available: false })
expect(line.text).toContain('离开')
expect(line.online).toBe(false)
})
it('switches to the human wording once someone takes the chat over', () => {
// The agent still has AI enabled, but a person owns this conversation now.
expect(presenceLine({ mode: 'ai', available: true }, true).text).toBe(
'在线 · 通常几分钟内回复'
)
expect(presenceLine({ mode: 'ai', available: false }, true).online).toBe(false)
})
it('keeps the old wording when the payload predates presence', () => {
// An older cached widget page sends nothing — do not declare the team away
// on no evidence.
expect(presenceLine(undefined).text).toBe('在线 · 立即回复')
expect(presenceLine({}).text).toBe('在线 · 立即回复')
})
})
@@ -0,0 +1,189 @@
/*
Copyright 2024-2026 ChatterMate
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount, VueWrapper } from '@vue/test-utils'
import { nextTick } from 'vue'
import ConversationsView from '../../views/ConversationsView.vue'
import { createPinia, setActivePinia } from 'pinia'
// Mock vue-router (component uses useRoute for deep-link query params)
vi.mock('vue-router', () => ({
useRoute: () => ({ query: {} }),
useRouter: () => ({ push: vi.fn(), replace: vi.fn() })
}))
// Mock the chat service
vi.mock('@/services/chat', () => ({
chatService: {
getRecentChats: vi.fn(),
getChatDetail: vi.fn(),
takeoverChat: vi.fn(),
reassignChat: vi.fn()
}
}))
// Mock the components
vi.mock('@/layouts/DashboardLayout.vue', () => ({
default: {
name: 'DashboardLayout',
template: '<div class="dashboard-layout"><slot /></div>'
}
}))
vi.mock('@/components/conversations/ConversationsList.vue', () => ({
default: {
name: 'ConversationsList',
template: '<div class="conversations-list"></div>',
props: ['conversations', 'loading', 'error', 'loadedCount', 'totalCount', 'hasMore', 'statusFilter', 'showChatInfo'],
emits: ['refresh', 'update-filter', 'load-more', 'chat-updated', 'chat-selected', 'clear-unread']
}
}))
vi.mock('@/components/conversations/ConversationFilters.vue', () => ({
default: {
name: 'ConversationFilters',
template: '<div class="conversation-filters"></div>',
props: ['showFilters', 'filterValues', 'users', 'agents', 'loadingUsers', 'loadingAgents'],
emits: ['toggle', 'apply', 'clear', 'update:filterValues']
}
}))
vi.mock('@/components/conversations/ChatInfoPanel.vue', () => ({
default: {
name: 'ChatInfoPanel',
template: '<div class="chat-info-panel"></div>',
props: ['chatInfo', 'users'],
emits: ['close', 'refresh', 'chatUpdated', 'chatClosed']
}
}))
// Mock API service
vi.mock('@/services/api', () => ({
default: {
get: vi.fn().mockResolvedValue({ data: [] }),
post: vi.fn().mockResolvedValue({ data: {} }),
put: vi.fn().mockResolvedValue({ data: {} }),
delete: vi.fn().mockResolvedValue({ data: {} })
}
}))
// Mock agent service
vi.mock('@/services/agent', () => ({
agentService: {
getOrganizationAgents: vi.fn().mockResolvedValue([])
}
}))
// Import the mocked modules
import { chatService } from '@/services/chat'
describe('ConversationsView', () => {
let wrapper: VueWrapper
beforeEach(() => {
setActivePinia(createPinia())
vi.clearAllMocks()
})
it('renders properly', () => {
wrapper = mount(ConversationsView)
expect(wrapper.find('.page-header').exists()).toBe(true)
expect(wrapper.find('h1').text()).toBe('会话')
})
it('shows loading state initially', () => {
wrapper = mount(ConversationsView)
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
expect(conversationsList.props('loading')).toBe(true)
})
it('loads conversations on mount', async () => {
const mockConversations = [
{ id: '1', title: 'Chat 1' },
{ id: '2', title: 'Chat 2' }
]
;(chatService.getRecentChats as any).mockResolvedValue(mockConversations)
wrapper = mount(ConversationsView)
// Wait for the mounted hook and async operations to complete
await vi.waitFor(async () => {
await nextTick()
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
return conversationsList.props('loading') === false
})
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
expect(chatService.getRecentChats).toHaveBeenCalledWith({
status: 'open,transferred',
skip: 0,
limit: 20
})
expect(conversationsList.props('conversations')).toEqual(mockConversations)
expect(conversationsList.props('loading')).toBe(false)
})
it('handles loading error', async () => {
const errorMessage = '加载会话失败'
;(chatService.getRecentChats as any).mockRejectedValue(new Error('API Error'))
wrapper = mount(ConversationsView)
// Wait for the mounted hook and async operations to complete
await vi.waitFor(async () => {
await nextTick()
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
return conversationsList.props('loading') === false
})
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
expect(conversationsList.props('error')).toBe(errorMessage)
expect(conversationsList.props('loading')).toBe(false)
})
it('refreshes conversations when refresh event is emitted', async () => {
const mockConversations = [
{ id: '1', title: 'Chat 1' },
{ id: '2', title: 'Chat 2' }
]
;(chatService.getRecentChats as any).mockResolvedValue(mockConversations)
wrapper = mount(ConversationsView)
await vi.waitFor(async () => {
await nextTick()
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
return conversationsList.props('loading') === false
})
// Clear the first call to getRecentChats from mounted
vi.clearAllMocks()
// Trigger refresh
const conversationsList = wrapper.findComponent({ name: 'ConversationsList' })
await conversationsList.vm.$emit('refresh')
// Wait for the refresh to complete
await vi.waitFor(async () => {
await nextTick()
return chatService.getRecentChats.mock.calls.length > 0
})
expect(chatService.getRecentChats).toHaveBeenCalled()
})
})