workspacePresentation.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { createUuid } from '@/utils/id'
  3. import { workspaceMessagesToUi } from '@/components/workspace/viewModels'
  4. afterEach(() => vi.unstubAllGlobals())
  5. describe('workspace chat uses the established presentation', () => {
  6. it('creates valid request ids on LAN HTTP without crypto.randomUUID', () => {
  7. vi.stubGlobal('crypto', { getRandomValues: (bytes: Uint8Array) => { for (let i=0;i<bytes.length;i++) bytes[i]=i; return bytes } })
  8. expect(createUuid()).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
  9. })
  10. it('preserves role identity, reasoning, files and tools for MessageTimeline', () => {
  11. const [message] = workspaceMessagesToUi([{id:'m',conversationId:'c',seq:1,role:'assistant',agentId:'a',agentName:'编辑',content:'[报告](/tmp/report.txt)',reasoning:'检查资料',status:'complete',createdAt:10,attachments:[{id:'f',name:'report.txt',mimeType:'text/plain',size:4,createdAt:10,sender:'agent',sourcePath:'/tmp/report.txt'}],tools:[{id:'t',name:'read_file',status:'tool.complete',result:'ok'}]}])
  12. expect(message).toMatchObject({profile:'a',author:'编辑',reasoning:'检查资料',status:'settled',content:'[报告](/api/app/files/f/download)'})
  13. expect(message?.tools?.[0]).toMatchObject({name:'read_file',status:'success',output:'ok'})
  14. expect(message?.attachments?.[0]?.url).toBe('/api/app/files/f/download')
  15. })
  16. it.each([
  17. ['complete', 'success'], ['failed', 'error'], ['interrupted', 'interrupted'], ['uncertain', 'running'], ['streaming', 'running'],
  18. ] as const)('renders stale tools in a %s message without reopening its trace', (status, expected) => {
  19. const [message] = workspaceMessagesToUi([{
  20. id: 'legacy', conversationId: 'c', seq: 1, role: 'assistant', content: '回复', reasoning: '',
  21. status, createdAt: 1, attachments: [], tools: [
  22. { id: '', name: 'tool_call', status: 'tool.generating' },
  23. { id: 'failed-tool', name: 'read_file', status: 'tool.complete', result: { error: '授权已结束' } },
  24. ],
  25. }])
  26. expect(message?.tools?.[0]?.status).toBe(expected)
  27. expect(message?.tools?.[1]?.status).toBe('error')
  28. })
  29. it('keeps peer direction outside the body without presenting it as a user message', () => {
  30. const communication = { direction: 'incoming' as const, peerId: 'b', peerName: '研究员', peerAvatar: '', peerKind: 'agent' as const, content: '当前为 v2' }
  31. const [message] = workspaceMessagesToUi([{ id: 'peer', conversationId: 'c', seq: 1, role: 'system', peerMessageId: 'p', communication, content: '来自 Bot「研究员」的回复:当前为 v2', reasoning: '', tools: [], attachments: [], status: 'complete', createdAt: 1 }])
  32. expect(message?.communication).toEqual(communication)
  33. expect(message?.content).toBe('当前为 v2')
  34. expect(message?.role).toBe('system')
  35. })
  36. })
  37. import { mount } from '@vue/test-utils'
  38. import { nextTick } from 'vue'
  39. import ConversationList from '@/components/workspace/ConversationList.vue'
  40. import ResourceSidebar from '@/components/app/ResourceSidebar.vue'
  41. import TeamAvatar from '@/components/common/TeamAvatar.vue'
  42. import type { WorkspaceAgent, WorkspaceConversation } from '../../src/shared/workspace'
  43. it('renders Bot unread as a dot and treats explicit false as authoritative over legacy counts', async () => {
  44. const conversation: WorkspaceConversation = { id: 'dot', kind: 'direct', name: '未读测试', avatar: '', memberIds: [], instructions: '', administratorId: '', mode: 'host', autoReplyIds: [], maxReplyRounds: 1, archived: false, pinned: false, readSeq: 0, lastSeq: 999, unreadCount: 999, unread: true, preview: '完成', createdAt: 1, updatedAt: 1 }
  45. const wrapper = mount(ConversationList, { props: { conversations: [conversation], agents: [] } })
  46. expect(wrapper.find('[aria-label="未读"]').exists()).toBe(true)
  47. expect(wrapper.find('.sidebar-item__row b').exists()).toBe(false)
  48. await wrapper.setProps({ conversations: [{ ...conversation, unread: false }] })
  49. expect(wrapper.find('[aria-label="未读"]').exists()).toBe(false)
  50. await wrapper.setProps({ conversations: [{ ...conversation, unread: undefined }] })
  51. expect(wrapper.find('[aria-label="未读"]').exists()).toBe(true)
  52. wrapper.unmount()
  53. })
  54. it('composes real member avatars and refreshes them without changing group membership', async () => {
  55. const agents: WorkspaceAgent[] = ['first','second'].map((id,index) => ({id,name:id,avatar:`yaoyao-mascot:v1:${index ? 'square' : 'circle'}:377fe6:friendly`,instructions:'',nodeId:'local',profile:'default',archived:false,revision:1,createdAt:1,updatedAt:1}))
  56. const c: WorkspaceConversation = {id:'g',kind:'group',name:'群聊',avatar:'data:image/png;base64,AA==',memberIds:['second','first'],instructions:'',administratorId:'first',mode:'host',autoReplyIds:[],maxReplyRounds:1,archived:false,pinned:false,readSeq:0,lastSeq:0,preview:'',createdAt:Date.now(),updatedAt:Date.now(),lastMessageAt:Date.now()}
  57. const wrapper = mount(ConversationList, {props:{conversations:[c],agents}})
  58. expect(wrapper.getComponent(TeamAvatar).props('members')!.map((m: {name:string}) => m.name)).toEqual(['second','first'])
  59. expect(wrapper.findAll('.team-avatar__member')).toHaveLength(2)
  60. expect(wrapper.find('.team-avatar__image').exists()).toBe(false)
  61. expect(wrapper.find('.sidebar-item__row small').text()).toMatch(/\d{2}:\d{2}/)
  62. await wrapper.setProps({agents:agents.map(a=>a.id==='first'?{...a,avatar:'yaoyao-mascot:v1:triangle:d94b52:curious'}:a)})
  63. expect(wrapper.getComponent(TeamAvatar).props('members')![1]!.avatar).toBe('yaoyao-mascot:v1:triangle:d94b52:curious')
  64. await wrapper.setProps({conversations:[{...c,activeRunId:'run',activeAgentId:'second',activeRunStatus:'running'}]})
  65. expect(wrapper.findAll('.team-avatar__member.agent-avatar--working')).toHaveLength(1)
  66. expect(wrapper.find('.team-avatar__member--1').classes()).toContain('agent-avatar--working')
  67. await wrapper.setProps({conversations:[{...c,activeRunId:'run',activeAgentId:'second',activeRunStatus:'waiting'}]})
  68. expect(wrapper.findAll('.team-avatar__member.agent-avatar--waiting')).toHaveLength(1)
  69. await wrapper.setProps({conversations:[c]})
  70. expect(wrapper.findAll('.team-avatar__member.agent-avatar--working')).toHaveLength(0)
  71. expect(wrapper.findAll('.team-avatar__member.agent-avatar--waiting')).toHaveLength(0)
  72. await wrapper.setProps({conversations:[{...c,kind:'direct',memberIds:['first'],activeRunId:'direct-run',activeAgentId:'first',activeRunStatus:'running'}]})
  73. expect(wrapper.find('.sidebar-item__icon .agent-avatar').exists() || wrapper.find('.sidebar-item .agent-avatar').exists()).toBe(true)
  74. expect(wrapper.find('.sidebar-item .agent-avatar--working').exists()).toBe(true)
  75. await wrapper.setProps({conversations:[{...c,kind:'direct',memberIds:['first'],activeRunId:'direct-run',activeAgentId:'first',activeRunStatus:'waiting'}]})
  76. expect(wrapper.find('.sidebar-item .agent-avatar--waiting').exists()).toBe(true)
  77. wrapper.unmount()
  78. })
  79. it.each([
  80. ['direct', '编辑资料'],
  81. ['group', '群聊设置'],
  82. ] as const)('opens settings for a %s conversation from its actions menu', async (kind, label) => {
  83. const conversation: WorkspaceConversation = {
  84. id: kind,
  85. kind,
  86. name: kind === 'direct' ? '机器人' : '群聊',
  87. avatar: '',
  88. memberIds: [],
  89. instructions: '',
  90. administratorId: '',
  91. mode: 'host',
  92. autoReplyIds: [],
  93. maxReplyRounds: 1,
  94. archived: false,
  95. pinned: false,
  96. readSeq: 0,
  97. lastSeq: 0,
  98. preview: '',
  99. createdAt: 1,
  100. updatedAt: 1,
  101. }
  102. const wrapper = mount(ConversationList, { attachTo: document.body, props: { conversations: [conversation] } })
  103. wrapper.getComponent(ResourceSidebar).vm.$emit('more', conversation.id, new MouseEvent('click', { clientX: 100, clientY: 100 }))
  104. await nextTick()
  105. const menu = document.body.querySelector<HTMLElement>('[aria-label="聊天操作"]')!
  106. const view = [...menu.querySelectorAll<HTMLButtonElement>('button')].find(button => button.textContent === label)!
  107. view.click()
  108. await nextTick()
  109. expect(wrapper.emitted('settings')).toEqual([[conversation.id]])
  110. expect(wrapper.emitted('select')).toBeUndefined()
  111. expect(document.body.querySelector('[aria-label="聊天操作"]')).toBeNull()
  112. wrapper.unmount()
  113. })
  114. it('keeps inline thinking in the process trace and its media out of the message body', () => {
  115. const messages = workspaceMessagesToUi([{
  116. id: 'inline-thinking', conversationId: 'chat', seq: 1, role: 'assistant',
  117. content: '<think>![过程图](/tmp/process.png)</think>[报告](/tmp/report.pdf)',
  118. reasoning: '', status: 'complete', attachments: [], tools: [], createdAt: 1,
  119. }])
  120. expect(messages[0].content).toBe('[报告](/tmp/report.pdf)')
  121. expect(messages[0].reasoning).toBe('![过程图](/tmp/process.png)')
  122. })
  123. it('keeps a Bot busy across group replies until its final active conversation finishes', async () => {
  124. const base: WorkspaceConversation = { id: 'direct', kind: 'direct', name: 'Bot', avatar: '', memberIds: ['a'], instructions: '', administratorId: 'a', mode: 'host', autoReplyIds: [], maxReplyRounds: 1, archived: false, pinned: false, readSeq: 0, lastSeq: 0, preview: '', createdAt: 1, updatedAt: 1 }
  125. const group: WorkspaceConversation = { ...base, id: 'group', kind: 'group', memberIds: ['a', 'b'], activeRunId: 'g-run', activeAgentStates: { a: 'running', b: 'waiting' } }
  126. const other: WorkspaceConversation = { ...group, id: 'other', activeRunId: 'other-run', activeAgentStates: { a: 'waiting' } }
  127. const wrapper = mount(ConversationList, { props: { conversations: [base, group, other, { ...base, id: 'unrelated', memberIds: ['unrelated'] }] } })
  128. const bot = () => wrapper.get('[data-sidebar-id="direct"]')
  129. expect(bot().find('.agent-avatar--working').exists()).toBe(true)
  130. expect(bot().find('.presence--working').exists()).toBe(true)
  131. expect(wrapper.get('[data-sidebar-id="unrelated"]').find('.agent-avatar--working').exists()).toBe(false)
  132. await wrapper.setProps({ conversations: [base, { ...group, activeRunId: undefined, activeAgentStates: {}, avatarSignals: { a: { id: 'done', state: 'success', at: Date.now() } } }, other] })
  133. expect(bot().find('.agent-avatar--waiting').exists()).toBe(true)
  134. await wrapper.setProps({ conversations: [base, { ...other, activeAgentStates: { a: 'queued' } }] })
  135. expect(bot().find('.agent-avatar--loading').exists()).toBe(true)
  136. await wrapper.setProps({ conversations: [base] })
  137. expect(bot().find('.agent-avatar--idle').exists()).toBe(true)
  138. expect(bot().find('.presence--working').exists()).toBe(false)
  139. wrapper.unmount()
  140. })