conversationSettings.test.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. const dialog = document.querySelector<HTMLDialogElement>('dialog.editor')!
  44. expect(dialog.open).toBe(true)
  45. expect(dialog.querySelector('h2')?.textContent?.trim()).toBe(kind === 'direct' ? '机器人设置' : '群聊设置')
  46. expect(dialog.querySelector<HTMLInputElement>('input[maxlength="100"]')?.value).toBe(kind === 'direct' ? '目标机器人' : '目标聊天')
  47. expect(router.currentRoute.value.path).toBe('/conversations/current')
  48. if (kind === 'group') {
  49. expect(dialog.querySelector<HTMLInputElement>('input[value="target-bot"]')?.disabled).toBe(true)
  50. const stop = [...dialog.querySelectorAll('button')].find(button => button.textContent === '停止 目标机器人')!
  51. stop.click(); await flushPromises()
  52. expect(apiRequest).toHaveBeenCalledWith('/api/app/conversations/target/agents/target-bot/stop', expect.objectContaining({ method: 'POST' }))
  53. }
  54. dialog.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
  55. await flushPromises()
  56. expect(apiRequest).toHaveBeenCalledWith(kind === 'direct' ? '/api/app/agents/target-bot' : '/api/app/conversations/target', expect.objectContaining({ method: 'PATCH', body: expect.objectContaining({ name: kind === 'direct' ? '目标机器人' : '目标聊天' }) }))
  57. })