import { test, expect, type Page } from '@playwright/test' import { writeFile } from 'node:fs/promises' async function login(page: Page) { await page.goto('/conversations') await page.getByRole('textbox', { name: '账号', exact: true }).fill('fixture') await page.getByRole('textbox', { name: '密码', exact: true }).fill('fixture-pass') await page.getByRole('button', { name: '登录', exact: true }).click() await expect(page.getByRole('heading', { name: '还没有聊天' })).toBeVisible() } async function openCreate(page: Page, name: '新建 Bot' | '新建群聊') { await page.locator('.desktop-sidebar .sidebar-create-trigger').click() await page.getByRole('menuitem', { name, exact: true }).click() } async function createAgent(page: Page, name: string) { await openCreate(page, '新建 Bot') const dialog = page.getByRole('dialog') await dialog.getByRole('textbox', { name: '名称', exact: true }).fill(name) await dialog .getByRole('textbox', { name: '角色提示词与规则', exact: true }) .fill(`你是${name},每次回复给出验收证据。`) await dialog.getByRole('button', { name: `使用颜色 ${name === '产品经理' ? '#ff6b00' : '#00b9ac'}`, exact: true }).click() await dialog.locator('.mascot-grid--shape button').filter({ hasText: name === '产品经理' ? '圆形' : '小三角' }).first().click() await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(page.getByRole('heading', { name, exact: true })).toBeVisible() } for (const { surface, kind } of [ { surface: 'Web', kind: 'direct' }, { surface: 'desktop bridge', kind: 'direct' }, { surface: 'Web', kind: 'group' }, { surface: 'desktop bridge', kind: 'group' }, ] as const) { test(`sending and queued Bot replies keep the ${kind} chat frame stable through ${surface}`, async ({ page }, testInfo) => { await page.setViewportSize({ width: surface === 'Web' ? 1280 : 1024, height: 800 }) if (surface === 'desktop bridge') await page.addInitScript(() => { Object.assign(window, { yaoyaoDesktop: { deviceHost: async () => ({ deviceHost: 'local' }) } }) }) await login(page) const capabilities = await (await page.request.get('/api/realtime/capabilities')).json() const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin } const created = await page.request.post('/api/app/agents', { headers, data: { name: `发送布局验收 ${surface} ${kind}`, profile: 'default' } }) expect(created.ok(), await created.text()).toBe(true) const agent = (await created.json()).agent const conversations = (await (await page.request.get('/api/app/conversations')).json()).conversations let conversation = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === agent.id) if (kind === 'group') { const peerResponse = await page.request.post('/api/app/agents', { headers, data: { name: `群聊布局成员 ${surface}`, profile: 'default' } }) expect(peerResponse.ok(), await peerResponse.text()).toBe(true) const peer = (await peerResponse.json()).agent const groupResponse = await page.request.post('/api/app/conversations', { headers, data: { name: `发送布局群 ${surface}`, memberIds: [agent.id, peer.id], administratorId: agent.id, autoReplyIds: [agent.id], } }) expect(groupResponse.ok(), await groupResponse.text()).toBe(true) conversation = (await groupResponse.json()).conversation } await page.goto(`/conversations/${conversation.id}`) const input = page.locator('.composer-textarea') await input.fill('[hold-workspace] 先执行第一条消息') await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.getByTestId('chat-run-thinking-dots')).toBeVisible() await expect(page.locator('.message--assistant')).toBeVisible() await expect(input).toHaveValue('') await input.fill('排队执行第二条消息') const messageIds = await page.locator('[data-message-id]').evaluateAll(rows => rows.map(row => row.getAttribute('data-message-id'))) await page.evaluate(() => { const selectors = ['.timeline-header', '.timeline', '.composer-area', '.composer-shell', '.composer-textarea', '.composer-tools', '.composer-actions'] const nodes = selectors.map(selector => document.querySelector(selector)!) const previousMessages = [...document.querySelectorAll('[data-message-id]')] const samples: Array<{ connected: boolean; rects: number[][] }> = [] let frame: number const record = () => { samples.push({ connected: [...nodes, ...previousMessages].every(node => node.isConnected), rects: nodes.map(node => { const box = node.getBoundingClientRect(); return [box.x, box.y, box.width, box.height] }) }) frame = requestAnimationFrame(record) } record() Object.assign(window, { stopSendLayoutRecording: () => { cancelAnimationFrame(frame); return { selectors, samples } } }) }) let release!: () => void const gate = new Promise(resolve => { release = resolve }) const pattern = `**/api/app/conversations/${conversation.id}/messages` await page.route(pattern, async route => { expect(route.request().postDataJSON().deviceHost).toBe(surface === 'Web' ? null : 'local') await gate; await route.continue() }) try { await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.locator('.composer-sending')).toBeVisible() await page.evaluate(async () => { for (let count = 0; count < 3; count++) await new Promise(requestAnimationFrame) }) release() await expect(page.getByText('正在等待可用机器人', { exact: true })).toBeVisible() await expect(input).toHaveValue('') await expect(page.locator('[data-message-id]')).toHaveCount(messageIds.length + 1) await page.screenshot({ path: testInfo.outputPath('send-layout-queued.png') }) await page.request.post('http://127.0.0.1:19120/__release') await expect(page.locator('.message--assistant')).toHaveCount(2) await page.request.post('http://127.0.0.1:19120/__release') await expect(page.getByTestId('chat-run-thinking-dots')).toHaveCount(0) await input.fill('完成后再发送一条普通消息') await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.locator('.message--user')).toHaveCount(3) await expect(page.locator('.message--assistant')).toHaveCount(3) await page.request.post('http://127.0.0.1:19120/__release') await expect(page.getByTestId('chat-run-thinking-dots')).toHaveCount(0) await expect(input).toHaveValue('') } finally { release(); await page.unroute(pattern) } const recording = await page.evaluate(() => (window as unknown as { stopSendLayoutRecording(): { selectors: string[]; samples: { connected: boolean; rects: number[][] }[] } }).stopSendLayoutRecording()) const recordingPath = testInfo.outputPath('send-layout-frames.json') await writeFile(recordingPath, JSON.stringify(recording, null, 2)) await testInfo.attach('send-layout-frames.json', { path: recordingPath, contentType: 'application/json' }) expect(recording.samples.every(sample => sample.connected)).toBe(true) for (const [index, selector] of recording.selectors.entries()) { for (let coordinate = 0; coordinate < 4; coordinate++) { const values = recording.samples.map(sample => sample.rects[index]![coordinate]!) expect(Math.max(...values) - Math.min(...values), `${selector} coordinate ${coordinate} shifted`).toBeLessThanOrEqual(1) } } }) } test('UTF-8 attachments stay inside the composer and retain their names after sending and reload', async ({ page }, testInfo) => { await login(page) const capabilities = await (await page.request.get('/api/realtime/capabilities')).json() const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin } const created = await page.request.post('/api/app/agents', { headers, data: { name: '附件验收', profile: 'default' } }) expect(created.ok(), await created.text()).toBe(true) const agent = (await created.json()).agent const conversations = (await (await page.request.get('/api/app/conversations')).json()).conversations const conversation = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === agent.id) await page.goto(`/conversations/${conversation.id}`) const name = '人工智能合同综合质量评估系统V2.0-信息采集表-待确认.docx' const certificate = 'CertificateSigningRequest.certSigningRequest' await page.locator('.composer-file-input').setInputFiles([ { name, mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', buffer: Buffer.from('附件内容保持不变') }, { name: certificate, mimeType: 'application/octet-stream', buffer: Buffer.from('certificate') }, { name: '图片.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64') }, ]) await page.locator('.composer-textarea').fill('请按格式填写附件') for (const width of [1280, 655, 375]) { await page.setViewportSize({ width, height: 863 }) const attachments = page.locator('.composer-shell > .composer-attachments') await expect(attachments.locator('.composer-attachment')).toHaveCount(3) await expect(attachments).toContainText(name) await expect(attachments.getByRole('img', { name: '图片.png' })).toBeVisible() const shell = (await page.locator('.composer-shell').boundingBox())! const tray = (await attachments.boundingBox())! const input = (await page.locator('.composer-textarea').boundingBox())! expect(tray.x).toBeGreaterThan(shell.x) expect(tray.y).toBeGreaterThan(shell.y) expect(tray.x + tray.width).toBeLessThan(shell.x + shell.width) expect(input.y - (tray.y + tray.height)).toBeGreaterThanOrEqual(0) expect(input.y - (tray.y + tray.height)).toBeLessThanOrEqual(12) expect(input.y + input.height).toBeLessThan(shell.y + shell.height) expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true) await page.screenshot({ path: testInfo.outputPath(`composer-attachments-${width}.png`) }) } await page.getByRole('button', { name: '移除 图片.png', exact: true }).click() await page.getByRole('button', { name: `移除 ${certificate}`, exact: true }).click() await expect(page.locator('.composer-attachment')).toHaveCount(1) await expect(page.locator('.composer-textarea')).toHaveValue('请按格式填写附件') const uploaded = page.waitForResponse(response => response.url().endsWith('/api/app/uploads') && response.request().method() === 'POST') await page.getByRole('button', { name: '发送消息', exact: true }).click() expect((await (await uploaded).json()).files[0].name).toBe(name) const file = page.locator('.message-file').filter({ hasText: name }) await expect(file).toBeVisible() await expect(file).toHaveAccessibleName(new RegExp(`预览文件 ${name}`)) await expect(page.locator('.composer-attachment')).toHaveCount(0) await page.reload() await expect(file).toBeVisible() await page.screenshot({ path: testInfo.outputPath('utf8-attachment-message.png') }) }) test('Bot unread dots sync across viewers and neither detail nor read requests delay navigation', async ({ page, context }, testInfo) => { await login(page) const capabilities = await (await page.request.get('/api/realtime/capabilities')).json() const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin } const create = async (name: string) => { const response = await page.request.post('/api/app/agents', { headers, data: { name, profile: 'default' } }) expect(response.ok(), await response.text()).toBe(true) return (await response.json()).agent } const first = await create('红点测试甲'), second = await create('红点测试乙') const conversations = (await (await page.request.get('/api/app/conversations')).json()).conversations const direct = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === first.id) const other = conversations.find((c: any) => c.kind === 'direct' && c.memberIds[0] === second.id) const groupResponse = await page.request.post('/api/app/conversations', { headers, data: { name: '红点测试群', memberIds: [first.id, second.id], administratorId: first.id } }) expect(groupResponse.ok(), await groupResponse.text()).toBe(true) const group = (await groupResponse.json()).conversation await page.goto(`/conversations/${other.id}`) const viewer = await context.newPage() await viewer.goto(`/conversations/${other.id}`) try { for (const target of [direct, group]) { const sent = await page.request.post(`/api/app/conversations/${target.id}/messages`, { headers, data: { requestId: crypto.randomUUID(), content: '给出测试结果' } }) expect(sent.ok(), await sent.text()).toBe(true) const row = page.locator(`.desktop-sidebar [data-sidebar-id="${target.id}"]`) const viewerRow = viewer.locator(`.desktop-sidebar [data-sidebar-id="${target.id}"]`) await expect(row.getByRole('img', { name: '未读', exact: true })).toBeVisible() await expect(viewerRow.getByRole('img', { name: '未读', exact: true })).toBeVisible() await expect(row.locator('b')).toHaveCount(0) await page.screenshot({ path: testInfo.outputPath(`unread-${target.kind}-dot.png`) }) let releaseDetail!: () => void, releaseRead!: () => void const detailGate = new Promise(resolve => { releaseDetail = resolve }) const readGate = new Promise(resolve => { releaseRead = resolve }) const detailPattern = new RegExp(`/api/app/conversations/${target.id}(?:\\?.*)?$`) const readPattern = new RegExp(`/api/app/conversations/${target.id}/read(?:\\?.*)?$`) await page.route(detailPattern, async route => { await detailGate; await route.continue() }) await page.route(readPattern, async route => { await readGate; await route.continue() }) try { // Warm transcripts are already in the snapshot; a detail request is optional. await row.click() await expect(page.getByRole('heading', { name: target.name, exact: true })).toBeVisible() releaseDetail() await expect(page.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })).toBeEnabled() await expect(row.getByRole('img', { name: '未读', exact: true })).toHaveCount(0) releaseRead() await expect(viewerRow.getByRole('img', { name: '未读', exact: true })).toHaveCount(0) } finally { releaseDetail(); releaseRead() await page.unroute(detailPattern); await page.unroute(readPattern) } await page.locator(`.desktop-sidebar [data-sidebar-id="${other.id}"]`).click() } await expect(page.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })).toBeEnabled() await page.screenshot({ path: testInfo.outputPath('unread-desktop.png') }) const sent = await page.request.post(`/api/app/conversations/${group.id}/messages`, { headers, data: { requestId: crypto.randomUUID(), content: '再次确认结果' } }) expect(sent.ok(), await sent.text()).toBe(true) await page.setViewportSize({ width: 375, height: 812 }) await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' }) await page.goto('/conversations') await expect(page.getByRole('option').filter({ hasText: group.name }).getByRole('img', { name: '未读', exact: true })).toBeVisible() await page.screenshot({ path: testInfo.outputPath('unread-mobile.png') }) } finally { await viewer.close() // This suite shares its fixture account; remove only the records created above. const archived = await page.request.patch(`/api/app/conversations/${group.id}`, { headers, data: { archived: true } }) expect(archived.ok(), await archived.text()).toBe(true) const removed = await page.request.delete(`/api/app/conversations/${group.id}`, { headers }) expect(removed.ok(), await removed.text()).toBe(true) for (const agent of [first, second]) { const archived = await page.request.patch(`/api/app/agents/${agent.id}`, { headers, data: { archived: true } }) expect(archived.ok(), await archived.text()).toBe(true) const removed = await page.request.delete(`/api/app/agents/${agent.id}`, { headers }) expect(removed.ok(), await removed.text()).toBe(true) } } }) test('an open Web chat list receives cross-client sessions and real title events without reload', async ({ page, context, }) => { await login(page) const pageAChannelOpened = page.waitForResponse(response => response.request().method() === 'POST' && response.url().endsWith('/api/realtime/channels')) await page.goto('/chat') await pageAChannelOpened await expect(page.getByRole('button', { name: '新建聊天', exact: true })).toBeVisible() const marker = `${Date.now()}-${Math.random().toString(16).slice(2)}` const initialTitle = `跨端新会话 ${marker}` const generatedTitle = `自动标题 ${marker}` const sentinel = `page-a-${marker}` await page.evaluate(value => { ;(window as Window & { __crossClientProjectionSentinel?: string }) .__crossClientProjectionSentinel = value }, sentinel) const pageB = await context.newPage() const pageBChannelOpened = pageB.waitForResponse(response => response.request().method() === 'POST' && response.url().endsWith('/api/realtime/channels')) await pageB.goto('/chat') await pageBChannelOpened await pageB.getByRole('button', { name: '新建聊天', exact: true }).click() const pageBComposer = pageB.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行', }) await pageBComposer.fill(`[cross-client-title:${initialTitle}] 创建跨端会话`) const pageBSend = pageB.getByRole('button', { name: '发送消息', exact: true }) await expect(pageBSend).toBeEnabled() await pageBSend.click() await expect(pageB).toHaveURL(/\/chat\/(?!draft-)[^/?]+(?:\?.*)?$/) const sessionId = decodeURIComponent(new URL(pageB.url()).pathname.split('/').at(-1) || '') expect(sessionId).not.toMatch(/^draft-/) await expect(pageB.locator('.message--assistant')).toContainText('会话独立保存') const cwdCalls = await (await page.request.get('http://127.0.0.1:19120/__calls')).json() const created = cwdCalls.calls.filter((call: { method: string }) => call.method === 'session.create').at(-1) expect(created.params.cwd).toBe('/tmp/hermes-fixture/default') const aligned = cwdCalls.calls.filter((call: { method: string }) => call.method === 'session.cwd.set').at(-1) expect(aligned.params.cwd).toBe('/tmp/hermes-fixture/default') const sessionRow = page.locator(`.desktop-sidebar .sidebar-item[data-sidebar-id="${sessionId}"]`) await expect(sessionRow).toContainText(initialTitle) expect(await page.evaluate(() => (window as Window & { __crossClientProjectionSentinel?: string }) .__crossClientProjectionSentinel)).toBe(sentinel) await pageB.close() const titled = await page.request.post( `http://127.0.0.1:19120/__test/sessions/title?id=${encodeURIComponent(sessionId)}` + `&title=${encodeURIComponent(generatedTitle)}`, ) expect(titled.ok(), await titled.text()).toBe(true) await expect(sessionRow).toContainText(generatedTitle) await expect(sessionRow).not.toContainText(initialTitle) expect(await page.evaluate(() => (window as Window & { __crossClientProjectionSentinel?: string }) .__crossClientProjectionSentinel)).toBe(sentinel) }) test('an idle Web viewer follows an iOS-origin run and restores thinking after reload', async ({ page }, testInfo) => { await login(page) const capabilities = await (await page.request.get('/api/realtime/capabilities')).json() const headers = { 'X-CSRF-Token': capabilities.csrfToken, Origin: new URL(page.url()).origin } const opened = await page.request.post('/api/realtime/channels', { headers, data: { channel: 'chat', chatProtocol: 'ordinary-chat-transcript-v2' } }) expect(opened.ok(), await opened.text()).toBe(true) const channel = (await opened.json()).id let sequence = 0 async function command(method: string, params: Record) { const response = await page.request.post(`/api/realtime/channels/${channel}/commands`, { headers: { ...headers, 'Idempotency-Key': `ios-live-${Date.now()}-${++sequence}` }, data: { jsonrpc: '2.0', method, params }, }) expect(response.ok(), await response.text()).toBe(true) const receipt = await response.json() expect(receipt.state).toBe('confirmed') return receipt.response.result } const session = await command('session.create', { profile: 'default', source: 'ios' }) const subscribed = page.waitForResponse(response => response.url().endsWith('/commands') && response.request().postDataJSON()?.method === 'session.resume') await page.goto(`/chat/${session.stored_session_id}?profile=default`) await subscribed await page.getByRole('button', { name: '设置', exact: true }).click() await page.getByRole('switch', { name: /显示思考/ }).click() await page.getByRole('button', { name: '设置', exact: true }).click() await command('prompt.submit', { session_id: session.session_id, text: '[cross-client-live] 检查文件' }) const typing = page.getByTestId('chat-run-thinking-dots') await expect(typing).toBeVisible() await expect(typing.locator('.agent-avatar')).toBeVisible() await expect(typing.locator('.thinking-indicator__dot')).toHaveCount(3) await expect(typing).toContainText('秒') await page.getByText('思考与工具', { exact: true }).click() await expect(page.getByText('read_file', { exact: true })).toBeVisible() await expect(typing).toBeVisible() await page.screenshot({ path: testInfo.outputPath('ios-run-web-thinking-tools.png') }) // This Web page has never submitted a prompt or written an in-flight marker. await page.evaluate(() => sessionStorage.clear()) await page.reload() await expect(typing).toBeVisible() await page.request.post('http://127.0.0.1:19120/__release') await expect(page.locator('.message--assistant')).toContainText('会话独立保存') await expect(typing).toHaveCount(0) await page.screenshot({ path: testInfo.outputPath('ios-run-web-completed.png') }) }) test('created roles and editable teams share a durable chat list without plugin calls', async ({ page, context, }, testInfo) => { const pluginCalls: string[] = [] page.on('request', (r) => { if (r.url().includes('/plugins/yaoyao')) pluginCalls.push(r.url()) }) await page.setViewportSize({ width: 1638, height: 874 }) await login(page) const rail = page.locator('.desktop-sidebar') await expect(rail.locator('.sidebar-feature-nav')).toHaveCount(0) await expect(rail.locator('.sidebar-primary-action')).toHaveCount(0) await expect(rail).toHaveCSS('width', '360px') await expect(rail.locator('.sidebar-context__heading')).toHaveCount(0) await expect(rail.locator('.bot-logo-trigger .brand-mark')).toBeVisible() await expect(rail.locator('.sidebar-footer')).toBeVisible() await expect(rail.locator('.sidebar-account-switcher__main')).toContainText('fixture') await expect(rail.locator('.sidebar-account-switcher__main .account-initial-avatar')).toHaveText('F') await rail.locator('.sidebar-account-switcher__main').click() await expect(page.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['我的设置', '关于', '检测更新', '帮助', '进入聊天模式']) await page.getByRole('menuitem', { name: '关于', exact: true }).click() const about = page.getByRole('dialog', { name: '关于夭夭 AI', exact: true }) await expect(about).toBeVisible() await expect(about.locator('.about-version')).toHaveText(/^版本 \d+\.\d+\.\d+$/) await expect(page.getByRole('dialog', { name: '我的设置', exact: true })).toHaveCount(0) await page.screenshot({ path: testInfo.outputPath('independent-about.png') }) await page.keyboard.press('Escape') await expect(about).toHaveCount(0) await rail.getByRole('button', { name: '工具', exact: true }).click() await page.getByRole('menuitem', { name: '已连接应用', exact: true }).click() const apps = page.getByRole('dialog', { name: '已连接应用', exact: true }) await expect(apps).toBeVisible() await expect(apps.getByRole('tab', { name: 'MCP 服务', exact: true })).toBeVisible() await expect(page.locator('.settings-sidebar')).toHaveCount(0) await page.screenshot({ path: testInfo.outputPath('independent-apps.png') }) await apps.getByRole('button', { name: '关闭已连接应用', exact: true }).click() await rail.getByRole('button', { name: '工具', exact: true }).click() await page.getByRole('menuitem', { name: '自动化', exact: true }).click() await expect(page).toHaveURL(/\/conversations\/automations(?:\?.*)?$/) await expect(page.getByRole('main', { name: '自动化工作区' })).toBeVisible() await expect(page.locator('.schedule-day')).toHaveCount(7) await page.getByRole('tab', { name: '运行日志', exact: true }).click() await page.screenshot({ path: testInfo.outputPath('independent-automations.png') }) await page.getByRole('button', { name: '返回聊天', exact: true }).click() await expect(page).toHaveURL(/\/conversations$/) await rail.locator('.sidebar-account-switcher__main').click() await page.getByRole('menuitem', { name: '我的设置', exact: true }).click() const settings = page.getByRole('dialog', { name: '我的设置', exact: true }) await settings.getByRole('button', {name:'账号资料',exact:true}).click() await expect(settings.locator('.account-avatar-card')).toContainText('fixture') await expect(settings.locator('.account-avatar-card .account-initial-avatar')).toHaveText('F') await settings.locator('.account-avatar-card input[type=file]').setInputFiles({name:'account.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64')}) await expect(settings.locator('.account-avatar-card .account-initial-avatar img')).toBeVisible() expect((await (await page.request.get('/api/app/bootstrap')).json()).user.avatar).toMatch(/^data:image\/png;base64,/) await settings.getByRole('button', {name:'使用首字母',exact:true}).click() await expect(settings.locator('.account-avatar-card .account-initial-avatar')).toHaveText('F') await settings.getByRole('button', { name: '身份与头像', exact: true }).click() await settings.getByRole('button', { name: '造型:星星', exact: true }).click() await settings.getByRole('button', { name: '使用颜色 #1488ff', exact: true }).click() await settings.locator('.mascot-grid--expression button').filter({ hasText: '开心' }).click() await settings.getByRole('button', { name: '保存更改', exact: true }).click() await expect(settings.getByRole('button', { name: '保存更改', exact: true })).toBeDisabled() await settings.getByRole('button', { name: '关闭我的设置', exact: true }).click() await rail.locator('.sidebar-account-switcher__main').click() await page.getByRole('menuitem', {name:'我的设置',exact:true}).click() await settings.getByRole('button', { name: '身份与头像', exact: true }).click() await expect(settings.getByRole('button', { name: '造型:星星', exact: true })).toHaveAttribute('aria-pressed', 'true') await expect(settings.getByRole('button', { name: '使用颜色 #1488ff', exact: true })).toHaveAttribute('aria-pressed', 'true') await expect(settings.locator('.mascot-grid--expression button').filter({ hasText: '开心' })).toHaveAttribute('aria-pressed', 'true') await settings.getByRole('button', { name: '关闭我的设置', exact: true }).click() await expect(rail.getByRole('checkbox', { name: '显示已归档' })).toHaveCount(0) const plus = rail.getByRole('button', { name: '新建', exact: true }) await expect(rail.locator('.sidebar-collapse')).toHaveCount(0) await plus.click() await expect(page.getByRole('menu', { name: '新建聊天' }).getByRole('menuitem')).toHaveText(['新建 Bot', '添加远程机器人', '新建群聊']) await page.keyboard.press('Escape') await rail.getByRole('button', { name: '搜索', exact: true }).click() await expect(page.getByRole('dialog', { name: '搜索聊天' })).toBeVisible() await page.keyboard.press('Escape') await page.goto('/chat') await expect(rail).toHaveCSS('width', '264px') await expect(rail.getByRole('button', { name: '聊天', exact: true })).toHaveCount(0) await rail.getByRole('button', { name: '设置与模式', exact: true }).click() const settingsMenu = page.getByRole('menu', { name: '账号菜单', exact: true }) await expect(settingsMenu.getByRole('menuitem')).toHaveText(['我的设置', '关于', '检测更新', '帮助', '进入 Bot 模式']) await page.screenshot({ path: testInfo.outputPath('chat-settings-mode-menu.png') }) await settingsMenu.getByRole('menuitem', { name: '我的设置', exact: true }).click() await expect(page.getByRole('dialog', { name: '我的设置', exact: true })).toBeVisible() await page.getByRole('button', { name: '关闭我的设置', exact: true }).click() await expect(rail.getByRole('button', { name: '设置与模式', exact: true })).toBeFocused() await rail.getByRole('button', { name: '设置与模式', exact: true }).click() await settingsMenu.getByRole('menuitem', { name: '进入 Bot 模式', exact: true }).click() await expect(page).toHaveURL(/\/conversations$/) await expect(rail).toHaveCSS('width', '360px') await page.addInitScript(() => { Object.defineProperty(crypto, 'randomUUID', { value: undefined, configurable: true }) }) await page.reload() await createAgent(page, '产品经理') await page.getByRole('button', {name:'聊天设置',exact:true}).click() const avatarEditor = page.getByRole('dialog') await expect(avatarEditor.locator('.color-grid button')).toHaveCount(11) await expect(avatarEditor.locator('.mascot-grid--expression button')).toHaveCount(10) await avatarEditor.getByRole('button', {name:'造型:星星',exact:true}).click() await avatarEditor.locator('.mascot-grid--expression button').filter({hasText:'自豪'}).click() await avatarEditor.getByRole('button', {name:'使用颜色 #000000',exact:true}).click() await avatarEditor.getByRole('button', {name:'保存',exact:true}).click() const identities = await (await page.request.get('/api/app/agents')).json() const edited = identities.agents.find((a: {name:string}) => a.name === '产品经理') expect(JSON.parse(edited.avatar.slice('yaoyao-avatar:v2:'.length))).toMatchObject({version:2,bodyId:'star',expression:'proud',color:'#000000'}) await page.reload() await page.getByRole('button', {name:'聊天设置',exact:true}).click() await expect(avatarEditor.getByRole('button', {name:'造型:星星',exact:true})).toHaveAttribute('aria-pressed','true') await avatarEditor.locator('input[type=file]').setInputFiles({name:'avatar.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=','base64')}) await expect(avatarEditor.getByText('图片裁剪',{exact:true})).toBeVisible() let photoBytes='' for(const [label,crop] of [['圆形','circle'],['方形','square'],['圆角方形','rounded']]){ await avatarEditor.getByRole('button',{name:label,exact:true}).click() await avatarEditor.getByRole('button',{name:'保存',exact:true}).click() const payload=await (await page.request.get('/api/app/agents')).json() const avatar=JSON.parse(payload.agents.find((a:{name:string})=>a.name==='产品经理').avatar.slice('yaoyao-avatar:v2:'.length)) expect(avatar).toMatchObject({avatarMode:'image',imageCrop:crop}) if(photoBytes)expect(avatar.imageDataURL).toBe(photoBytes) else photoBytes=avatar.imageDataURL await page.getByRole('button',{name:'聊天设置',exact:true}).click() } await avatarEditor.getByRole('button',{name:'动态吉祥物',exact:true}).click() await avatarEditor.locator('.mascot-grid--shape button').filter({hasText:'圆形'}).first().click() await avatarEditor.getByRole('button', {name:'使用颜色 #ff6b00',exact:true}).click() await avatarEditor.locator('.mascot-grid--expression button').filter({hasText:'默认'}).click() await avatarEditor.getByRole('button', {name:'保存',exact:true}).click() await expect(avatarEditor).toBeHidden() const composerInput = page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行') const sendButton = page.getByRole('button', { name: '发送消息', exact: true }) await expect(composerInput).toBeEnabled() await expect(rail.getByText('聊天', { exact: true })).toHaveCount(0) await expect(rail.getByText('聊天列表', { exact: true })).toHaveCount(0) await expect(rail.locator('.sidebar-item__row strong').first()).toHaveCSS('font-size', '15px') await expect(rail.locator('.sidebar-item__row--secondary').first()).toHaveCSS('font-size', '13px') await expect(rail.locator('.sidebar-item__row small').first()).toHaveCSS('font-size', '10px') await composerInput.fill('请说明角色职责') await expect(sendButton).toBeEnabled() await sendButton.click() await expect(page.locator('.message--assistant')).toContainText('我是产品经理') for (const colorScheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme }) for (const selector of ['.message__avatar.agent-avatar', '.desktop-sidebar .sidebar-item__icon--avatar', '.desktop-sidebar .agent-avatar']) { await expect(page.locator(selector).first()).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)') await expect(page.locator(selector).first()).toHaveCSS('background-image', 'none') } } await page.emulateMedia({ colorScheme: 'light' }) await expect(page.locator('.message--assistant a').first()).toHaveAttribute( 'href', /\/api\/app\/files\/.+\/download/, ) await page.locator('.message--assistant a').first().click() const textPreview = page.getByRole('dialog', { name: '预览 workspace-report.txt', exact: true }) await expect(textPreview).toBeVisible() await expect(textPreview).toContainText('Fixture report') await textPreview.getByRole('button', { name: '关闭预览' }).click() const managerRow = rail.getByRole('option').filter({ hasText: '产品经理' }) await managerRow.click({ button: 'right' }) await page.getByRole('menuitem', {name:'置顶聊天',exact:true}).click() await managerRow.click({ button: 'right' }) await expect(page.getByRole('menuitem', {name:'取消置顶',exact:true})).toBeVisible() await page.getByRole('menuitem', {name:'取消置顶',exact:true}).press('Escape') const directURL = page.url() await createAgent(page, '开发工程师') await expect(page.locator('.message')).toHaveCount(0) await openCreate(page, '新建群聊') const dialog = page.getByRole('dialog') await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('产品开发团队') await dialog.getByRole('checkbox', { name: '产品经理', exact: true }).check() await dialog.getByRole('checkbox', { name: '开发工程师', exact: true }).check() await dialog.getByText('高级协作设置', { exact: true }).click() await dialog.getByRole('combobox', { name: '协作方式', exact: true }).selectOption('host') await dialog .getByRole('combobox', { name: '负责人', exact: true }) .selectOption({ label: '产品经理' }) await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(page.getByRole('heading', { name: '产品开发团队', exact: true })).toBeVisible() await expect(page.locator('.desktop-sidebar .sidebar-item')).toHaveCount(3) // Every cluster portrait must be the same portrait shown in that member's direct chat. const groupRow = page.locator('.desktop-sidebar .sidebar-item').filter({ hasText: '产品开发团队' }) await expect(groupRow.locator('.team-avatar__member')).toHaveCount(2) for (const name of ['产品经理', '开发工程师']) { const portrait = `.agent-avatar[aria-label="${name} 的头像"]` const direct = page.locator('.desktop-sidebar .sidebar-item').filter({ hasText: name }).filter({ hasNot: page.locator('.team-avatar') }).locator(portrait) const member = groupRow.locator(portrait) await expect(member.locator('[data-part=outline] > :first-child')).toHaveAttribute('fill', await direct.locator('[data-part=outline] > :first-child').getAttribute('fill') || '') expect(await member.locator('[data-part=outline] > :first-child').evaluate(el => el.tagName)) .toBe(await direct.locator('[data-part=outline] > :first-child').evaluate(el => el.tagName)) } await expect(page.locator('.desktop-sidebar')).not.toContainText('话题') await expect(page.locator('.desktop-sidebar .sidebar-account-switcher__main')).not.toContainText( '通用助手', ) await page.getByRole('button', { name: '聊天设置', exact: true }).click() await expect(dialog.getByRole('checkbox', { name: '产品经理', exact: true })).toBeDisabled() await expect(dialog.getByRole('checkbox', { name: '开发工程师', exact: true })).toBeEnabled() await dialog.getByRole('button', { name: '取消', exact: true }).click() await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('请@开发工程师给出实现结果') await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.locator('.message--assistant')).toHaveCount(3) await expect(page.locator('.message--assistant').nth(1)).toContainText('我是开发工程师') await expect(page.locator('.run-status')).toHaveCount(0) const second = await context.newPage() await second.goto(page.url()) await expect(second.locator('.message--assistant')).toHaveCount(3) await page.screenshot({ path: testInfo.outputPath('mixed-chats.png'), fullPage: true }) const groupURL=page.url() await page.getByRole('button', { name: '聊天设置', exact: true }).click() await dialog.getByRole('checkbox', { name: '开发工程师', exact: true }).uncheck() await expect(dialog.getByRole('checkbox', { name: '产品经理', exact: true })).toBeDisabled() await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(groupRow.locator('.team-avatar__member')).toHaveCount(1) await expect(page.locator('.message--assistant')).toHaveCount(3) await expect(second.locator('.desktop-sidebar .sidebar-item').filter({ hasText: '产品开发团队' }).locator('.team-avatar__member')).toHaveCount(1) await page.reload() await page.getByRole('button', { name: '聊天设置', exact: true }).click() await expect(dialog.getByRole('checkbox', { name: '开发工程师', exact: true })).not.toBeChecked() await dialog.getByRole('button', { name: '取消', exact: true }).click() await createAgent(page, '新成员') await page.goto(groupURL) await page.getByRole('button', { name: '聊天设置', exact: true }).click() await dialog.getByRole('checkbox', { name: '新成员', exact: true }).check() await dialog.getByRole('checkbox', { name: '产品经理', exact: true }).scrollIntoViewIfNeeded() await page.screenshot({ path: testInfo.outputPath('member-settings.png'), fullPage: true }) await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(groupRow.locator('.team-avatar__member')).toHaveCount(2) await expect(groupRow.locator('[aria-label="开发工程师 的头像"]')).toHaveCount(0) await expect(groupRow.locator('[aria-label="新成员 的头像"]')).toHaveCount(1) await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('请@新成员继续') await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.locator('.message--assistant')).toHaveCount(6) await expect(page.locator('.message--assistant').nth(4)).toContainText('我是新成员') await page.goto('/files') await page.getByRole('button',{name:'查看来源',exact:true}).first().click() await expect(page).toHaveURL(groupURL) await groupRow.click({ button: 'right' }) page.once('dialog', dialog => dialog.accept()) await page.getByRole('menuitem', { name: '归档聊天', exact: true }).click() await expect(page.locator('.desktop-sidebar .sidebar-item')).toHaveCount(3) await page.locator('.desktop-sidebar .sidebar-search-trigger').click() const search = page.getByRole('dialog', { name: '搜索聊天', exact: true }) await expect(search).toBeVisible() await search.getByRole('searchbox', { name: '搜索聊天', exact: true }).fill('产品开发') await expect(search.getByRole('listitem')).toHaveCount(0) await search.getByRole('tab', { name: '已归档', exact: true }).click() await expect(search.getByRole('searchbox')).toHaveValue('产品开发') await expect(search.getByRole('listitem')).toHaveCount(1) await page.screenshot({ path: testInfo.outputPath('archived-chat-search.png'), fullPage: true }) await search.getByRole('listitem').getByRole('button').filter({ hasText: '产品开发团队' }).click() await expect(search).not.toBeVisible() await expect(page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行')).toBeDisabled() await page.goto(directURL) await expect(page.locator('.message--assistant')).toHaveCount(1) await expect(page.locator('.message--assistant')).toContainText('我是产品经理') await page.goto('/chat') await expect(page).toHaveURL(/\/chat/) expect(pluginCalls).toEqual([]) await second.close() await page.goto('/conversations') await openCreate(page, '新建群聊') await dialog.locator('summary').filter({hasText:'从团队模板选择'}).click() await expect(dialog.getByRole('button', { name: '信息收集团队', exact: true })).toBeDisabled() await dialog.getByRole('button', { name: '取消', exact: true }).click() await createAgent(page, '模板成员四') await createAgent(page, '模板成员五') await openCreate(page, '新建群聊') await dialog.locator('summary').filter({hasText:'从团队模板选择'}).click() for (const name of ['信息收集团队', '产品设计团队', '软件开发团队', '文案书写团队', '项目管理团队', '数据分析团队', '会议协作团队', '运维保障团队']) { await expect(dialog.getByRole('button', { name, exact: true })).toBeEnabled() } await page.screenshot({ path: testInfo.outputPath('restored-team-presets.png'), fullPage: true }) await dialog.getByRole('button', { name: '产品设计团队', exact: true }).click() await expect(dialog.getByRole('textbox', { name: '名称', exact: true })).toHaveValue('产品设计团队') await dialog.getByText('高级协作设置', { exact: true }).click() await dialog.getByRole('combobox', { name: '协作方式', exact: true }).selectOption('host') await dialog.getByRole('combobox', { name: '产品负责人对应的机器人', exact: true }).selectOption({ label: '产品经理' }) await dialog.getByRole('combobox', { name: '交互设计对应的机器人', exact: true }).selectOption({ label: '开发工程师' }) const [submitted] = await Promise.all([ page.waitForRequest(r => r.method() === 'POST' && r.url().endsWith('/api/app/conversations')), dialog.getByRole('button', { name: '保存', exact: true }).click(), ]) const payload = submitted.postDataJSON() expect(new Set(payload.memberIds).size).toBe(5) expect(Object.keys(payload.memberRoles)).toHaveLength(5) expect(payload.memberRoles[payload.administratorId].name).toBe('产品负责人') await expect(page.getByRole('heading', { name: '产品设计团队', exact: true })).toBeVisible() await page.getByRole('button', { name: '聊天设置', exact: true }).click() await expect(dialog.getByText('产品经理 · 产品负责人', { exact: false })).toBeVisible() await expect(dialog.getByText('开发工程师 · 交互设计', { exact: false })).toBeVisible() await dialog.getByRole('button', { name: '取消', exact: true }).click() await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('请汇总设计方案') await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.locator('.message--assistant')).toContainText('我是产品经理') const conversationPath = new URL(page.url()).pathname.replace('/conversations/', '/api/app/conversations/') await expect.poll(async () => { const c = (await (await page.request.get(conversationPath)).json()).conversation return { active: Boolean(c.activeRunId), queued: c.queuedMessageCount } }).toEqual({ active: false, queued: 0 }) const composer = page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行') await composer.fill('[hold-workspace] 正在执行的任务') await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.getByRole('button', { name: '停止生成', exact: true })).toBeVisible() await expect.poll(async () => (await (await page.request.get(conversationPath)).json()).conversation.queuedMessageCount).toBe(0) await composer.fill('后续排队任务') await expect(page.getByRole('button', { name: '发送消息', exact: true })).toBeEnabled() await page.getByRole('button', { name: '发送消息', exact: true }).click() await expect(page.locator('.message--user').last()).toContainText('后续排队任务') const detail = await (await page.request.get(new URL(page.url()).pathname.replace('/conversations/', '/api/app/conversations/'))).json() expect(detail.conversation.queuedMessageCount).toBe(1) await page.request.post('http://127.0.0.1:19120/__release') await expect.poll(async () => (await (await page.request.get(`/api/app/conversations/${detail.conversation.id}`)).json()).conversation.activeRunId).toBeUndefined() await page.setViewportSize({ width: 390, height: 844 }) await page.getByRole('button', { name: '返回 Bot 列表', exact: true }).click() await expect(rail).toBeVisible() await expect(rail).toHaveCSS('width', '390px') await expect(page.locator('.mobile-header')).toBeHidden() await expect(rail.locator('.sidebar-feature-nav')).toHaveCount(0) await page.screenshot({ path: testInfo.outputPath('mobile-bot-list.png') }) await rail.getByRole('button', { name: '新建', exact: true }).click() await expect(page.getByRole('menuitem', { name: '新建 Bot', exact: true })).toBeVisible() await page.keyboard.press('Escape') await rail.getByRole('button', { name: '搜索', exact: true }).click() await expect(page.getByRole('dialog', { name: '搜索聊天' })).toBeVisible() await expect(page.getByRole('tab', { name: '未归档', exact: true })).toBeVisible() await page.getByRole('button', { name: '关闭搜索', exact: true }).click() await rail.locator('.sidebar-account-switcher__main').click() await page.getByRole('menuitem', { name: '进入聊天模式', exact: true }).click() await expect(page).toHaveURL(/\/chat$/) await page.goto('/') await expect(page).toHaveURL(/\/chat$/) await page.setViewportSize({ width: 1280, height: 800 }) await page.getByRole('button', { name: '设置与模式', exact: true }).click() await page.getByRole('menuitem', { name: '进入 Bot 模式', exact: true }).click() await page.goto('/') await expect(page).toHaveURL(/\/conversations$/) await page.reload() await expect(rail.locator('.bot-list-header')).toBeVisible() expect(pluginCalls).toEqual([]) }) test('subaccount allocation and Bot-only navigation work through the browser', async ({ page, browser }, testInfo) => { await login(page) await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click() await page.getByRole('menuitem', { name: '我的设置', exact: true }).click() const settings = page.getByRole('dialog', { name: '我的设置', exact: true }) await settings.getByRole('button', { name: '用户与权限', exact: true }).click() const username = `child-${Date.now()}` await settings.locator('input[name=managed-username]').fill(username) await settings.locator('input[name=managed-temporary-password]').fill('temporary-pass') await settings.getByRole('listbox', { name: '新子账号的基础机器人' }).selectOption('default') await settings.getByRole('button', { name: '创建用户', exact: true }).click() await expect(settings.getByRole('listbox', { name: `分配给 ${username} 的基础机器人`, exact: true })).toHaveValues(['default']) await page.screenshot({ path: testInfo.outputPath('admin-agent-allocation.png'), fullPage: true }) const childContext = await browser.newContext({ viewport: { width: 1280, height: 800 } }) const child = await childContext.newPage() await child.goto(new URL('/chat', page.url()).href) await child.getByRole('textbox', { name: '账号', exact: true }).fill(username) await child.getByRole('textbox', { name: '密码', exact: true }).fill('temporary-pass') await child.getByRole('button', { name: '登录', exact: true }).click() await child.getByLabel('当前密码', { exact: true }).fill('temporary-pass') await child.getByLabel('新密码', { exact: true }).fill('permanent-pass') await child.getByLabel('确认新密码', { exact: true }).fill('permanent-pass') await child.getByRole('button', { name: '保存并进入夭夭', exact: true }).click() await expect(child).toHaveURL(/\/conversations$/) await expect(child.getByRole('heading', { name: '还没有聊天' })).toBeVisible() await child.locator('.desktop-sidebar .sidebar-account-switcher__main').click() await expect(child.getByRole('menu', { name: '账号菜单' }).getByRole('menuitem')).toHaveText(['我的设置', '关于', '帮助']) await child.keyboard.press('Escape') await openCreate(child, '新建 Bot') const dialog = child.getByRole('dialog') await expect(dialog.getByLabel('基础机器人').locator('option')).toHaveCount(1) await expect(dialog.getByLabel('基础机器人').locator('option')).toContainText('通用助手') await dialog.getByLabel('基础机器人').scrollIntoViewIfNeeded() await child.screenshot({ path: testInfo.outputPath('subaccount-assigned-source.png'), fullPage: true }) await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('子账号助手') await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(child.getByRole('heading', { name: '子账号助手', exact: true })).toBeVisible() for (const path of ['/history', '/kanban', '/files', '/chat']) { await child.goto(new URL(path, page.url()).href) await expect(child).toHaveURL(/\/conversations$/) } await childContext.close() }) for (const mode of ['普通聊天', 'Bot 单聊', '群聊', '普通长回复'] as const) { test(`${mode} 在完成前格式化流式 Markdown 并保留最终内容`, async ({ page }, testInfo) => { await login(page) if (mode.startsWith('普通')) { await page.goto('/chat') await page.getByRole('button', { name: '新建聊天', exact: true }).click() } else { await createAgent(page, `${mode}流式验证助手`) if (mode === '群聊') { await createAgent(page, '群聊流式协作成员') await openCreate(page, '新建群聊') const dialog = page.getByRole('dialog') await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('流式验证群') await dialog.getByRole('checkbox', { name: `${mode}流式验证助手`, exact: true }).check() await dialog.getByRole('checkbox', { name: '群聊流式协作成员', exact: true }).check() await dialog.getByText('高级协作设置', { exact: true }).click() await dialog.getByRole('combobox', { name: '协作方式', exact: true }).selectOption('host') await dialog.getByRole('combobox', { name: '负责人', exact: true }).selectOption({ label: `${mode}流式验证助手` }) await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(page.getByRole('heading', { name: '流式验证群', exact: true })).toBeVisible() } } await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill(`[streaming-markdown] ${mode === '普通长回复' ? '[long]' : ''} 演示排版`) await page.getByRole('button', { name: '发送消息', exact: true }).click() const message = page.locator('.message--assistant').last() await expect(message.locator('.markdown--streaming h1')).toHaveText('流式标题') await expect(message.locator('strong').filter({ hasText: '即时格式化' })).toBeVisible() await expect(message.locator('li')).toHaveText(['第一项', '第二项']) await expect(message.locator('pre code').first()).toContainText('const answer = 42') await expect(message).not.toContainText('最终完整标记') await page.screenshot({ path: testInfo.outputPath('streaming-markdown.png'), fullPage: true }) if (mode === '普通长回复') { await expect(message.getByText('流式末尾标记', { exact: true })).toBeInViewport() await page.locator('.timeline').evaluate(el => { el.scrollTop = 0; el.dispatchEvent(new Event('scroll')) }) await expect(message.getByRole('heading', { name: '流式标题', exact: true })).toBeInViewport() } const released = await page.request.post('http://127.0.0.1:19120/__release') expect(released.ok()).toBe(true) await expect(message).toContainText('最终完整标记') await expect(message.locator('table')).toContainText('项目') await expect(message.locator('.markdown--streaming')).toHaveCount(0) if (mode === '普通长回复') { await expect(message.getByRole('heading', { name: '流式标题', exact: true })).toBeInViewport() await expect(message.getByText('最终完整标记', { exact: true })).not.toBeInViewport() } }) } test('only chat messages introduce files across transcript and library', async ({ page }, testInfo) => { await login(page) await createAgent(page, '文件展示验收') await page.getByPlaceholder('输入消息,Enter 发送,Shift + Enter 换行').fill('[message-files] 请发送报告') await page.getByRole('button', { name: '发送消息', exact: true }).click() const report = page.locator('.message--assistant .file-link-card').first() await expect(report).toBeVisible() const process = page.locator('.turn-trace') await expect(process).toHaveCount(0) await page.locator('.composer-tool[title="显示思考"]').click() await expect(process).toHaveCount(1) await process.locator('summary').first().click() await expect(process).toContainText('/tmp/process.pdf') await expect(process.locator('img, .file-link-card')).toHaveCount(0) const conversationId = new URL(page.url()).pathname.split('/').at(-1)! const files = await (await page.request.get(`/api/app/files?session_id=${encodeURIComponent(conversationId)}`)).json() expect(files.items.map((file: { name: string }) => file.name)).toEqual(['workspace-report.txt']) await report.click() const preview = page.getByRole('dialog', { name: '预览 workspace-report.txt', exact: true }) await expect(preview).toContainText('Fixture report') await preview.getByRole('button', { name: '关闭预览' }).click() await page.reload() await expect(page.locator('.message--assistant .file-link-card')).toHaveCount(1) await expect(page.locator('.turn-trace')).toHaveCount(0) await page.locator('.composer-tool[title="显示思考"]').click() await page.locator('.turn-trace summary').first().click() await page.setViewportSize({ width: 1280, height: 1100 }) await page.screenshot({ path: testInfo.outputPath('message-files-web.png') }) }) test('Bot transcript switches from cache and preserves the viewport during history and live updates', async ({ page }, testInfo) => { await login(page) const bootstrap = await (await page.request.get('/api/app/bootstrap')).json() const headers = { 'X-CSRF-Token': bootstrap.csrfToken } const seed = await (await page.request.post('/__test/workspace-transcript', { headers })).json() try { await page.goto(`/conversations/${seed.conversationId}`) await expect(page.locator('.message')).toHaveCount(50) const scroller = page.locator('.timeline') for (let index = 0; index < 4; index++) { await scroller.evaluate(el => { el.scrollTop = 0 }) const before = await page.locator('.message').first().getAttribute('data-message-id') await page.getByRole('button', { name: '加载更早消息', exact: true }).click() await expect(page.locator('.message')).toHaveCount(100 + index * 50) expect(await page.locator(`[data-message-id="${before}"]`).evaluate(el => { const scroller = el.closest('.timeline')!; return el.getBoundingClientRect().top - scroller.getBoundingClientRect().top })).toBeGreaterThanOrEqual(-10) } // Returning keeps loaded history in memory but mounts only the 120-message tail. await page.locator('.desktop-sidebar .bot-logo-trigger').click() await expect(page.locator('.desktop-sidebar .sidebar-item').filter({ hasText: '长会话性能验收' })).toBeVisible() const requests: string[] = [] page.on('request', request => { if (request.method() === 'GET') requests.push(new URL(request.url()).pathname) }) await page.locator(`.desktop-sidebar [data-sidebar-id="${seed.conversationId}"]`).click() await expect(page.locator('.message')).toHaveCount(120) expect(requests).not.toContain(`/api/app/conversations/${seed.conversationId}`) await scroller.hover(); await page.mouse.wheel(0, -600) await expect(page.getByRole('button', { name: '回到底部', exact: true })).toBeVisible() const top = await scroller.evaluate(el => el.scrollTop) await page.request.post(`/__test/workspace-transcript?id=${seed.conversationId}`, { headers }) await expect(page.locator('.message').last()).toContainText('实时追加的内容') expect(Math.abs(await scroller.evaluate(el => el.scrollTop) - top)).toBeLessThan(4) expect(requests).not.toContain('/api/app/agents') expect(requests).not.toContain('/api/app/events') await page.screenshot({ path: testInfo.outputPath('bot-cached-transcript.png') }) await page.setViewportSize({ width: 375, height: 812 }) await page.emulateMedia({ colorScheme: 'dark', reducedMotion: 'reduce' }) await expect(page.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' })).toBeVisible() await page.screenshot({ path: testInfo.outputPath('bot-cached-transcript-mobile-dark.png') }) } finally { await page.request.patch(`/api/app/agents/${seed.agentId}`, { headers, data: { archived: true } }) await page.request.delete(`/api/app/agents/${seed.agentId}`, { headers }) } }) test('Bot startup loads only the selected transcript and fetches large tool output after expansion', async ({ page }) => { await login(page) const bootstrap = await (await page.request.get('/api/app/bootstrap')).json() const headers = { 'X-CSRF-Token': bootstrap.csrfToken } const seeded = await page.request.post('/__test/workspace-transcript?tools=large', { headers }) expect(seeded.ok(), await seeded.text()).toBe(true) const seed = await seeded.json() const requests: string[] = [] page.on('request', request => { if (request.method() === 'GET') requests.push(request.url()) }) const snapshot = page.waitForResponse(response => response.url().includes('/api/app/workspace/snapshot?')) await page.goto('/conversations') expect((await (await snapshot).json()).details).toEqual([]) await page.locator(`.desktop-sidebar [data-sidebar-id="${seed.conversationId}"]`).click() await expect(page.locator('.message')).toHaveCount(50) await page.locator('.composer-tool[title="显示思考"]').click() await page.locator('.turn-trace summary').click() const tool = page.locator('.tool-trace').filter({ hasText: 'read_file' }) await expect(tool).toBeVisible() expect(requests.some(url => url.includes('/tools/'))).toBe(false) await tool.getByRole('button', { name: /read_file/ }).click() await expect(tool.locator('pre').last()).toContainText('工具输出末尾') expect(requests.filter(url => url.includes('/tools/'))).toHaveLength(1) const reloaded = page.waitForResponse(response => response.url().includes('/api/app/workspace/snapshot?')) await page.reload() const selected = await (await reloaded).json() expect(selected.details).toHaveLength(1) expect(selected.details[0].conversation.id).toBe(seed.conversationId) expect(JSON.stringify(selected)).not.toContain('工具输出末尾') await expect(page.locator('.message')).toHaveCount(50) }) test('account update checks show loading, available versions and retry on desktop and phone', async ({ page }, testInfo) => { await login(page) const current = { schemaVersion: 1, releaseVersion: '0.4.17', webVersion: '0.4.17', gitTag: 'v0.4.17' } 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' } await page.route('**/api/app/system/update/status', route => route.fulfill({ json: status })) let failed = false let releaseCheck: (() => void) | undefined await page.route('**/api/app/system/update/check', async route => { await new Promise(resolve => { releaseCheck = resolve }) await route.fulfill(failed ? { status: 502, json: { error: '暂时无法连接更新服务' } } : { json: status }) }) for (const width of [1280, 390]) { await page.setViewportSize({ width, height: 866 }) await page.emulateMedia({ colorScheme: width === 390 ? 'dark' : 'light', reducedMotion: 'reduce' }) const account = page.locator('.desktop-sidebar .sidebar-account-switcher__main') await expect(page.locator('.sidebar-settings-trigger')).toHaveCount(0) await account.click() // The menu's dismiss layer receives the second pointer click over the account. const accountRect = (await account.boundingBox())! await page.mouse.click(accountRect.x + accountRect.width / 2, accountRect.y + accountRect.height / 2) await expect(page.getByRole('menu', { name: '账号菜单' })).toHaveCount(0) await account.click() await page.screenshot({ path: testInfo.outputPath(`update-menu-${width}.png`) }) await page.getByRole('menuitem', { name: '检测更新', exact: true }).click() const dialog = page.getByRole('dialog', { name: '检测更新', exact: true }) await expect(dialog.getByRole('status')).toHaveText('正在检测更新…') await expect(dialog.getByRole('button', { name: '正在检测…', exact: true })).toBeDisabled() await expect.poll(() => Boolean(releaseCheck)).toBe(true) releaseCheck!(); releaseCheck = undefined await expect(dialog.getByRole('status')).toHaveText('发现新版本 0.4.18') await page.screenshot({ path: testInfo.outputPath(`update-available-${width}.png`) }) expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true) failed = true await dialog.getByRole('button', { name: '重新检测', exact: true }).click() await expect.poll(() => Boolean(releaseCheck)).toBe(true) releaseCheck!(); releaseCheck = undefined await expect(dialog.getByRole('alert')).toContainText('暂时无法连接更新服务') await expect(dialog.getByRole('button', { name: '前往更新', exact: true })).toHaveCount(0) failed = false await dialog.getByRole('button', { name: '重试', exact: true }).click() await expect.poll(() => Boolean(releaseCheck)).toBe(true) releaseCheck!(); releaseCheck = undefined await expect(dialog.getByRole('button', { name: '前往更新', exact: true })).toBeVisible() await page.keyboard.press('Escape') await expect(dialog).toHaveCount(0) await expect(account).toBeFocused() } }) test('self-registered subaccount approval supports Bot replies, reload and isolation', async ({ page, browser }, testInfo) => { const childContext = await browser.newContext({ viewport: { width: 1280, height: 800 } }) const child = await childContext.newPage() const username = `registered-${Date.now()}` const denied: string[] = [] child.on('response', response => { if (response.status() === 403 && response.url().includes('/api/app/')) denied.push(new URL(response.url()).pathname) }) try { await child.goto('/conversations') await child.getByRole('button', { name: '没有账号?注册子账号' }).click() await child.getByRole('textbox', { name: '账号', exact: true }).fill(username) await child.getByLabel('密码', { exact: true }).fill('child-password') await child.getByLabel('确认密码', { exact: true }).fill('child-password') await child.getByRole('button', { name: '注册子账号', exact: true }).click() await expect(child.getByRole('status')).toContainText('注册成功') await child.getByLabel('密码', { exact: true }).fill('child-password') await child.getByRole('button', { name: '登录', exact: true }).click() await expect(child.getByRole('alert')).toContainText('尚未开通') await login(page) await page.locator('.desktop-sidebar .sidebar-account-switcher__main').click() await page.getByRole('menuitem', { name: '我的设置', exact: true }).click() const settings = page.getByRole('dialog', { name: '我的设置', exact: true }) await settings.getByRole('button', { name: '用户与权限', exact: true }).click() const row = settings.locator('.user').filter({ hasText: username }) await expect(row).toContainText('待管理员开通') await expect(row.getByRole('button', { name: '分配并开通' })).toBeDisabled() await row.getByRole('listbox').selectOption('default') await row.getByRole('button', { name: '分配并开通' }).click() await expect(row).toContainText('普通用户') await child.getByLabel('密码', { exact: true }).fill('child-password') await child.getByRole('button', { name: '登录', exact: true }).click() await expect(child.getByRole('heading', { name: '还没有聊天' })).toBeVisible() denied.length = 0 await openCreate(child, '新建 Bot') const dialog = child.getByRole('dialog') await expect(dialog.getByLabel('基础机器人').locator('option')).toHaveCount(1) await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('注册验收助手') await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect(child.getByRole('heading', { name: '注册验收助手', exact: true })).toBeVisible() const composer = child.getByRole('textbox', { name: '输入消息,Enter 发送,Shift + Enter 换行' }) await composer.fill('注册后验证 Bot 回复') await composer.press('Enter') await expect.poll(async () => { const id = new URL(child.url()).pathname.split('/').at(-1) const response = await child.request.get(`/api/app/conversations/${id}/messages`) const value = await response.json() return value.messages?.some((m: any) => m.role === 'assistant' && m.status === 'complete' && m.content) }).toBe(true) await expect(child.getByText('会话独立保存', { exact: true })).toBeVisible() await childContext.setOffline(true) await expect(child.getByText('网络已断开,恢复连接后将自动同步', { exact: true })).toBeVisible() await childContext.setOffline(false) await expect(child.getByText('网络已断开,恢复连接后将自动同步', { exact: true })).toBeHidden({ timeout: 15_000 }) await child.reload() await expect(child.getByRole('heading', { name: '注册验收助手', exact: true })).toBeVisible() await expect(child.getByText('注册后验证 Bot 回复', { exact: true }).first()).toBeVisible() expect((await (await page.request.get('/api/app/agents')).json()).agents.some((a: any) => a.name === '注册验收助手')).toBe(false) expect(denied).toEqual([]) await child.screenshot({ path: testInfo.outputPath('registered-subaccount-bot.png'), fullPage: true }) } finally { await childContext.close() } })