workspace-chat.spec.ts 59 KB

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