Files
XHChat/tests/encrypted-chat.test.mjs

507 lines
31 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { _electron, chromium } from 'playwright'
import electron from 'electron'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
const work = (page) => page.getByRole('navigation', { name: '工作区' })
const testUser = () => 'qa_' + randomBytes(6).toString('hex')
async function login(page, username, password, register) {
if (register) await page.getByRole('button', { name: '注册', exact: true }).click()
await page.getByLabel('用户名').fill(username)
await page.getByLabel('密码', { exact: true }).fill(password)
await page.locator('button.primary').click()
await page.getByText('实时连接已建立').waitFor()
}
async function enable(page) {
await page.getByRole('button', { name: '启用本机加密聊天' }).click()
await page.locator('.security-code').waitFor({ timeout: 10_000 })
return page.locator('.security-code').textContent()
}
async function trust(page, code) {
await page.getByLabel('对方安全码').fill(code)
await page.getByRole('button', { name: '核验设备' }).click()
await page.getByText('设备已验证').waitFor()
}
async function send(page, text) {
await page.getByRole('textbox', { name: '消息', exact: true }).fill(text)
await page.getByRole('button', { name: '发送', exact: true }).click()
try {
await page.getByText(text, { exact: true }).waitFor({ timeout: 10_000 })
} catch (error) {
throw new Error(JSON.stringify(await page.locator('[role=alert]').allTextContents()), { cause: error })
}
}
test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢复', { timeout: 90000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
const profile = await mkdtemp(join(tmpdir(), 'xhchat-mls-test-'))
let desktop
try {
const web = await browser.newPage({ acceptDownloads: true })
await web.goto(base)
desktop = await _electron.launch({
executablePath: electron,
args: [join(import.meta.dirname, '..', 'Desktop'), '--user-data-dir=' + profile, '--use-fake-device-for-media-stream'],
env: { ...process.env, XHCHAT_SERVER_URL: base },
})
const windows = await desktop.firstWindow()
const clientErrors = []
for (const [label, page] of [['web', web], ['windows', windows]]) {
page.on('pageerror', (error) => clientErrors.push(label + ': ' + error.message))
page.on('console', (message) => { if (message.type() === 'error') clientErrors.push(label + ': ' + message.text()) })
}
const a = testUser(), b = testUser()
const password = randomBytes(24).toString('hex')
await login(web, a, password, true)
await login(windows, b, password, true)
await work(web).getByRole('link', { name: '联系人' }).click()
await work(windows).getByRole('link', { name: '联系人' }).click()
await web.getByLabel('按用户名查找').fill(b)
await web.getByRole('button', { name: '查找' }).click()
await web.getByRole('button', { name: '添加好友' }).click()
await windows.getByRole('button', { name: new RegExp(a) }).click()
await windows.getByRole('button', { name: '接受申请' }).click()
await web.getByRole('link', { name: '打开加密聊天' }).waitFor()
await work(web).getByRole('link', { name: '消息', exact: true }).click()
const conversation = web.getByRole('complementary', { name: '会话列表' })
await conversation.getByRole('link', { name: b }).waitFor()
await web.getByLabel('查找会话').fill('没有匹配')
await web.getByText('没有匹配的会话。').waitFor()
await web.getByLabel('查找会话').clear()
await conversation.getByRole('link', { name: b }).click()
await windows.getByRole('link', { name: '打开加密聊天' }).click()
const windowsChat = windows.url()
let webCode, desktopCode
try {
;[webCode, desktopCode] = await Promise.all([enable(web), enable(windows)])
} catch (error) {
throw new Error(JSON.stringify({ web: await web.locator('[role=alert]').allTextContents(), windows: await windows.locator('[role=alert]').allTextContents(), clientErrors }), { cause: error })
}
assert.match(webCode, /^[0-9a-f]{64}$/)
assert.match(desktopCode, /^[0-9a-f]{64}$/)
assert.notEqual(webCode, desktopCode)
const packageRefill = windows.waitForResponse((response) => response.request().method() === 'POST' &&
response.url().endsWith('/api/v1/key-packages') && response.status() === 204)
await web.getByRole('button', { name: '刷新' }).click()
await windows.getByRole('button', { name: '刷新' }).click()
await web.getByLabel('对方安全码').fill('0'.repeat(64))
await web.getByRole('button', { name: '核验设备' }).click()
await web.getByText('安全码不匹配').waitFor()
assert.equal(await web.getByRole('button', { name: '发送', exact: true }).count(), 0)
await trust(web, desktopCode)
await trust(windows, webCode)
const pin = web.getByRole('button', { name: '会话置顶', exact: true })
await pin.click()
await conversation.getByText('已置顶', { exact: true }).waitFor()
assert.equal(await pin.getAttribute('aria-pressed'), 'true')
assert.equal(await windows.getByRole('button', { name: '会话置顶' }).getAttribute('aria-pressed'), 'false')
const text = 'Web 到 Windows ' + randomBytes(8).toString('hex')
const packets = []
web.on('request', (req) => {
if (req.method() === 'POST' && req.url().endsWith('/api/v1/inbox')) packets.push(req.postDataJSON())
})
await send(web, text)
const packet = packets.find((entry) => Buffer.from(entry.ciphertext, 'base64')[3] === 2)
assert.ok(packet)
assert.ok(!Buffer.from(packet.ciphertext, 'base64').includes(Buffer.from(text)))
assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice'])
await windows.getByText(text, { exact: true }).waitFor()
await packageRefill
const sentLine = web.getByRole('listitem').filter({ hasText: text })
assert.equal(await sentLine.getByText('已读', { exact: true }).count(), 0)
assert.equal(await windows.getByLabel('发送已读回执').isChecked(), false)
const receiptPackets = []
windows.on('request', (req) => {
if (req.method() === 'POST' && req.url().endsWith('/api/v1/inbox')) receiptPackets.push(req.postDataJSON())
})
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].focus())
await windows.getByLabel('发送已读回执').check()
await sentLine.getByText('已读', { exact: true }).waitFor({ timeout: 15_000 })
assert.ok(receiptPackets.length > 0)
assert.ok(receiptPackets.every((item) => item.silent === true))
assert.ok(receiptPackets.every((item) => !JSON.stringify(item).includes(packet.messageId)))
const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex')
await windows.getByRole('listitem').filter({ hasText: text }).getByRole('button', { name: '引用', exact: true }).click()
await send(windows, reply)
await web.getByText(reply, { exact: true }).waitFor()
await web.getByRole('listitem').filter({ hasText: reply }).locator('blockquote').getByText(text, { exact: true }).waitFor()
assert.equal(await web.getByRole('listitem').filter({ hasText: reply }).getByRole('button', { name: '编辑', exact: true }).count(), 0)
const edited = '编辑后 ' + randomBytes(8).toString('hex')
await windows.getByRole('listitem').filter({ hasText: reply }).getByRole('button', { name: '编辑', exact: true }).click()
await windows.getByRole('textbox', { name: '消息', exact: true }).fill(edited)
await windows.getByRole('button', { name: '保存编辑', exact: true }).click()
await web.getByRole('listitem').filter({ hasText: edited }).getByText('已编辑', { exact: true }).waitFor()
await windows.getByRole('listitem').filter({ hasText: edited }).getByRole('button', { name: '撤回', exact: true }).click()
await windows.getByRole('button', { name: '确认撤回', exact: true }).click()
await web.getByText('消息已撤回', { exact: true }).waitFor()
assert.equal(await web.getByText(edited, { exact: true }).count(), 0)
const original = web.getByRole('listitem').filter({ has: web.getByText(text, { exact: true }) }).filter({ hasNot: web.locator('blockquote') })
await original.getByRole('button', { name: '收藏', exact: true }).click()
await original.getByRole('button', { name: '取消收藏' }).waitFor()
await web.getByLabel('只看收藏').check()
assert.equal(await web.getByRole('listitem').count(), 1)
await web.getByLabel('搜索本机消息').fill('无匹配的搜索词')
await web.getByText('没有匹配的消息。').waitFor()
await web.getByLabel('搜索本机消息').clear()
await web.getByLabel('只看收藏').uncheck()
await original.getByRole('button', { name: '本机删除' }).click()
await web.getByRole('button', { name: '确认删除' }).click()
await original.waitFor({ state: 'detached' })
await windows.getByRole('listitem').filter({ hasText: text }).filter({ hasNot: windows.locator('blockquote') }).waitFor()
const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex'))
const fileName = '跨端验收.txt'
const remainingFile = '私聊批量重试.txt'
const discardedFile = '待移除附件.txt'
const payload = (name, buffer = Buffer.from(name)) => ({ name, mimeType: 'text/plain', buffer })
const dropZone = (page) => page.getByRole('region', { name: '私聊附件发送区' })
const sendBatch = (page) => dropZone(page).getByRole('button', { name: '发送私聊附件', exact: true }).click()
const queue = dropZone(windows).getByRole('list', { name: '待发私聊附件' })
const transfer = await windows.evaluateHandle((name) => {
const data = new DataTransfer()
data.items.add(new File([name], name, { type: 'text/plain' }))
return data
}, remainingFile)
await dropZone(windows).locator('input:enabled').setInputFiles([payload(fileName, contents), payload(discardedFile)])
assert.equal(await queue.getByRole('listitem').count(), 2)
await queue.getByRole('button', { name: '移除 ' + discardedFile, exact: true }).click()
await dropZone(windows).dispatchEvent('dragover', { dataTransfer: transfer })
await dropZone(windows).dispatchEvent('drop', { dataTransfer: transfer })
await transfer.dispose()
assert.deepEqual(await queue.getByRole('listitem').locator('span').allTextContents(), [fileName, remainingFile])
assert.equal(await web.getByRole('button', { name: '下载 ' + fileName, exact: true }).count(), 0)
const uploadMatcher = (url) => url.pathname.startsWith('/api/v1/attachments/') && url.searchParams.has('recipient')
let attempts = 0
const failSecond = async (route) => {
if (route.request().method() === 'POST' && ++attempts === 2) {
await route.fulfill({ status: 503, headers: { 'access-control-allow-origin': 'xhchat://app' },
json: { error: { message: '私聊附件上传暂不可用' } } })
} else await route.continue()
}
await windows.route(uploadMatcher, failSecond)
const upload = windows.waitForRequest((req) => req.method() === 'POST' && req.url().includes('/api/v1/attachments/'))
await sendBatch(windows)
const fileRequest = await upload
const uploaded = fileRequest.postDataBuffer()
assert.ok(uploaded)
assert.equal(uploaded.length, contents.length + 16)
assert.ok(!uploaded.includes(contents))
assert.ok(!fileRequest.url().includes(encodeURIComponent(fileName)))
const fileButton = web.getByRole('button', { name: '下载 ' + fileName, exact: true })
await fileButton.waitFor()
await windows.getByRole('alert').getByText('私聊附件上传暂不可用', { exact: true }).waitFor()
assert.deepEqual(await queue.getByRole('listitem').locator('span').allTextContents(), [remainingFile])
await windows.unroute(uploadMatcher, failSecond)
await sendBatch(windows)
await web.getByRole('button', { name: '下载 ' + remainingFile, exact: true }).waitFor()
await queue.waitFor({ state: 'detached' })
assert.equal(await fileButton.count(), 1)
assert.equal(await web.getByRole('button', { name: '下载 ' + discardedFile, exact: true }).count(), 0)
const fileURL = new URL(fileRequest.url())
await web.route(fileURL.origin + fileURL.pathname, async (route) => {
const response = await route.fetch()
const corrupted = await response.body()
corrupted[0] ^= 1
await route.fulfill({ response, body: corrupted })
}, { times: 1 })
await fileButton.click()
await web.getByText('附件完整性校验失败').waitFor()
const downloaded = web.waitForEvent('download')
await fileButton.click()
const file = await downloaded
assert.equal(file.suggestedFilename(), fileName)
assert.deepEqual(await readFile(await file.path()), contents)
const forwardedRequest = web.waitForRequest((req) => req.method() === 'POST' && req.url().includes('/api/v1/attachments/'))
await web.getByRole('listitem').filter({ hasText: fileName }).getByRole('button', { name: '转发', exact: true }).click()
await web.getByLabel('转发给').selectOption({ label: b })
await web.getByRole('button', { name: '确认转发' }).click()
const forwarded = await forwardedRequest
assert.notEqual(new URL(forwarded.url()).pathname, fileURL.pathname)
assert.notDeepEqual(forwarded.postDataBuffer(), uploaded)
await windows.getByRole('button', { name: '下载 ' + fileName, exact: true }).nth(1).waitFor()
await windows.getByRole('button', { name: '录制语音', exact: true }).click()
await windows.getByRole('button', { name: '发送语音', exact: true }).waitFor()
await windows.getByText(/录音中 1 \/ 60 秒/).waitFor()
await windows.getByRole('button', { name: '发送语音', exact: true }).click()
await web.getByRole('button', { name: '播放语音', exact: true }).click()
await web.waitForFunction(() => {
const audio = document.querySelector('audio')
return audio && audio.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && audio.currentTime > 0
})
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jf2sAAAAASUVORK5CYII=', 'base64')
const webInput = dropZone(web).locator('input:enabled')
const webQueue = dropZone(web).getByRole('list', { name: '待发私聊附件' })
await webInput.setInputFiles(Array.from({ length: 9 }, (_, index) => payload('容量测试' + index + '.txt')))
await web.getByText('每批最多发送 8 个私聊附件', { exact: true }).waitFor()
assert.equal(await webQueue.count(), 0)
await webInput.setInputFiles(payload('清空测试.txt'))
await webQueue.getByText('清空测试.txt', { exact: true }).waitFor()
await dropZone(web).getByRole('button', { name: '清空待发附件', exact: true }).click()
await webQueue.waitFor({ state: 'detached' })
await webInput.setInputFiles({ name: '加密预览.png', mimeType: 'image/png', buffer: pixel })
await sendBatch(web)
await windows.getByRole('button', { name: '预览 加密预览.png' }).click()
const image = windows.getByRole('img', { name: '加密预览.png' })
await image.waitFor()
await windows.waitForFunction(() => document.querySelector('img[alt="加密预览.png"]')?.naturalWidth === 1)
assert.match(await image.getAttribute('src'), /^blob:/)
await windows.getByRole('button', { name: '关闭预览' }).click()
assert.equal(await image.count(), 0)
const privateDraft = '重新登录恢复的私聊草稿 ' + randomBytes(8).toString('hex')
await windows.getByRole('textbox', { name: '消息', exact: true }).fill(privateDraft)
await windows.getByText('草稿已保存在本机', { exact: true }).waitFor()
assert.ok(!(await windows.evaluate(() => JSON.stringify(localStorage))).includes(privateDraft))
await windows.getByRole('button', { name: '退出登录' }).click()
await windows.getByRole('heading', { name: '登录 XHChat' }).waitFor()
const offline = '离线补拉 ' + randomBytes(8).toString('hex')
await send(web, offline)
await login(windows, b, password, false)
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
assert.equal(await enable(windows), desktopCode)
await windows.getByText('已恢复本机草稿', { exact: true }).waitFor()
assert.equal(await windows.getByRole('textbox', { name: '消息', exact: true }).inputValue(), privateDraft)
await windows.getByRole('textbox', { name: '消息', exact: true }).clear()
await windows.getByText(offline, { exact: true }).waitFor()
const stored = await windows.evaluate(async () => {
const db = await new Promise((resolve, reject) => {
const request = indexedDB.open('xhchat-encrypted-chat', 1)
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
try {
return await new Promise((resolve, reject) => {
const request = db.transaction('vaults').objectStore('vaults').getAll()
request.onsuccess = () => resolve(request.result.map((value) => ({
wrapped: typeof value.key === 'string',
encrypted: value.sealed instanceof ArrayBuffer && value.sealed.byteLength > 0,
fields: Object.keys(value).sort(),
})))
request.onerror = () => reject(request.error)
})
} finally { db.close() }
})
assert.deepEqual(stored, [{ wrapped: true, encrypted: true, fields: ['iv', 'key', 'sealed'] }])
const systemToggle = (page) => page.getByRole('button', { name: '消息系统通知', exact: true })
const privateNotice = (page) => page.getByRole('link', { name: '有新的私聊消息', exact: true })
const muteToggle = (page) => page.getByRole('button', { name: '消息免打扰', exact: true })
await desktop.evaluate(({ Notification }) => {
const nativeShow = Notification.prototype.show
globalThis.privateNotificationLog = []
Notification.prototype.show = function () {
globalThis.privateNotificationLog.push({ title: this.title, body: this.body })
return nativeShow.call(this)
}
})
await systemToggle(windows).click()
await windows.getByText('已在本设备启用消息系统通知', { exact: true }).waitFor()
await work(windows).getByRole('link', { name: '设备管理' }).click()
const desktopNoticeText = 'Windows 后台私聊 ' + randomBytes(8).toString('hex')
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].minimize())
try {
await send(web, desktopNoticeText)
const toast = await desktop.evaluate(async () => {
for (let attempt = 0; attempt < 30 && !globalThis.privateNotificationLog.length; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 150))
}
return globalThis.privateNotificationLog[0]
})
assert.deepEqual(toast, { title: 'XHChat', body: '有新的私聊消息' })
} finally {
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].restore())
}
await privateNotice(windows).click()
await windows.waitForURL(windowsChat)
await enable(windows)
await windows.getByText(desktopNoticeText, { exact: true }).waitFor()
assert.equal(await systemToggle(web).getAttribute('aria-pressed'), 'false')
await web.context().grantPermissions(['notifications'], { origin: base })
await web.evaluate(() => {
const BrowserNotification = window.Notification
window.privateNotificationLog = []
window.Notification = class extends BrowserNotification {
constructor(title, options) {
super(title, options)
window.privateNotificationLog.push({ title, body: options.body, tag: options.tag })
}
}
document.hasFocus = () => false
})
await systemToggle(web).click()
await web.getByText('已在本设备启用消息系统通知', { exact: true }).waitFor()
const webChat = web.url()
await work(web).getByRole('link', { name: '设备管理' }).click()
const webNoticeText = 'Edge 后台私聊 ' + randomBytes(8).toString('hex')
await send(windows, webNoticeText)
await privateNotice(web).waitFor()
await web.waitForFunction(() => window.privateNotificationLog.length === 1)
assert.deepEqual(await web.evaluate(() => window.privateNotificationLog[0]),
{ title: 'XHChat', body: '有新的私聊消息', tag: 'xhchat-private' })
await privateNotice(web).click()
await web.waitForURL(webChat)
await enable(web)
await web.getByText(webNoticeText, { exact: true }).waitFor()
await conversation.getByText('已置顶', { exact: true }).waitFor()
await pin.click()
await conversation.getByText('已置顶', { exact: true }).waitFor({ state: 'detached' })
await conversation.locator('.unread-badge').waitFor()
await web.evaluate(() => { document.hasFocus = () => true; window.dispatchEvent(new Event('focus')) })
await conversation.locator('.unread-badge').waitFor({ state: 'detached' })
await muteToggle(web).click()
await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor()
assert.equal(await muteToggle(windows).getAttribute('aria-pressed'), 'false')
await work(web).getByRole('link', { name: '联系人' }).click()
await web.getByRole('button', { name: new RegExp(b) }).click()
await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor()
const mutedText = '免打扰仍能同步 ' + randomBytes(8).toString('hex')
await send(windows, mutedText)
await work(web).getByRole('link', { name: '消息', exact: true }).click()
const badge = conversation.getByRole('link', { name: new RegExp(b) }).locator('.unread-badge.muted')
await badge.waitFor()
assert.equal(await badge.locator('.unread-label').textContent(), '1 条未读')
await work(web).getByRole('link', { name: '联系人' }).click()
await web.getByRole('button', { name: new RegExp(b) }).click()
await web.getByRole('link', { name: '打开加密聊天' }).click()
await enable(web)
await web.getByText(mutedText, { exact: true }).waitFor()
await badge.waitFor({ state: 'detached' })
assert.equal(await privateNotice(web).count(), 0)
assert.equal(await web.evaluate(() => window.privateNotificationLog.length), 1)
const link = base + '/healthz'
await send(web, link)
const webLink = web.getByRole('link', { name: link, exact: true })
assert.equal(await webLink.getAttribute('href'), link)
assert.equal(await webLink.getAttribute('rel'), 'noopener noreferrer')
const windowOpened = desktop.waitForEvent('window')
await windows.getByRole('button', { name: link, exact: true }).click()
const toolbar = await windowOpened
const address = toolbar.getByRole('textbox', { name: '网址或搜索关键词' })
await toolbar.waitForFunction((expected) => document.querySelector('#address')?.value === expected, link)
assert.equal(await address.inputValue(), link)
await toolbar.close()
async function addFavorite(page, locator) {
const line = page.getByRole('list', { name: '消息记录' }).getByRole('listitem').filter({ has: locator })
await line.getByRole('button', { name: '收藏', exact: true }).click()
await line.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
}
await addFavorite(web, webLink)
await addFavorite(web, web.getByRole('button', { name: '下载 ' + remainingFile, exact: true }))
await addFavorite(windows, windows.getByRole('button', { name: '预览 加密预览.png', exact: true }))
await addFavorite(windows, windows.getByRole('button', { name: '播放语音', exact: true }))
await Promise.all([web, windows].map((page) => work(page).getByRole('link', { name: '收藏', exact: true }).click()))
const webFavorites = web.getByRole('list', { name: '本机收藏' })
const windowsFavorites = windows.getByRole('list', { name: '本机收藏' })
await webFavorites.getByRole('link', { name: link, exact: true }).waitFor()
assert.equal(await webFavorites.getByRole('listitem').count(), 2)
const tracked = []
const trackFavorites = (request) => tracked.push([request.url(), request.method(), request.postData()])
web.on('request', trackFavorites)
await web.getByLabel('内容类型').selectOption('link')
assert.equal(await webFavorites.getByRole('listitem').count(), 1)
const search = web.getByRole('searchbox', { name: '搜索本机收藏' })
const marker = '本机收藏验收 ' + randomBytes(8).toString('hex')
await search.fill(marker)
await web.getByText('没有匹配的收藏。', { exact: true }).waitFor()
await search.clear()
await web.getByLabel('内容类型').selectOption('file')
const favoriteDownload = web.waitForEvent('download')
await webFavorites.getByRole('button', { name: '下载 ' + remainingFile, exact: true }).click()
assert.deepEqual(await readFile(await (await favoriteDownload).path()), Buffer.from(remainingFile))
await webFavorites.getByRole('button', { name: '取消收藏', exact: true }).click()
await web.getByText('没有匹配的收藏。', { exact: true }).waitFor()
await web.getByLabel('内容类型').selectOption('link')
await webFavorites.getByRole('button', { name: '编辑标签', exact: true }).click()
await web.getByLabel('收藏标签').fill('验收资料,DOC,Doc')
await webFavorites.getByRole('button', { name: '保存标签', exact: true }).click()
await webFavorites.getByRole('button', { name: '验收资料', exact: true }).waitFor()
assert.equal(await webFavorites.locator('.favorite-tags button').count(), 2)
await web.getByLabel('标签筛选', { exact: true }).selectOption('doc')
await search.fill('dOc')
await webFavorites.getByRole('link', { name: link, exact: true }).waitFor()
await work(web).getByRole('link', { name: '联系人', exact: true }).click()
await work(web).getByRole('link', { name: '收藏', exact: true }).click()
await webFavorites.getByRole('button', { name: '验收资料', exact: true }).waitFor()
web.off('request', trackFavorites)
assert.ok(tracked.every(([url, method, body]) => method === 'GET' && !body &&
!url.includes(encodeURIComponent(marker)) && !url.includes(encodeURIComponent('验收资料'))))
const originalLink = webFavorites.getByRole('link', { name: '查看原消息', exact: true })
assert.ok(!(await originalLink.getAttribute('href')).includes('healthz'))
await originalLink.click()
const locatedPrivate = web.getByRole('list', { name: '消息记录' }).locator('li[aria-current="true"]')
await locatedPrivate.getByRole('link', { name: link, exact: true }).waitFor()
await locatedPrivate.evaluate((row) => {
if (document.activeElement !== row) throw new Error('私聊原消息未获得焦点')
})
await windows.getByLabel('内容类型').selectOption('image')
await windowsFavorites.getByRole('button', { name: '预览 加密预览.png', exact: true }).click()
await windowsFavorites.getByRole('img', { name: '加密预览.png' }).waitFor()
await windows.getByLabel('内容类型').selectOption('voice')
await windowsFavorites.getByRole('button', { name: '播放语音', exact: true }).click()
await windows.waitForFunction(() => document.querySelector('.favorite-card audio')?.currentTime > 0)
assert.equal(await windowsFavorites.getByRole('link', { name: link, exact: true }).count(), 0)
await windows.getByLabel('内容类型').selectOption('all')
await windows.getByRole('button', { name: '批量管理', exact: true }).click()
await windows.getByRole('button', { name: '选择当前列表', exact: true }).click()
const bulk = windows.getByRole('button', { name: '取消所选收藏(2)', exact: true })
await bulk.click()
const confirmation = windows.getByRole('region', { name: '确认取消收藏' })
await confirmation.getByRole('button', { name: '返回', exact: true }).click()
assert.equal(await windowsFavorites.getByRole('listitem').count(), 2)
await bulk.click()
await confirmation.getByRole('button', { name: '确认取消收藏', exact: true }).click()
await windows.getByText('本机还没有收藏。', { exact: true }).waitFor()
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
await enable(windows)
await windows.getByRole('button', { name: '预览 加密预览.png', exact: true }).waitFor()
await windows.getByRole('button', { name: '播放语音', exact: true }).waitFor()
await work(windows).getByRole('link', { name: '设置', exact: true }).click()
await windows.getByLabel('消息发送方式', { exact: true }).selectOption('ctrl-enter')
await windows.getByRole('button', { name: '保存设置' }).click()
await windows.getByText('已保存本机设置').waitFor()
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
await enable(windows)
const composer = windows.getByRole('textbox', { name: '消息', exact: true })
const shortcutText = '快捷键验收 ' + randomBytes(8).toString('hex')
await composer.fill(shortcutText)
await composer.press('Enter')
assert.equal(await composer.inputValue(), shortcutText + '\n')
await composer.dispatchEvent('keydown', { key: 'Enter', ctrlKey: true, isComposing: true, bubbles: true, cancelable: true })
assert.equal(await windows.getByRole('list', { name: '消息记录' }).getByText(shortcutText, { exact: true }).count(), 0)
await composer.press('Control+Enter')
await web.getByRole('list', { name: '消息记录' }).getByText(shortcutText, { exact: true }).waitFor()
await work(windows).getByRole('link', { name: '联系人' }).click()
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
await enable(windows)
await composer.fill('编辑时保留的草稿')
await windows.getByText('草稿已保存在本机', { exact: true }).waitFor()
await windows.getByRole('listitem').filter({ hasText: shortcutText }).getByRole('button', { name: '编辑', exact: true }).click()
await composer.fill('临时编辑内容')
await windows.getByRole('button', { name: '取消编辑' }).click()
assert.equal(await composer.inputValue(), '编辑时保留的草稿')
} finally {
if (desktop) await desktop.evaluate(({ dialog }) => { dialog.showMessageBoxSync = () => 1 }).catch(() => {})
await desktop?.close()
await browser.close()
await rm(profile, { recursive: true, maxRetries: 5, retryDelay: 200, force: true })
}
})