conversationSettings.test.ts 5.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { afterEach, expect, it, vi } from 'vitest'
  2. import { flushPromises, shallowMount, type VueWrapper } from '@vue/test-utils'
  3. import { shallowRef } from 'vue'
  4. import { createMemoryHistory, createRouter, matchedRouteKey } from 'vue-router'
  5. import ConversationsView from '@/views/ConversationsView.vue'
  6. import { apiRequest } from '@/api/client'
  7. import type { WorkspaceConversation } from '@shared/workspace'
  8. vi.mock('@/api/client', () => ({ apiRequest: vi.fn(), setApiCsrfToken: vi.fn(), ApiError: class extends Error {} }))
  9. vi.mock('@/stores/auth', () => ({ useAuthStore: () => ({ user: { id: 'owner' }, profiles: [], refreshProfileAvatars: async () => {} }) }))
  10. vi.mock('@/stores/theme', () => ({ useThemeStore: () => ({}) }))
  11. const originalShowModal = HTMLDialogElement.prototype.showModal
  12. const originalClose = HTMLDialogElement.prototype.close
  13. let wrapper: VueWrapper | undefined
  14. afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.mocked(apiRequest).mockReset(); HTMLDialogElement.prototype.showModal = originalShowModal; HTMLDialogElement.prototype.close = originalClose })
  15. it.each(['direct', 'group'] as const)('opens and saves the menu target %s while another chat is selected', async kind => {
  16. const base: WorkspaceConversation = { id: 'current', kind: 'direct', name: '当前聊天', avatar: '', memberIds: ['current-bot'], instructions: '', administratorId: 'current-bot', mode: 'host', autoReplyIds: [], maxReplyRounds: 3, archived: false, pinned: false, readSeq: 0, lastSeq: 0, preview: '', createdAt: 1, updatedAt: 1 }
  17. const target: WorkspaceConversation = { ...base, id: 'target', kind, name: '目标聊天', memberIds: ['target-bot', ...(kind === 'group' ? ['current-bot'] : [])], administratorId: 'target-bot', instructions: '目标规则', activeAgentStates: kind === 'group' ? { 'target-bot': 'running' } : {} }
  18. const conversations = [base, target]
  19. const agents = ['current-bot', 'target-bot'].map(id => ({ id, name: id === 'target-bot' ? '目标机器人' : '当前机器人', avatar: '', instructions: `${id}规则`, nodeId: 'local', profile: 'default', archived: false }))
  20. vi.stubGlobal('EventSource', class { addEventListener() {} close() {} })
  21. vi.mocked(apiRequest).mockImplementation(async path => {
  22. if (path === '/api/app/capabilities') return { features: [], csrfToken: 'fixture-csrf' } as never
  23. if (path === '/api/app/workspace/snapshot') return { agents, conversations, cursor: 1, details: [] } as never
  24. if (path === '/api/app/agents') return { agents } as never
  25. if (path === '/api/app/agents/sources') return { sources: [{ nodeId: 'local', profile: 'default', name: '基础机器人' }] } as never
  26. if (path === '/api/app/conversations') return { conversations, cursor: 1 } as never
  27. if (path.startsWith('/api/app/events')) return { events: [], cursor: 1 } as never
  28. const conversation = conversations.find(c => path.split('?')[0] === `/api/app/conversations/${c.id}`)
  29. if (conversation) return { conversation, messages: [], runs: [], run: null, interactions: [], tasks: [] } as never
  30. return {} as never
  31. })
  32. HTMLDialogElement.prototype.showModal = function () { this.open = true }
  33. HTMLDialogElement.prototype.close = function () { this.open = false }
  34. const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/conversations/:id?', component: { template: '<div />' } }] })
  35. await router.push('/conversations/current'); await router.isReady()
  36. wrapper = shallowMount(ConversationsView, { attachTo: document.body, global: {
  37. provide: { [matchedRouteKey as symbol]: shallowRef(router.currentRoute.value.matched[0]) }, plugins: [router],
  38. stubs: { WorkspaceShell: { template: '<div><slot name="sidebar" /><slot /></div>' }, ComposerShell: { template: '<div />', methods: { filesSnapshot: () => [], attachFiles: async () => {} } }, Teleport: false },
  39. } })
  40. await flushPromises()
  41. wrapper.findComponent({ name: 'ConversationList' }).vm.$emit('settings', 'target')
  42. await flushPromises()
  43. expect(router.currentRoute.value.path).toBe('/conversations/current')
  44. if (kind === 'direct') {
  45. expect(document.querySelector('dialog.editor')).toBeNull()
  46. const editor = wrapper.findComponent({ name: 'BotProfileDialog' })
  47. expect(editor.props('agent')).toMatchObject({ id: 'target-bot', name: '目标机器人' })
  48. expect(editor.props('conversationId')).toBe('target')
  49. expect(editor.props('draft')).toMatchObject({ name: '目标机器人', source: '["local","default"]' })
  50. editor.vm.$emit('save', { ...editor.props('draft'), name: '目标机器人' })
  51. } else {
  52. const dialog = document.querySelector<HTMLDialogElement>('dialog.editor')!
  53. expect(dialog.open).toBe(true)
  54. expect(dialog.querySelector('h2')?.textContent?.trim()).toBe('群聊设置')
  55. expect(dialog.querySelector<HTMLInputElement>('input[maxlength="100"]')?.value).toBe('目标聊天')
  56. expect(dialog.querySelector<HTMLInputElement>('input[value="target-bot"]')?.disabled).toBe(true)
  57. const stop = [...dialog.querySelectorAll('button')].find(button => button.textContent === '停止 目标机器人')!
  58. stop.click(); await flushPromises()
  59. expect(apiRequest).toHaveBeenCalledWith('/api/app/conversations/target/agents/target-bot/stop', expect.objectContaining({ method: 'POST' }))
  60. dialog.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
  61. }
  62. await flushPromises()
  63. expect(apiRequest).toHaveBeenCalledWith(kind === 'direct' ? '/api/app/agents/target-bot' : '/api/app/conversations/target', expect.objectContaining({ method: 'PATCH', body: expect.objectContaining({ name: kind === 'direct' ? '目标机器人' : '目标聊天' }) }))
  64. if (kind === 'direct') expect(router.currentRoute.value.path).toBe('/conversations/current')
  65. })