conversationSearchDelete.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { afterEach, describe, 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 '../../src/client/views/ConversationsView.vue'
  6. import { apiRequest } from '../../src/client/api/client'
  7. import type { WorkspaceLifecyclePreview } from '../../src/shared/workspaceLifecycle'
  8. vi.mock('../../src/client/api/client', () => ({ apiRequest: vi.fn(), ApiError: class extends Error {} }))
  9. vi.mock('../../src/client/stores/auth', () => ({ useAuthStore: () => ({ user: { id: 'owner' }, profiles: [], refreshProfileAvatars: async () => {} }) }))
  10. vi.mock('../../src/client/stores/theme', () => ({ useThemeStore: () => ({}) }))
  11. let wrapper: VueWrapper | undefined
  12. afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.mocked(apiRequest).mockReset() })
  13. async function setup(kind: 'direct' | 'group', remove: () => Promise<void> = async () => {}, groups: WorkspaceLifecyclePreview['groups'] = [], initiallyArchived = true) {
  14. let archived = [{ id: 'archived', name: '旧聊天', kind, archived: initiallyArchived, memberIds: ['bot'], updatedAt: 1 }]
  15. const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/conversations/:id?', component: { template: '<div />' } }] })
  16. await router.push('/conversations'); await router.isReady()
  17. vi.mocked(apiRequest).mockImplementation(async (path, options) => {
  18. if (path.endsWith('/lifecycle')) {
  19. if (options?.method !== 'POST') return { name: '旧聊天', kind, groups, confirmationToken: 'a'.repeat(64) } as never
  20. await remove()
  21. const action = (options.body as { action: string }).action
  22. if (action === 'delete') archived = []
  23. else archived = archived.map(item => ({ ...item, archived: action === 'archive' }))
  24. return {} as never
  25. }
  26. if (path === '/api/app/agents') return { agents: [{ id: 'bot', name: '旧聊天', archived: true }] } as never
  27. if (path === '/api/app/conversations') return { conversations: archived, cursor: 1 } as never
  28. if (path.startsWith('/api/app/events')) return { events: [], cursor: 1 } as never
  29. return {} as never
  30. })
  31. wrapper = shallowMount(ConversationsView, { attachTo: document.body, global: {
  32. provide: { [matchedRouteKey as symbol]: shallowRef(router.currentRoute.value.matched[0]) },
  33. plugins: [router], stubs: { WorkspaceShell: { template: '<div><slot name="sidebar" /><slot /></div>' }, FloatingResourceSearch: false, Teleport: false },
  34. } })
  35. await flushPromises()
  36. document.dispatchEvent(new CustomEvent('hermes-yaoyao:sidebar-search', { detail: { section: 'groups' } }))
  37. await flushPromises()
  38. expect(document.querySelector('.search-delete')).toBeNull()
  39. document.querySelector<HTMLButtonElement>('[role="tab"][aria-label="已归档"]')!.click()
  40. await flushPromises()
  41. return router
  42. }
  43. describe('archived chat deletion from search', () => {
  44. it('keeps the archived result and route when confirmation is cancelled', async () => {
  45. const router = await setup('direct')
  46. const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
  47. document.querySelector<HTMLButtonElement>('.search-delete')!.click()
  48. await flushPromises()
  49. expect(confirm).toHaveBeenCalledWith(expect.stringContaining('永久删除 Bot「旧聊天」'))
  50. expect(vi.mocked(apiRequest).mock.calls.some(([, options]) => options?.method === 'POST')).toBe(false)
  51. expect(router.currentRoute.value.path).toBe('/conversations')
  52. expect(document.querySelector('[role="dialog"]')?.textContent).toContain('旧聊天')
  53. })
  54. it.each(['direct', 'group'] as const)('deletes an archived %s with the confirmed snapshot and updates the open search', async kind => {
  55. await setup(kind)
  56. vi.spyOn(window, 'confirm').mockReturnValue(true)
  57. const button = document.querySelector<HTMLButtonElement>('.search-delete')!
  58. button.focus(); button.click()
  59. await flushPromises()
  60. expect(apiRequest).toHaveBeenCalledWith('/api/app/conversations/archived/lifecycle', { method: 'POST', body: { action: 'delete', confirmationToken: 'a'.repeat(64) } })
  61. expect(document.querySelector('[role="dialog"]')?.textContent).toContain('没有已归档聊天')
  62. expect(document.querySelector('[role="tab"][aria-label="已归档"]')?.textContent).toContain('0')
  63. expect(document.activeElement).toBe(document.querySelector('[role="dialog"] input'))
  64. })
  65. it('disables repeated deletion and keeps server errors inside search', async () => {
  66. let reject!: (error: Error) => void
  67. await setup('direct', () => new Promise<void>((_, fail) => { reject = fail }))
  68. vi.spyOn(window, 'confirm').mockReturnValue(true)
  69. const button = document.querySelector<HTMLButtonElement>('.search-delete')!
  70. button.click(); await flushPromises()
  71. expect(button.disabled).toBe(true)
  72. button.click()
  73. expect(vi.mocked(apiRequest).mock.calls.filter(([, options]) => options?.method === 'POST')).toHaveLength(1)
  74. reject(new Error('此 Bot 仍是群聊成员'))
  75. await flushPromises()
  76. expect(document.querySelector('[role="dialog"] [role="alert"]')?.textContent).toBe('此 Bot 仍是群聊成员')
  77. expect(button.disabled).toBe(false)
  78. expect(document.querySelector('[role="dialog"]')?.textContent).toContain('旧聊天')
  79. })
  80. it('restores a chat without opening it and updates both archive counts', async () => {
  81. const router = await setup('direct')
  82. document.querySelector<HTMLButtonElement>('.search-restore')!.click()
  83. await flushPromises()
  84. expect(apiRequest).toHaveBeenCalledWith('/api/app/conversations/archived/lifecycle', { method: 'POST', body: { action: 'restore' } })
  85. expect(router.currentRoute.value.path).toBe('/conversations')
  86. expect(document.querySelector('[role="tab"][aria-label="未归档"]')?.textContent).toContain('1')
  87. expect(document.querySelector('[role="tab"][aria-label="已归档"]')?.textContent).toContain('0')
  88. })
  89. it.each(['archive', 'delete'] as const)('warns about group membership before %s from the chat menu', async operation => {
  90. await setup('direct', async () => {}, [{ id: 'group', name: '设计群', administrator: false }], false)
  91. const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
  92. wrapper!.findComponent({ name: 'ConversationList' }).vm.$emit(operation, 'archived')
  93. await flushPromises()
  94. expect(confirm).toHaveBeenCalledWith(expect.stringContaining('「设计群」'))
  95. expect(confirm).toHaveBeenCalledWith(expect.stringContaining('先从这些群聊移除'))
  96. expect(vi.mocked(apiRequest).mock.calls.some(([, options]) => options?.method === 'POST')).toBe(false)
  97. })
  98. it('blocks a group administrator and asks for a transfer instead of deleting', async () => {
  99. await setup('direct', async () => {}, [{ id: 'group', name: '管理群', administrator: true }])
  100. const confirm = vi.spyOn(window, 'confirm')
  101. document.querySelector<HTMLButtonElement>('.search-delete')!.click()
  102. await flushPromises()
  103. expect(confirm).not.toHaveBeenCalled()
  104. expect(document.querySelector('[role="dialog"] [role="alert"]')?.textContent).toContain('「管理群」的管理者,请先转交管理权')
  105. expect(vi.mocked(apiRequest).mock.calls.some(([, options]) => options?.method === 'POST')).toBe(false)
  106. })
  107. })