workspace-chat.spec.ts 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. import { test, expect, type Page } from '@playwright/test'
  2. import { writeFile } from 'node:fs/promises'
  3. async function login(page: Page) {
  4. await page.goto('/conversations')
  5. await page.getByRole('textbox', { name: '账号', exact: true }).fill('fixture')
  6. await page.getByRole('textbox', { name: '密码', exact: true }).fill('fixture-pass')
  7. await page.getByRole('button', { name: '登录', exact: true }).click()
  8. await expect(page.getByRole('heading', { name: '还没有聊天' })).toBeVisible()
  9. }
  10. async function openCreate(page: Page, name: '新建 Bot' | '新建群聊') {
  11. await page.locator('.desktop-sidebar .sidebar-create-trigger').click()
  12. await page.getByRole('menuitem', { name, exact: true }).click()
  13. }
  14. async function createAgent(page: Page, name: string) {
  15. await openCreate(page, '新建 Bot')
  16. const dialog = page.getByRole('dialog')
  17. await dialog.getByRole('textbox', { name: '名称', exact: true }).fill(name)
  18. await dialog
  19. .getByRole('textbox', { name: '角色提示词与规则', exact: true })
  20. .fill(`你是${name},每次回复给出验收证据。`)
  21. await dialog.getByRole('button', { name: `使用颜色 ${name === '产品经理' ? '#ff6b00' : '#00b9ac'}`, exact: true }).click()
  22. await dialog.locator('.mascot-grid--shape button').filter({ hasText: name === '产品经理' ? '圆形' : '小三角' }).first().click()
  23. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  24. await expect(page.getByRole('heading', { name, exact: true })).toBeVisible()
  25. }
  26. for (const { surface, kind } of [
  27. { surface: 'Web', kind: 'direct' }, { surface: 'desktop bridge', kind: 'direct' },
  28. { surface: 'Web', kind: 'group' }, { surface: 'desktop bridge', kind: 'group' },
  29. ] as const) {
  30. test(`sending and queued Bot replies keep the ${kind} chat frame stable through ${surface}`, async ({ page }, testInfo) => {
  31. await page.setViewportSize({ width: surface === 'Web' ? 1280 : 1024, height: 800 })
  32. if (surface === 'desktop bridge') await page.addInitScript(() => {
  33. Object.assign(window, { yaoyaoDesktop: { deviceHost: async () => ({ deviceHost: 'local' }) } })
  34. })
  35. await login(page)
  36. const capabilities = await (await page.request.get('/api/app/bootstrap')).json()
  37. const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin }
  38. const created = await page.request.post('/api/app/agents', { headers, data: { name: `发送布局验收 ${surface} ${kind}`, profile: 'default' } })
  39. expect(created.ok(), await created.text()).toBe(true)
  40. const agent = (await created.json()).agent
  41. const conversations = (await (await page.request.get('/api/app/conversations')).json()).conversations
  42. let conversation = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === agent.id)
  43. if (kind === 'group') {
  44. const peerResponse = await page.request.post('/api/app/agents', { headers, data: { name: `群聊布局成员 ${surface}`, profile: 'default' } })
  45. expect(peerResponse.ok(), await peerResponse.text()).toBe(true)
  46. const peer = (await peerResponse.json()).agent
  47. const groupResponse = await page.request.post('/api/app/conversations', { headers, data: {
  48. name: `发送布局群 ${surface}`, memberIds: [agent.id, peer.id], administratorId: agent.id, autoReplyIds: [agent.id],
  49. } })
  50. expect(groupResponse.ok(), await groupResponse.text()).toBe(true)
  51. conversation = (await groupResponse.json()).conversation
  52. }
  53. await page.goto(`/conversations/${conversation.id}`)
  54. const input = page.locator('.composer-textarea')
  55. await input.fill('[hold-workspace] 先执行第一条消息')
  56. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  57. await expect(page.getByTestId('chat-run-thinking-dots')).toBeVisible()
  58. await expect(page.locator('.message--assistant')).toBeVisible()
  59. await expect(input).toHaveValue('')
  60. await input.fill('排队执行第二条消息')
  61. const messageIds = await page.locator('[data-message-id]').evaluateAll(rows => rows.map(row => row.getAttribute('data-message-id')))
  62. await page.evaluate(() => {
  63. const selectors = ['.timeline-header', '.timeline', '.composer-area', '.composer-shell', '.composer-textarea', '.composer-tools', '.composer-actions']
  64. const nodes = selectors.map(selector => document.querySelector(selector)!)
  65. const previousMessages = [...document.querySelectorAll('[data-message-id]')]
  66. const samples: Array<{ connected: boolean; rects: number[][] }> = []
  67. let frame: number
  68. const record = () => {
  69. samples.push({ connected: [...nodes, ...previousMessages].every(node => node.isConnected), rects: nodes.map(node => {
  70. const box = node.getBoundingClientRect(); return [box.x, box.y, box.width, box.height]
  71. }) })
  72. frame = requestAnimationFrame(record)
  73. }
  74. record()
  75. Object.assign(window, { stopSendLayoutRecording: () => { cancelAnimationFrame(frame); return { selectors, samples } } })
  76. })
  77. let release!: () => void
  78. const gate = new Promise<void>(resolve => { release = resolve })
  79. const pattern = `**/api/app/conversations/${conversation.id}/messages`
  80. await page.route(pattern, async route => {
  81. expect(route.request().postDataJSON().deviceHost).toBe(surface === 'Web' ? null : 'local')
  82. await gate; await route.continue()
  83. })
  84. try {
  85. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  86. await expect(page.locator('.composer-sending')).toBeVisible()
  87. await page.evaluate(async () => { for (let count = 0; count < 3; count++) await new Promise(requestAnimationFrame) })
  88. release()
  89. await expect(page.getByText('正在等待可用机器人', { exact: true })).toBeVisible()
  90. await expect(input).toHaveValue('')
  91. await expect(page.locator('[data-message-id]')).toHaveCount(messageIds.length + 1)
  92. await page.screenshot({ path: testInfo.outputPath('send-layout-queued.png') })
  93. await page.request.post('http://127.0.0.1:19120/__release')
  94. await expect(page.locator('.message--assistant')).toHaveCount(2)
  95. await page.request.post('http://127.0.0.1:19120/__release')
  96. await expect(page.getByTestId('chat-run-thinking-dots')).toHaveCount(0)
  97. await input.fill('完成后再发送一条普通消息')
  98. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  99. await expect(page.locator('.message--user')).toHaveCount(3)
  100. await expect(page.locator('.message--assistant')).toHaveCount(3)
  101. await page.request.post('http://127.0.0.1:19120/__release')
  102. await expect(page.getByTestId('chat-run-thinking-dots')).toHaveCount(0)
  103. await expect(input).toHaveValue('')
  104. } finally {
  105. release(); await page.unroute(pattern)
  106. }
  107. const recording = await page.evaluate(() => (window as unknown as { stopSendLayoutRecording(): { selectors: string[]; samples: { connected: boolean; rects: number[][] }[] } }).stopSendLayoutRecording())
  108. const recordingPath = testInfo.outputPath('send-layout-frames.json')
  109. await writeFile(recordingPath, JSON.stringify(recording, null, 2))
  110. await testInfo.attach('send-layout-frames.json', { path: recordingPath, contentType: 'application/json' })
  111. expect(recording.samples.every(sample => sample.connected)).toBe(true)
  112. for (const [index, selector] of recording.selectors.entries()) {
  113. for (let coordinate = 0; coordinate < 4; coordinate++) {
  114. const values = recording.samples.map(sample => sample.rects[index]![coordinate]!)
  115. expect(Math.max(...values) - Math.min(...values), `${selector} coordinate ${coordinate} shifted`).toBeLessThanOrEqual(1)
  116. }
  117. }
  118. })
  119. }
  120. test('UTF-8 attachments stay inside the composer and retain their names after sending and reload', async ({ page }, testInfo) => {
  121. await login(page)
  122. const capabilities = await (await page.request.get('/api/app/bootstrap')).json()
  123. const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin }
  124. const created = await page.request.post('/api/app/agents', { headers, data: { name: '附件验收', profile: 'default' } })
  125. expect(created.ok(), await created.text()).toBe(true)
  126. const agent = (await created.json()).agent
  127. const conversations = (await (await page.request.get('/api/app/conversations')).json()).conversations
  128. const conversation = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === agent.id)
  129. await page.goto(`/conversations/${conversation.id}`)
  130. const name = '人工智能合同综合质量评估系统V2.0-信息采集表-待确认.docx'
  131. const certificate = 'CertificateSigningRequest.certSigningRequest'
  132. await page.locator('.composer-file-input').setInputFiles([
  133. { name, mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', buffer: Buffer.from('附件内容保持不变') },
  134. { name: certificate, mimeType: 'application/octet-stream', buffer: Buffer.from('certificate') },
  135. { name: '图片.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64') },
  136. ])
  137. await page.locator('.composer-textarea').fill('请按格式填写附件')
  138. for (const width of [1280, 655, 375]) {
  139. await page.setViewportSize({ width, height: 863 })
  140. const attachments = page.locator('.composer-shell > .composer-attachments')
  141. await expect(attachments.locator('.composer-attachment')).toHaveCount(3)
  142. await expect(attachments).toContainText(name)
  143. await expect(attachments.getByRole('img', { name: '图片.png' })).toBeVisible()
  144. const shell = (await page.locator('.composer-shell').boundingBox())!
  145. const tray = (await attachments.boundingBox())!
  146. const input = (await page.locator('.composer-textarea').boundingBox())!
  147. expect(tray.x).toBeGreaterThan(shell.x)
  148. expect(tray.y).toBeGreaterThan(shell.y)
  149. expect(tray.x + tray.width).toBeLessThan(shell.x + shell.width)
  150. expect(input.y - (tray.y + tray.height)).toBeGreaterThanOrEqual(0)
  151. expect(input.y - (tray.y + tray.height)).toBeLessThanOrEqual(12)
  152. expect(input.y + input.height).toBeLessThan(shell.y + shell.height)
  153. expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
  154. await page.screenshot({ path: testInfo.outputPath(`composer-attachments-${width}.png`) })
  155. }
  156. await page.getByRole('button', { name: '移除 图片.png', exact: true }).click()
  157. await page.getByRole('button', { name: `移除 ${certificate}`, exact: true }).click()
  158. await expect(page.locator('.composer-attachment')).toHaveCount(1)
  159. await expect(page.locator('.composer-textarea')).toHaveValue('请按格式填写附件')
  160. const uploaded = page.waitForResponse(response => response.url().endsWith('/api/app/uploads') && response.request().method() === 'POST')
  161. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  162. expect((await (await uploaded).json()).files[0].name).toBe(name)
  163. const file = page.locator('.message-file').filter({ hasText: name })
  164. await expect(file).toBeVisible()
  165. await expect(file).toHaveAccessibleName(new RegExp(`预览文件 ${name}`))
  166. await expect(page.locator('.composer-attachment')).toHaveCount(0)
  167. await page.reload()
  168. await expect(file).toBeVisible()
  169. await page.screenshot({ path: testInfo.outputPath('utf8-attachment-message.png') })
  170. })
  171. test('Bot unread dots sync across viewers and neither detail nor read requests delay navigation', async ({ page, context }, testInfo) => {
  172. await login(page)
  173. const capabilities = await (await page.request.get('/api/app/bootstrap')).json()
  174. const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin }
  175. const create = async (name: string) => {
  176. const response = await page.request.post('/api/app/agents', { headers, data: { name, profile: 'default' } })
  177. expect(response.ok(), await response.text()).toBe(true)
  178. return (await response.json()).agent
  179. }
  180. const first = await create('红点测试甲'), second = await create('红点测试乙')
  181. const conversations = (await (await page.request.get('/api/app/conversations')).json()).conversations
  182. const direct = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === first.id)
  183. const other = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === second.id)
  184. const groupResponse = await page.request.post('/api/app/conversations', { headers, data: { name: '红点测试群', memberIds: [first.id, second.id], administratorId: first.id } })
  185. expect(groupResponse.ok(), await groupResponse.text()).toBe(true)
  186. const group = (await groupResponse.json()).conversation
  187. await page.goto(`/conversations/${other.id}`)
  188. const viewer = await context.newPage()
  189. await viewer.goto(`/conversations/${other.id}`)
  190. try {
  191. for (const target of [direct, group]) {
  192. const sent = await page.request.post(`/api/app/conversations/${target.id}/messages`, { headers, data: { requestId: crypto.randomUUID(), content: '给出测试结果' } })
  193. expect(sent.ok(), await sent.text()).toBe(true)
  194. const row = page.locator(`.desktop-sidebar [data-sidebar-id="${target.id}"]`)
  195. const viewerRow = viewer.locator(`.desktop-sidebar [data-sidebar-id="${target.id}"]`)
  196. await expect(row.getByRole('img', { name: '未读', exact: true })).toBeVisible()
  197. await expect(viewerRow.getByRole('img', { name: '未读', exact: true })).toBeVisible()
  198. await expect(row.locator('b')).toHaveCount(0)
  199. await page.screenshot({ path: testInfo.outputPath(`unread-${target.kind}-dot.png`) })
  200. let releaseDetail!: () => void, releaseRead!: () => void
  201. const detailGate = new Promise<void>(resolve => { releaseDetail = resolve })
  202. const readGate = new Promise<void>(resolve => { releaseRead = resolve })
  203. const detailPattern = new RegExp(`/api/app/conversations/${target.id}(?:\\?.*)?$`)
  204. const readPattern = new RegExp(`/api/app/conversations/${target.id}/read(?:\\?.*)?$`)
  205. await page.route(detailPattern, async route => { await detailGate; await route.continue() })
  206. await page.route(readPattern, async route => { await readGate; await route.continue() })
  207. try {
  208. // Warm transcripts are already in the snapshot; a detail request is optional.
  209. await row.click()
  210. await expect(page.getByRole('heading', { name: target.name, exact: true })).toBeVisible()
  211. releaseDetail()
  212. await expect(page.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })).toBeEnabled()
  213. await expect(row.getByRole('img', { name: '未读', exact: true })).toHaveCount(0)
  214. releaseRead()
  215. await expect(viewerRow.getByRole('img', { name: '未读', exact: true })).toHaveCount(0)
  216. } finally {
  217. releaseDetail(); releaseRead()
  218. await page.unroute(detailPattern); await page.unroute(readPattern)
  219. }
  220. await page.locator(`.desktop-sidebar [data-sidebar-id="${other.id}"]`).click()
  221. }
  222. await expect(page.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })).toBeEnabled()
  223. await page.screenshot({ path: testInfo.outputPath('unread-desktop.png') })
  224. const sent = await page.request.post(`/api/app/conversations/${group.id}/messages`, { headers, data: { requestId: crypto.randomUUID(), content: '再次确认结果' } })
  225. expect(sent.ok(), await sent.text()).toBe(true)
  226. await page.setViewportSize({ width: 375, height: 812 })
  227. await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' })
  228. await page.goto('/conversations')
  229. await expect(page.getByRole('option').filter({ hasText: group.name }).getByRole('img', { name: '未读', exact: true })).toBeVisible()
  230. await page.screenshot({ path: testInfo.outputPath('unread-mobile.png') })
  231. } finally {
  232. await viewer.close()
  233. // This suite shares its fixture account; remove only the records created above.
  234. const archived = await page.request.patch(`/api/app/conversations/${group.id}`, { headers, data: { archived: true } })
  235. expect(archived.ok(), await archived.text()).toBe(true)
  236. const removed = await page.request.delete(`/api/app/conversations/${group.id}`, { headers })
  237. expect(removed.ok(), await removed.text()).toBe(true)
  238. for (const agent of [first, second]) {
  239. const archived = await page.request.patch(`/api/app/agents/${agent.id}`, { headers, data: { archived: true } })
  240. expect(archived.ok(), await archived.text()).toBe(true)
  241. const removed = await page.request.delete(`/api/app/agents/${agent.id}`, { headers })
  242. expect(removed.ok(), await removed.text()).toBe(true)
  243. }
  244. }
  245. })
  246. test('created roles and editable teams share a durable chat list without plugin calls', async ({
  247. page,
  248. context,
  249. }, testInfo) => {
  250. const pluginCalls: string[] = []
  251. page.on('request', (r) => {
  252. if (r.url().includes('/plugins/yaoyao')) pluginCalls.push(r.url())
  253. })
  254. await page.setViewportSize({ width: 1638, height: 874 })
  255. await login(page)
  256. const rail = page.locator('.desktop-sidebar')
  257. await expect(rail.locator('.sidebar-feature-nav')).toHaveCount(0)
  258. await expect(rail.locator('.sidebar-primary-action')).toHaveCount(0)
  259. await expect(rail).toHaveCSS('width', '360px')
  260. await expect(rail.locator('.sidebar-context__heading')).toHaveCount(0)
  261. await expect(rail.locator('.bot-logo-trigger .brand-mark')).toBeVisible()
  262. await expect(rail.locator('.sidebar-footer')).toBeVisible()
  263. await expect(rail.locator('.sidebar-account-switcher__main')).toContainText('fixture')
  264. await expect(rail.locator('.sidebar-account-switcher__main .account-initial-avatar')).toHaveText('F')
  265. await rail.locator('.sidebar-account-switcher__main').click()
  266. await expect(page.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['我的设置', '关于', '检测更新', '帮助', '进入聊天模式'])
  267. await page.getByRole('menuitem', { name: '关于', exact: true }).click()
  268. const about = page.getByRole('dialog', { name: '关于夭夭 AI', exact: true })
  269. await expect(about).toBeVisible()
  270. await expect(about.locator('.about-version')).toHaveText(/^版本 \d+\.\d+\.\d+$/)
  271. await expect(page.getByRole('dialog', { name: '我的设置', exact: true })).toHaveCount(0)
  272. await page.screenshot({ path: testInfo.outputPath('independent-about.png') })
  273. await page.keyboard.press('Escape')
  274. await expect(about).toHaveCount(0)
  275. await rail.getByRole('button', { name: '工具', exact: true }).click()
  276. await page.getByRole('menuitem', { name: '已连接应用', exact: true }).click()
  277. const apps = page.getByRole('dialog', { name: '已连接应用', exact: true })
  278. await expect(apps).toBeVisible()
  279. await expect(apps.getByRole('tab', { name: 'MCP 服务', exact: true })).toBeVisible()
  280. await expect(page.locator('.settings-sidebar')).toHaveCount(0)
  281. await page.screenshot({ path: testInfo.outputPath('independent-apps.png') })
  282. await apps.getByRole('button', { name: '关闭已连接应用', exact: true }).click()
  283. await rail.getByRole('button', { name: '工具', exact: true }).click()
  284. await page.getByRole('menuitem', { name: '自动化', exact: true }).click()
  285. await expect(page).toHaveURL(/\/conversations\/automations(?:\?.*)?$/)
  286. await expect(page.getByRole('main', { name: '自动化工作区' })).toBeVisible()
  287. await expect(page.locator('.schedule-day')).toHaveCount(7)
  288. await page.getByRole('tab', { name: '运行日志', exact: true }).click()
  289. await page.screenshot({ path: testInfo.outputPath('independent-automations.png') })
  290. await page.getByRole('button', { name: '返回聊天', exact: true }).click()
  291. await expect(page).toHaveURL(/\/conversations$/)
  292. await rail.locator('.sidebar-account-switcher__main').click()
  293. await page.getByRole('menuitem', { name: '我的设置', exact: true }).click()
  294. const settings = page.getByRole('dialog', { name: '我的设置', exact: true })
  295. await settings.getByRole('button', {name:'账号资料',exact:true}).click()
  296. await expect(settings.locator('.account-avatar-card')).toContainText('fixture')
  297. await expect(settings.locator('.account-avatar-card .account-initial-avatar')).toHaveText('F')
  298. await settings.locator('.account-avatar-card input[type=file]').setInputFiles({name:'account.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64')})
  299. await expect(settings.locator('.account-avatar-card .account-initial-avatar img')).toBeVisible()
  300. expect((await (await page.request.get('/api/app/bootstrap')).json()).user.avatar).toMatch(/^data:image\/png;base64,/)
  301. await settings.getByRole('button', {name:'使用首字母',exact:true}).click()
  302. await expect(settings.locator('.account-avatar-card .account-initial-avatar')).toHaveText('F')
  303. await settings.getByRole('button', { name: '身份与头像', exact: true }).click()
  304. await settings.getByRole('button', { name: '造型:星星', exact: true }).click()
  305. await settings.getByRole('button', { name: '使用颜色 #1488ff', exact: true }).click()
  306. await settings.locator('.mascot-grid--expression button').filter({ hasText: '开心' }).click()
  307. await settings.getByRole('button', { name: '保存更改', exact: true }).click()
  308. await expect(settings.getByRole('button', { name: '保存更改', exact: true })).toBeDisabled()
  309. await settings.getByRole('button', { name: '关闭我的设置', exact: true }).click()
  310. await rail.locator('.sidebar-account-switcher__main').click()
  311. await page.getByRole('menuitem', {name:'我的设置',exact:true}).click()
  312. await settings.getByRole('button', { name: '身份与头像', exact: true }).click()
  313. await expect(settings.getByRole('button', { name: '造型:星星', exact: true })).toHaveAttribute('aria-pressed', 'true')
  314. await expect(settings.getByRole('button', { name: '使用颜色 #1488ff', exact: true })).toHaveAttribute('aria-pressed', 'true')
  315. await expect(settings.locator('.mascot-grid--expression button').filter({ hasText: '开心' })).toHaveAttribute('aria-pressed', 'true')
  316. await settings.getByRole('button', { name: '关闭我的设置', exact: true }).click()
  317. await expect(rail.getByRole('checkbox', { name: '显示已归档' })).toHaveCount(0)
  318. const plus = rail.getByRole('button', { name: '新建', exact: true })
  319. await expect(rail.locator('.sidebar-collapse')).toHaveCount(0)
  320. await plus.click()
  321. await expect(page.getByRole('menu', { name: '新建聊天' }).getByRole('menuitem')).toHaveText(['新建 Bot', '添加远程机器人', '新建群聊'])
  322. await page.keyboard.press('Escape')
  323. await rail.getByRole('button', { name: '搜索', exact: true }).click()
  324. await expect(page.getByRole('dialog', { name: '搜索聊天' })).toBeVisible()
  325. await page.keyboard.press('Escape')
  326. await page.addInitScript(() => { Object.defineProperty(crypto, 'randomUUID', { value: undefined, configurable: true }) })
  327. await page.reload()
  328. await createAgent(page, '产品经理')
  329. await page.getByRole('button', {name:'聊天设置',exact:true}).click()
  330. const avatarEditor = page.getByRole('dialog')
  331. await expect(avatarEditor.locator('.color-grid button')).toHaveCount(11)
  332. await expect(avatarEditor.locator('.mascot-grid--expression button')).toHaveCount(10)
  333. await avatarEditor.getByRole('button', {name:'造型:星星',exact:true}).click()
  334. await avatarEditor.locator('.mascot-grid--expression button').filter({hasText:'自豪'}).click()
  335. await avatarEditor.getByRole('button', {name:'使用颜色 #000000',exact:true}).click()
  336. await avatarEditor.getByRole('button', {name:'保存',exact:true}).click()
  337. const identities = await (await page.request.get('/api/app/agents')).json()
  338. const edited = identities.agents.find((a: {name:string}) => a.name === '产品经理')
  339. expect(JSON.parse(edited.avatar.slice('yaoyao-avatar:v2:'.length))).toMatchObject({version:2,bodyId:'star',expression:'proud',color:'#000000'})
  340. await page.reload()
  341. await page.getByRole('button', {name:'聊天设置',exact:true}).click()
  342. await expect(avatarEditor.getByRole('button', {name:'造型:星星',exact:true})).toHaveAttribute('aria-pressed','true')
  343. await avatarEditor.locator('input[type=file]').setInputFiles({name:'avatar.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64')})
  344. await expect(avatarEditor.getByText('图片裁剪',{exact:true})).toBeVisible()
  345. let photoBytes=''
  346. for(const [label,crop] of [['圆形','circle'],['方形','square'],['圆角方形','rounded']]){
  347. await avatarEditor.getByRole('button',{name:label,exact:true}).click()
  348. await avatarEditor.getByRole('button',{name:'保存',exact:true}).click()
  349. const payload=await (await page.request.get('/api/app/agents')).json()
  350. const avatar=JSON.parse(payload.agents.find((a:{name:string})=>a.name==='产品经理').avatar.slice('yaoyao-avatar:v2:'.length))
  351. expect(avatar).toMatchObject({avatarMode:'image',imageCrop:crop})
  352. if(photoBytes)expect(avatar.imageDataURL).toBe(photoBytes)
  353. else photoBytes=avatar.imageDataURL
  354. await page.getByRole('button',{name:'聊天设置',exact:true}).click()
  355. }
  356. await avatarEditor.getByRole('button',{name:'动态吉祥物',exact:true}).click()
  357. await avatarEditor.locator('.mascot-grid--shape button').filter({hasText:'圆形'}).first().click()
  358. await avatarEditor.getByRole('button', {name:'使用颜色 #ff6b00',exact:true}).click()
  359. await avatarEditor.locator('.mascot-grid--expression button').filter({hasText:'默认'}).click()
  360. await avatarEditor.getByRole('button', {name:'保存',exact:true}).click()
  361. await expect(avatarEditor).toBeHidden()
  362. const composerInput = page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行')
  363. const sendButton = page.getByRole('button', { name: '发送消息', exact: true })
  364. await expect(composerInput).toBeEnabled()
  365. await expect(rail.getByText('聊天', { exact: true })).toHaveCount(0)
  366. await expect(rail.getByText('聊天列表', { exact: true })).toHaveCount(0)
  367. await expect(rail.locator('.sidebar-item__row strong').first()).toHaveCSS('font-size', '15px')
  368. await expect(rail.locator('.sidebar-item__row--secondary').first()).toHaveCSS('font-size', '13px')
  369. await expect(rail.locator('.sidebar-item__row small').first()).toHaveCSS('font-size', '10px')
  370. await composerInput.fill('请说明角色职责')
  371. await expect(sendButton).toBeEnabled()
  372. await sendButton.click()
  373. await expect(page.locator('.message--assistant')).toContainText('我是产品经理')
  374. for (const colorScheme of ['light', 'dark'] as const) {
  375. await page.emulateMedia({ colorScheme })
  376. for (const selector of ['.message__avatar.agent-avatar', '.desktop-sidebar .sidebar-item__icon--avatar', '.desktop-sidebar .agent-avatar']) {
  377. await expect(page.locator(selector).first()).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)')
  378. await expect(page.locator(selector).first()).toHaveCSS('background-image', 'none')
  379. }
  380. }
  381. await page.emulateMedia({ colorScheme: 'light' })
  382. await expect(page.locator('.message--assistant a').first()).toHaveAttribute(
  383. 'href',
  384. /\/api\/app\/files\/.+\/download/,
  385. )
  386. await page.locator('.message--assistant a').first().click()
  387. const textPreview = page.getByRole('dialog', { name: '预览 workspace-report.txt', exact: true })
  388. await expect(textPreview).toBeVisible()
  389. await expect(textPreview).toContainText('Fixture report')
  390. await textPreview.getByRole('button', { name: '关闭预览' }).click()
  391. const managerRow = rail.getByRole('option').filter({ hasText: '产品经理' })
  392. await managerRow.click({ button: 'right' })
  393. await page.getByRole('menuitem', {name:'置顶聊天',exact:true}).click()
  394. await managerRow.click({ button: 'right' })
  395. await expect(page.getByRole('menuitem', {name:'取消置顶',exact:true})).toBeVisible()
  396. await page.getByRole('menuitem', {name:'取消置顶',exact:true}).press('Escape')
  397. const directURL = page.url()
  398. await createAgent(page, '开发工程师')
  399. await expect(page.locator('.message')).toHaveCount(0)
  400. await openCreate(page, '新建群聊')
  401. const dialog = page.getByRole('dialog')
  402. await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('产品开发团队')
  403. await dialog.getByRole('checkbox', { name: '产品经理', exact: true }).check()
  404. await dialog.getByRole('checkbox', { name: '开发工程师', exact: true }).check()
  405. await dialog.getByText('高级协作设置', { exact: true }).click()
  406. await dialog.getByRole('combobox', { name: '协作方式', exact: true }).selectOption('host')
  407. await dialog
  408. .getByRole('combobox', { name: '负责人', exact: true })
  409. .selectOption({ label: '产品经理' })
  410. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  411. await expect(page.getByRole('heading', { name: '产品开发团队', exact: true })).toBeVisible()
  412. await expect(page.locator('.desktop-sidebar .sidebar-item')).toHaveCount(3)
  413. // Every cluster portrait must be the same portrait shown in that member's direct chat.
  414. const groupRow = page.locator('.desktop-sidebar .sidebar-item').filter({ hasText: '产品开发团队' })
  415. await expect(groupRow.locator('.team-avatar__member')).toHaveCount(2)
  416. for (const name of ['产品经理', '开发工程师']) {
  417. const portrait = `.agent-avatar[aria-label="${name} 的头像"]`
  418. const direct = page.locator('.desktop-sidebar .sidebar-item').filter({ hasText: name }).filter({ hasNot: page.locator('.team-avatar') }).locator(portrait)
  419. const member = groupRow.locator(portrait)
  420. await expect(member.locator('[data-part=outline] > :first-child')).toHaveAttribute('fill', await direct.locator('[data-part=outline] > :first-child').getAttribute('fill') || '')
  421. expect(await member.locator('[data-part=outline] > :first-child').evaluate(el => el.tagName))
  422. .toBe(await direct.locator('[data-part=outline] > :first-child').evaluate(el => el.tagName))
  423. }
  424. await expect(page.locator('.desktop-sidebar')).not.toContainText('话题')
  425. await expect(page.locator('.desktop-sidebar .sidebar-account-switcher__main')).not.toContainText(
  426. '通用助手',
  427. )
  428. await page.getByRole('button', { name: '聊天设置', exact: true }).click()
  429. await expect(dialog.getByRole('checkbox', { name: '产品经理', exact: true })).toBeDisabled()
  430. await expect(dialog.getByRole('checkbox', { name: '开发工程师', exact: true })).toBeEnabled()
  431. await dialog.getByRole('button', { name: '取消', exact: true }).click()
  432. await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('请@开发工程师给出实现结果')
  433. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  434. await expect(page.locator('.message--assistant')).toHaveCount(3)
  435. await expect(page.locator('.message--assistant').nth(1)).toContainText('我是开发工程师')
  436. await expect(page.locator('.run-status')).toHaveCount(0)
  437. const second = await context.newPage()
  438. await second.goto(page.url())
  439. await expect(second.locator('.message--assistant')).toHaveCount(3)
  440. await page.screenshot({ path: testInfo.outputPath('mixed-chats.png'), fullPage: true })
  441. const groupURL=page.url()
  442. await page.getByRole('button', { name: '聊天设置', exact: true }).click()
  443. await dialog.getByRole('checkbox', { name: '开发工程师', exact: true }).uncheck()
  444. await expect(dialog.getByRole('checkbox', { name: '产品经理', exact: true })).toBeDisabled()
  445. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  446. await expect(groupRow.locator('.team-avatar__member')).toHaveCount(1)
  447. await expect(page.locator('.message--assistant')).toHaveCount(3)
  448. await expect(second.locator('.desktop-sidebar .sidebar-item').filter({ hasText: '产品开发团队' }).locator('.team-avatar__member')).toHaveCount(1)
  449. await page.reload()
  450. await page.getByRole('button', { name: '聊天设置', exact: true }).click()
  451. await expect(dialog.getByRole('checkbox', { name: '开发工程师', exact: true })).not.toBeChecked()
  452. await dialog.getByRole('button', { name: '取消', exact: true }).click()
  453. await createAgent(page, '新成员')
  454. await page.goto(groupURL)
  455. await page.getByRole('button', { name: '聊天设置', exact: true }).click()
  456. await dialog.getByRole('checkbox', { name: '新成员', exact: true }).check()
  457. await dialog.getByRole('checkbox', { name: '产品经理', exact: true }).scrollIntoViewIfNeeded()
  458. await page.screenshot({ path: testInfo.outputPath('member-settings.png'), fullPage: true })
  459. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  460. await expect(groupRow.locator('.team-avatar__member')).toHaveCount(2)
  461. await expect(groupRow.locator('[aria-label="开发工程师 的头像"]')).toHaveCount(0)
  462. await expect(groupRow.locator('[aria-label="新成员 的头像"]')).toHaveCount(1)
  463. await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('请@新成员继续')
  464. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  465. await expect(page.locator('.message--assistant')).toHaveCount(6)
  466. await expect(page.locator('.message--assistant').nth(4)).toContainText('我是新成员')
  467. await page.goto('/files')
  468. await page.getByRole('button',{name:'查看来源',exact:true}).first().click()
  469. await expect(page).toHaveURL(groupURL)
  470. await groupRow.click({ button: 'right' })
  471. page.once('dialog', dialog => dialog.accept())
  472. await page.getByRole('menuitem', { name: '归档聊天', exact: true }).click()
  473. await expect(page.locator('.desktop-sidebar .sidebar-item')).toHaveCount(3)
  474. await page.locator('.desktop-sidebar .sidebar-search-trigger').click()
  475. const search = page.getByRole('dialog', { name: '搜索聊天', exact: true })
  476. await expect(search).toBeVisible()
  477. await search.getByRole('searchbox', { name: '搜索聊天', exact: true }).fill('产品开发')
  478. await expect(search.getByRole('listitem')).toHaveCount(0)
  479. await search.getByRole('tab', { name: '已归档', exact: true }).click()
  480. await expect(search.getByRole('searchbox')).toHaveValue('产品开发')
  481. await expect(search.getByRole('listitem')).toHaveCount(1)
  482. await page.screenshot({ path: testInfo.outputPath('archived-chat-search.png'), fullPage: true })
  483. await search.getByRole('listitem').getByRole('button').filter({ hasText: '产品开发团队' }).click()
  484. await expect(search).not.toBeVisible()
  485. await expect(page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行')).toBeDisabled()
  486. await page.goto(directURL)
  487. await expect(page.locator('.message--assistant')).toHaveCount(1)
  488. await expect(page.locator('.message--assistant')).toContainText('我是产品经理')
  489. expect(pluginCalls).toEqual([])
  490. await second.close()
  491. await page.goto('/conversations')
  492. await openCreate(page, '新建群聊')
  493. await dialog.locator('summary').filter({hasText:'从团队模板选择'}).click()
  494. await expect(dialog.getByRole('button', { name: '信息收集团队', exact: true })).toBeDisabled()
  495. await dialog.getByRole('button', { name: '取消', exact: true }).click()
  496. await createAgent(page, '模板成员四')
  497. await createAgent(page, '模板成员五')
  498. await openCreate(page, '新建群聊')
  499. await dialog.locator('summary').filter({hasText:'从团队模板选择'}).click()
  500. for (const name of ['信息收集团队', '产品设计团队', '软件开发团队', '文案书写团队', '项目管理团队', '数据分析团队', '会议协作团队', '运维保障团队']) {
  501. await expect(dialog.getByRole('button', { name, exact: true })).toBeEnabled()
  502. }
  503. await page.screenshot({ path: testInfo.outputPath('restored-team-presets.png'), fullPage: true })
  504. await dialog.getByRole('button', { name: '产品设计团队', exact: true }).click()
  505. await expect(dialog.getByRole('textbox', { name: '名称', exact: true })).toHaveValue('产品设计团队')
  506. await dialog.getByText('高级协作设置', { exact: true }).click()
  507. await dialog.getByRole('combobox', { name: '协作方式', exact: true }).selectOption('host')
  508. await dialog.getByRole('combobox', { name: '产品负责人对应的机器人', exact: true }).selectOption({ label: '产品经理' })
  509. await dialog.getByRole('combobox', { name: '交互设计对应的机器人', exact: true }).selectOption({ label: '开发工程师' })
  510. const [submitted] = await Promise.all([
  511. page.waitForRequest(r => r.method() === 'POST' && r.url().endsWith('/api/app/conversations')),
  512. dialog.getByRole('button', { name: '保存', exact: true }).click(),
  513. ])
  514. const payload = submitted.postDataJSON()
  515. expect(new Set(payload.memberIds).size).toBe(5)
  516. expect(Object.keys(payload.memberRoles)).toHaveLength(5)
  517. expect(payload.memberRoles[payload.administratorId].name).toBe('产品负责人')
  518. await expect(page.getByRole('heading', { name: '产品设计团队', exact: true })).toBeVisible()
  519. await page.getByRole('button', { name: '聊天设置', exact: true }).click()
  520. await expect(dialog.getByText('产品经理 · 产品负责人', { exact: false })).toBeVisible()
  521. await expect(dialog.getByText('开发工程师 · 交互设计', { exact: false })).toBeVisible()
  522. await dialog.getByRole('button', { name: '取消', exact: true }).click()
  523. await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('请汇总设计方案')
  524. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  525. await expect(page.locator('.message--assistant')).toContainText('我是产品经理')
  526. const conversationPath = new URL(page.url()).pathname.replace('/conversations/', '/api/app/conversations/')
  527. await expect.poll(async () => {
  528. const c = (await (await page.request.get(conversationPath)).json()).conversation
  529. return { active: Boolean(c.activeRunId), queued: c.queuedMessageCount }
  530. }).toEqual({ active: false, queued: 0 })
  531. const composer = page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行')
  532. await composer.fill('[hold-workspace] 正在执行的任务')
  533. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  534. await expect(page.getByRole('button', { name: '停止生成', exact: true })).toBeVisible()
  535. await expect.poll(async () => (await (await page.request.get(conversationPath)).json()).conversation.queuedMessageCount).toBe(0)
  536. await composer.fill('后续排队任务')
  537. await expect(page.getByRole('button', { name: '发送消息', exact: true })).toBeEnabled()
  538. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  539. await expect(page.locator('.message--user').last()).toContainText('后续排队任务')
  540. const detail = await (await page.request.get(new URL(page.url()).pathname.replace('/conversations/', '/api/app/conversations/'))).json()
  541. expect(detail.conversation.queuedMessageCount).toBe(1)
  542. await page.request.post('http://127.0.0.1:19120/__release')
  543. await expect.poll(async () => (await (await page.request.get(`/api/app/conversations/${detail.conversation.id}`)).json()).conversation.activeRunId).toBeUndefined()
  544. await page.setViewportSize({ width: 390, height: 844 })
  545. await page.getByRole('button', { name: '返回 Bot 列表', exact: true }).click()
  546. await expect(rail).toBeVisible()
  547. await expect(rail).toHaveCSS('width', '390px')
  548. await expect(page.locator('.mobile-header')).toBeHidden()
  549. await expect(rail.locator('.sidebar-feature-nav')).toHaveCount(0)
  550. await page.screenshot({ path: testInfo.outputPath('mobile-bot-list.png') })
  551. await rail.getByRole('button', { name: '新建', exact: true }).click()
  552. await expect(page.getByRole('menuitem', { name: '新建 Bot', exact: true })).toBeVisible()
  553. await page.keyboard.press('Escape')
  554. await rail.getByRole('button', { name: '搜索', exact: true }).click()
  555. await expect(page.getByRole('dialog', { name: '搜索聊天' })).toBeVisible()
  556. await expect(page.getByRole('tab', { name: '未归档', exact: true })).toBeVisible()
  557. await page.getByRole('button', { name: '关闭搜索', exact: true }).click()
  558. await rail.locator('.sidebar-account-switcher__main').click()
  559. await page.getByRole('menuitem', { name: '进入聊天模式', exact: true }).click()
  560. await expect(page).toHaveURL(/\/chat$/)
  561. await page.goto('/')
  562. await expect(page).toHaveURL(/\/chat$/)
  563. await page.setViewportSize({ width: 1280, height: 800 })
  564. await page.getByRole('button', { name: '设置与模式', exact: true }).click()
  565. await page.getByRole('menuitem', { name: '进入 Bot 模式', exact: true }).click()
  566. await page.goto('/')
  567. await expect(page).toHaveURL(/\/conversations$/)
  568. await page.reload()
  569. await expect(rail.locator('.bot-list-header')).toBeVisible()
  570. expect(pluginCalls).toEqual([])
  571. })
  572. test('subaccount allocation and Bot-only navigation work through the browser', async ({ page, browser }, testInfo) => {
  573. await login(page)
  574. await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
  575. await page.getByRole('menuitem', { name: '我的设置', exact: true }).click()
  576. const settings = page.getByRole('dialog', { name: '我的设置', exact: true })
  577. await settings.getByRole('button', { name: '用户与权限', exact: true }).click()
  578. const username = `child-${Date.now()}`
  579. await settings.locator('input[name=managed-username]').fill(username)
  580. await settings.locator('input[name=managed-temporary-password]').fill('temporary-pass')
  581. await settings.getByRole('listbox', { name: '新子账号的基础机器人' }).selectOption('default')
  582. await settings.getByRole('button', { name: '创建用户', exact: true }).click()
  583. await expect(settings.getByRole('listbox', { name: `分配给 ${username} 的基础机器人`, exact: true })).toHaveValues(['default'])
  584. await page.screenshot({ path: testInfo.outputPath('admin-agent-allocation.png'), fullPage: true })
  585. const childContext = await browser.newContext({ viewport: { width: 1280, height: 800 } })
  586. const child = await childContext.newPage()
  587. await child.goto(new URL('/conversations', page.url()).href)
  588. await child.getByRole('textbox', { name: '账号', exact: true }).fill(username)
  589. await child.getByRole('textbox', { name: '密码', exact: true }).fill('temporary-pass')
  590. await child.getByRole('button', { name: '登录', exact: true }).click()
  591. await child.getByLabel('当前密码', { exact: true }).fill('temporary-pass')
  592. await child.getByLabel('新密码', { exact: true }).fill('permanent-pass')
  593. await child.getByLabel('确认新密码', { exact: true }).fill('permanent-pass')
  594. await child.getByRole('button', { name: '保存并进入夭夭', exact: true }).click()
  595. await expect(child).toHaveURL(/\/conversations$/)
  596. await expect(child.getByRole('heading', { name: '还没有聊天' })).toBeVisible()
  597. await child.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
  598. await expect(child.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['我的设置', '关于', '帮助'])
  599. await child.keyboard.press('Escape')
  600. await openCreate(child, '新建 Bot')
  601. const dialog = child.getByRole('dialog')
  602. await expect(dialog.getByLabel('基础机器人').locator('option')).toHaveCount(1)
  603. await expect(dialog.getByLabel('基础机器人').locator('option')).toContainText('通用助手')
  604. await dialog.getByLabel('基础机器人').scrollIntoViewIfNeeded()
  605. await child.screenshot({ path: testInfo.outputPath('subaccount-assigned-source.png'), fullPage: true })
  606. await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('子账号助手')
  607. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  608. await expect(child.getByRole('heading', { name: '子账号助手', exact: true })).toBeVisible()
  609. for (const path of ['/history', '/files', '/chat']) {
  610. await child.goto(new URL(path, page.url()).href)
  611. await expect(child).toHaveURL(/\/conversations$/)
  612. }
  613. await childContext.close()
  614. })
  615. for (const mode of ['Bot 单聊', '群聊'] as const) {
  616. test(`${mode} 在完成前格式化流式 Markdown 并保留最终内容`, async ({ page }, testInfo) => {
  617. await login(page)
  618. await createAgent(page, `${mode}流式验证助手`)
  619. if (mode === '群聊') {
  620. await createAgent(page, '群聊流式协作成员')
  621. await openCreate(page, '新建群聊')
  622. const dialog = page.getByRole('dialog')
  623. await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('流式验证群')
  624. await dialog.getByRole('checkbox', { name: `${mode}流式验证助手`, exact: true }).check()
  625. await dialog.getByRole('checkbox', { name: '群聊流式协作成员', exact: true }).check()
  626. await dialog.getByText('高级协作设置', { exact: true }).click()
  627. await dialog.getByRole('combobox', { name: '协作方式', exact: true }).selectOption('host')
  628. await dialog.getByRole('combobox', { name: '负责人', exact: true }).selectOption({ label: `${mode}流式验证助手` })
  629. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  630. await expect(page.getByRole('heading', { name: '流式验证群', exact: true })).toBeVisible()
  631. }
  632. await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('[streaming-markdown] 演示排版')
  633. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  634. const message = page.locator('.message--assistant').last()
  635. await expect(message.locator('.markdown--streaming h1')).toHaveText('流式标题')
  636. await expect(message.locator('strong').filter({ hasText: '即时格式化' })).toBeVisible()
  637. await expect(message.locator('li')).toHaveText(['第一项', '第二项'])
  638. await expect(message.locator('pre code').first()).toContainText('const answer = 42')
  639. await expect(message).not.toContainText('最终完整标记')
  640. await page.screenshot({ path: testInfo.outputPath('streaming-markdown.png'), fullPage: true })
  641. const released = await page.request.post('http://127.0.0.1:19120/__release')
  642. expect(released.ok()).toBe(true)
  643. await expect(message).toContainText('最终完整标记')
  644. await expect(message.locator('table')).toContainText('项目')
  645. await expect(message.locator('.markdown--streaming')).toHaveCount(0)
  646. })
  647. }
  648. test('only chat messages introduce files across transcript and library', async ({ page }, testInfo) => {
  649. await login(page)
  650. await createAgent(page, '文件展示验收')
  651. await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('[message-files] 请发送报告')
  652. await page.getByRole('button', { name: '发送消息', exact: true }).click()
  653. const report = page.locator('.message--assistant .file-link-card').first()
  654. await expect(report).toBeVisible()
  655. const process = page.locator('.turn-trace')
  656. await expect(process).toHaveCount(0)
  657. await page.locator('.composer-tool[title="显示思考"]').click()
  658. await expect(process).toHaveCount(1)
  659. await process.locator('summary').first().click()
  660. await expect(process).toContainText('/tmp/process.pdf')
  661. await expect(process.locator('img, .file-link-card')).toHaveCount(0)
  662. const conversationId = new URL(page.url()).pathname.split('/').at(-1)!
  663. const files = await (await page.request.get(`/api/app/files?session_id=${encodeURIComponent(conversationId)}`)).json()
  664. expect(files.items.map((file: { name: string }) => file.name)).toEqual(['workspace-report.txt'])
  665. await report.click()
  666. const preview = page.getByRole('dialog', { name: '预览 workspace-report.txt', exact: true })
  667. await expect(preview).toContainText('Fixture report')
  668. await preview.getByRole('button', { name: '关闭预览' }).click()
  669. await page.reload()
  670. await expect(page.locator('.message--assistant .file-link-card')).toHaveCount(1)
  671. await expect(page.locator('.turn-trace')).toHaveCount(0)
  672. await page.locator('.composer-tool[title="显示思考"]').click()
  673. await page.locator('.turn-trace summary').first().click()
  674. await page.setViewportSize({ width: 1280, height: 1100 })
  675. await page.screenshot({ path: testInfo.outputPath('message-files-web.png') })
  676. })
  677. test('Bot transcript switches from cache and preserves the viewport during history and live updates', async ({ page }, testInfo) => {
  678. await login(page)
  679. const bootstrap = await (await page.request.get('/api/app/bootstrap')).json()
  680. const headers = { 'X-CSRF-Token': bootstrap.csrfToken }
  681. const seed = await (await page.request.post('/__test/workspace-transcript', { headers })).json()
  682. try {
  683. await page.goto(`/conversations/${seed.conversationId}`)
  684. await expect(page.locator('.message')).toHaveCount(50)
  685. const scroller = page.locator('.timeline')
  686. for (let index = 0; index < 4; index++) {
  687. await scroller.evaluate(el => { el.scrollTop = 0 })
  688. const before = await page.locator('.message').first().getAttribute('data-message-id')
  689. await page.getByRole('button', { name: '加载更早消息', exact: true }).click()
  690. await expect(page.locator('.message')).toHaveCount(100 + index * 50)
  691. expect(await page.locator(`[data-message-id="${before}"]`).evaluate(el => {
  692. const scroller = el.closest('.timeline')!; return el.getBoundingClientRect().top - scroller.getBoundingClientRect().top
  693. })).toBeGreaterThanOrEqual(-10)
  694. }
  695. // Returning keeps loaded history in memory but mounts only the 120-message tail.
  696. await page.locator('.desktop-sidebar .bot-logo-trigger').click()
  697. await expect(page.locator('.desktop-sidebar .sidebar-item').filter({ hasText: '长会话性能验收' })).toBeVisible()
  698. const requests: string[] = []
  699. page.on('request', request => { if (request.method() === 'GET') requests.push(new URL(request.url()).pathname) })
  700. await page.locator(`.desktop-sidebar [data-sidebar-id="${seed.conversationId}"]`).click()
  701. await expect(page.locator('.message')).toHaveCount(120)
  702. expect(requests).not.toContain(`/api/app/conversations/${seed.conversationId}`)
  703. await scroller.hover(); await page.mouse.wheel(0, -600)
  704. await expect(page.getByRole('button', { name: '回到底部', exact: true })).toBeVisible()
  705. const top = await scroller.evaluate(el => el.scrollTop)
  706. await page.request.post(`/__test/workspace-transcript?id=${seed.conversationId}`, { headers })
  707. await expect(page.locator('.message').last()).toContainText('实时追加的内容')
  708. expect(Math.abs(await scroller.evaluate(el => el.scrollTop) - top)).toBeLessThan(4)
  709. expect(requests).not.toContain('/api/app/agents')
  710. expect(requests).not.toContain('/api/app/events')
  711. await page.screenshot({ path: testInfo.outputPath('bot-cached-transcript.png') })
  712. await page.setViewportSize({ width: 375, height: 812 })
  713. await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' })
  714. await expect(page.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })).toBeVisible()
  715. await page.screenshot({ path: testInfo.outputPath('bot-cached-transcript-mobile-dark.png') })
  716. } finally {
  717. await page.request.patch(`/api/app/agents/${seed.agentId}`, { headers, data: { archived: true } })
  718. await page.request.delete(`/api/app/agents/${seed.agentId}`, { headers })
  719. }
  720. })
  721. test('Bot startup loads only the selected transcript and fetches large tool output after expansion', async ({ page }) => {
  722. await login(page)
  723. const bootstrap = await (await page.request.get('/api/app/bootstrap')).json()
  724. const headers = { 'X-CSRF-Token': bootstrap.csrfToken }
  725. const seeded = await page.request.post('/__test/workspace-transcript?tools=large', { headers })
  726. expect(seeded.ok(), await seeded.text()).toBe(true)
  727. const seed = await seeded.json()
  728. const requests: string[] = []
  729. page.on('request', request => { if (request.method() === 'GET') requests.push(request.url()) })
  730. const snapshot = page.waitForResponse(response => response.url().includes('/api/app/workspace/snapshot?'))
  731. await page.goto('/conversations')
  732. expect((await (await snapshot).json()).details).toEqual([])
  733. await page.locator(`.desktop-sidebar [data-sidebar-id="${seed.conversationId}"]`).click()
  734. await expect(page.locator('.message')).toHaveCount(50)
  735. await page.locator('.composer-tool[title="显示思考"]').click()
  736. await page.locator('.turn-trace summary').click()
  737. const tool = page.locator('.tool-trace').filter({ hasText: 'read_file' })
  738. await expect(tool).toBeVisible()
  739. expect(requests.some(url => url.includes('/tools/'))).toBe(false)
  740. await tool.getByRole('button', { name: /read_file/ }).click()
  741. await expect(tool.locator('pre').last()).toContainText('工具输出末尾')
  742. expect(requests.filter(url => url.includes('/tools/'))).toHaveLength(1)
  743. const reloaded = page.waitForResponse(response => response.url().includes('/api/app/workspace/snapshot?'))
  744. await page.reload()
  745. const selected = await (await reloaded).json()
  746. expect(selected.details).toHaveLength(1)
  747. expect(selected.details[0].conversation.id).toBe(seed.conversationId)
  748. expect(JSON.stringify(selected)).not.toContain('工具输出末尾')
  749. await expect(page.locator('.message')).toHaveCount(50)
  750. })
  751. test('account update checks show loading, available versions and retry on desktop and phone', async ({ page }, testInfo) => {
  752. await login(page)
  753. const current = { schemaVersion: 1, releaseVersion: '0.4.17', webVersion: '0.4.17', gitTag: 'v0.4.17' }
  754. const status = { current, latest: { ...current, webVersion: '0.4.18', releaseVersion: '0.4.18', gitTag: 'v0.4.18' }, supported: true, installationMode: 'source', updateAvailable: true, canRollback: false, releasePageUrl: 'https://github.com/Lsamien/yaoyao/releases/tag/v0.4.18' }
  755. await page.route('**/api/app/system/update/status', route => route.fulfill({ json: status }))
  756. let failed = false
  757. let releaseCheck: (() => void) | undefined
  758. await page.route('**/api/app/system/update/check', async route => {
  759. await new Promise<void>(resolve => { releaseCheck = resolve })
  760. await route.fulfill(failed ? { status: 502, json: { error: '暂时无法连接更新服务' } } : { json: status })
  761. })
  762. for (const width of [1280, 390]) {
  763. await page.setViewportSize({ width, height: 866 })
  764. await page.emulateMedia({ colorScheme: width === 390 ? 'dark' : 'light', reducedMotion: 'reduce' })
  765. const account = page.locator('.desktop-sidebar .sidebar-account-switcher__main')
  766. await expect(page.locator('.sidebar-settings-trigger')).toHaveCount(0)
  767. await account.click()
  768. // The menu's dismiss layer receives the second pointer click over the account.
  769. const accountRect = (await account.boundingBox())!
  770. await page.mouse.click(accountRect.x + accountRect.width / 2, accountRect.y + accountRect.height / 2)
  771. await expect(page.getByRole('menu', { name: '账号菜单' })).toHaveCount(0)
  772. await account.click()
  773. await page.screenshot({ path: testInfo.outputPath(`update-menu-${width}.png`) })
  774. await page.getByRole('menuitem', { name: '检测更新', exact: true }).click()
  775. const dialog = page.getByRole('dialog', { name: '检测更新', exact: true })
  776. await expect(dialog.getByRole('status')).toHaveText('正在检测更新…')
  777. await expect(dialog.getByRole('button', { name: '正在检测…', exact: true })).toBeDisabled()
  778. await expect.poll(() => Boolean(releaseCheck)).toBe(true)
  779. releaseCheck!(); releaseCheck = undefined
  780. await expect(dialog.getByRole('status')).toHaveText('发现新版本 0.4.18')
  781. await page.screenshot({ path: testInfo.outputPath(`update-available-${width}.png`) })
  782. expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
  783. failed = true
  784. await dialog.getByRole('button', { name: '重新检测', exact: true }).click()
  785. await expect.poll(() => Boolean(releaseCheck)).toBe(true)
  786. releaseCheck!(); releaseCheck = undefined
  787. await expect(dialog.getByRole('alert')).toContainText('暂时无法连接更新服务')
  788. await expect(dialog.getByRole('button', { name: '前往更新', exact: true })).toHaveCount(0)
  789. failed = false
  790. await dialog.getByRole('button', { name: '重试', exact: true }).click()
  791. await expect.poll(() => Boolean(releaseCheck)).toBe(true)
  792. releaseCheck!(); releaseCheck = undefined
  793. await expect(dialog.getByRole('button', { name: '前往更新', exact: true })).toBeVisible()
  794. await page.keyboard.press('Escape')
  795. await expect(dialog).toHaveCount(0)
  796. await expect(account).toBeFocused()
  797. }
  798. })
  799. test('self-registered subaccount approval supports Bot replies, reload and isolation', async ({ page, browser }, testInfo) => {
  800. const childContext = await browser.newContext({ viewport: { width: 1280, height: 800 } })
  801. const child = await childContext.newPage()
  802. const username = `registered-${Date.now()}`
  803. const denied: string[] = []
  804. child.on('response', response => { if (response.status() === 403 && response.url().includes('/api/app/')) denied.push(new URL(response.url()).pathname) })
  805. try {
  806. await child.goto('/conversations')
  807. await child.getByRole('button', { name: '没有账号?注册子账号' }).click()
  808. await child.getByRole('textbox', { name: '账号', exact: true }).fill(username)
  809. await child.getByLabel('密码', { exact: true }).fill('child-password')
  810. await child.getByLabel('确认密码', { exact: true }).fill('child-password')
  811. await child.getByRole('button', { name: '注册子账号', exact: true }).click()
  812. await expect(child.getByRole('status')).toContainText('注册成功')
  813. await child.getByLabel('密码', { exact: true }).fill('child-password')
  814. await child.getByRole('button', { name: '登录', exact: true }).click()
  815. await expect(child.getByRole('alert')).toContainText('尚未开通')
  816. await login(page)
  817. await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click()
  818. await page.getByRole('menuitem', { name: '我的设置', exact: true }).click()
  819. const settings = page.getByRole('dialog', { name: '我的设置', exact: true })
  820. await settings.getByRole('button', { name: '用户与权限', exact: true }).click()
  821. const row = settings.locator('.user').filter({ hasText: username })
  822. await expect(row).toContainText('待管理员开通')
  823. await expect(row.getByRole('button', { name: '分配并开通' })).toBeDisabled()
  824. await row.getByRole('listbox').selectOption('default')
  825. await row.getByRole('button', { name: '分配并开通' }).click()
  826. await expect(row).toContainText('普通用户')
  827. await child.getByLabel('密码', { exact: true }).fill('child-password')
  828. await child.getByRole('button', { name: '登录', exact: true }).click()
  829. await expect(child.getByRole('heading', { name: '还没有聊天' })).toBeVisible()
  830. denied.length = 0
  831. await openCreate(child, '新建 Bot')
  832. const dialog = child.getByRole('dialog')
  833. await expect(dialog.getByLabel('基础机器人').locator('option')).toHaveCount(1)
  834. await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('注册验收助手')
  835. await dialog.getByRole('button', { name: '保存', exact: true }).click()
  836. await expect(child.getByRole('heading', { name: '注册验收助手', exact: true })).toBeVisible()
  837. const composer = child.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })
  838. await composer.fill('注册后验证 Bot 回复')
  839. await composer.press('Enter')
  840. await expect.poll(async () => {
  841. const id = new URL(child.url()).pathname.split('/').at(-1)
  842. const response = await child.request.get(`/api/app/conversations/${id}/messages`)
  843. const value = await response.json()
  844. return value.messages?.some((m: any) => m.role === 'assistant' && m.status === 'complete' && m.content)
  845. }).toBe(true)
  846. await expect(child.getByText('会话独立保存', { exact: true })).toBeVisible()
  847. await childContext.setOffline(true)
  848. await expect(child.getByText('网络已断开,恢复连接后将自动同步', { exact: true })).toBeVisible()
  849. await childContext.setOffline(false)
  850. await expect(child.getByText('网络已断开,恢复连接后将自动同步', { exact: true })).toBeHidden({ timeout: 15_000 })
  851. await child.reload()
  852. await expect(child.getByRole('heading', { name: '注册验收助手', exact: true })).toBeVisible()
  853. await expect(child.getByText('注册后验证 Bot 回复', { exact: true }).first()).toBeVisible()
  854. expect((await (await page.request.get('/api/app/agents')).json()).agents.some((a: any) => a.name === '注册验收助手')).toBe(false)
  855. expect(denied).toEqual([])
  856. await child.screenshot({ path: testInfo.outputPath('registered-subaccount-bot.png'), fullPage: true })
  857. } finally { await childContext.close() }
  858. })