增加会话导航与可选加密已读回执 #16

Merged
xhgit merged 1 commits from xhgit/chat-conversations-receipts into main 2026-11-14 08:12:42 +08:00
8 changed files with 218 additions and 17 deletions

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 |
| 消息管理 | 支持引用回复、编辑、撤回、转发、搜索本机历史、收藏和本机删除。 |
| 消息管理 | 支持会话查找、可选加密已读回执、引用回复、编辑、撤回、转发、本机搜索和收藏。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+4
View File
@@ -76,3 +76,7 @@ Windows 浏览器新增可跨窗口保留的本地书签和历史,每类最多
## 聊天中的链接
加密文字消息中的 HTTPS 链接在端侧识别。Windows 从链接启动隔离 Chromium,Web 在独立标签页打开并隔离 opener。开发环境支持本机 HTTP。真实双端测试验证消息链接点击与 Chromium 地址显示。网页卡片与从浏览器分享给联系人仍待实现。
## 会话导航和已读回执
「消息」页支持按用户名或备注查找已接受的联系人,按本机最近消息时间排序。用户可按设备开启已读回执,默认关闭。开启后,仅在窗口聚焦且消息显示于可见区域时,通过 MLS 发送已读消息 ID。发送端根据对方设备身份和原消息 ID 更新状态。偏好、状态与待发回执保存在端侧加密记录中。
+20 -1
View File
@@ -70,7 +70,14 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
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: '打开加密聊天' }).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
@@ -102,6 +109,18 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
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()
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) => !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)
+14 -1
View File
@@ -54,10 +54,19 @@ export function encodeAttachment(attachment: Attachment) {
}
export type Mutation = { action: 'edit' | 'recall'; id: string; text?: string }
type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation }
type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation; read?: string[] }
const messageID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
export function decodeMessage(message: Uint8Array): ChatContent {
if (message[0] !== 255) return { text: decoder.decode(message) }
if (message[1] === 4 && message.length <= 4096) {
const ids: unknown = JSON.parse(decoder.decode(message.subarray(2)))
if (!Array.isArray(ids) || ids.length === 0 || ids.length > 64 ||
!ids.every((id) => typeof id === 'string' && messageID.test(id))) {
throw new Error('已读回执格式无效')
}
return { text: '', read: ids }
}
if (message[1] === 3 && message.length <= 18_000) {
const value = JSON.parse(decoder.decode(message.subarray(2))) as Mutation | null
if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) ||
@@ -93,6 +102,10 @@ export function encodeMutation(mutation: Mutation) {
return encodeContent(3, mutation)
}
export function encodeRead(ids: string[]) {
return encodeContent(4, ids)
}
function encodeContent(kind: number, value: object) {
const body = encoder.encode(JSON.stringify(value))
if (body.length + 2 > 18_000) throw new Error('消息内容过长')
+65 -5
View File
@@ -3,7 +3,7 @@ import { mlsBinding, signMls } from '../identity'
import { base64, decode, fingerprint, loadEngine } from './engine'
import type { DeviceMls } from './engine'
import { withVault } from './vault'
import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, readAttachment, sealAttachment, uploadAttachment } from './attachments'
import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readAttachment, sealAttachment, uploadAttachment } from './attachments'
import type { Attachment, Mutation } from './attachments'
export interface Peer {
@@ -31,6 +31,8 @@ export interface ChatLine {
favorite?: boolean
recalled?: boolean
edited?: boolean
read?: boolean
contact?: string
time: string
own: boolean
}
@@ -45,6 +47,7 @@ interface ChatState {
groups: Record<string, string>
package?: { lastPublished: number; item: Package }
rejected: number
shareRead?: boolean
}
export type Call = <T>(path: string, method?: string, body?: object, binary?: boolean) => Promise<T>
@@ -233,7 +236,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
const id = crypto.randomUUID()
const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext)
state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext) })
state.lines.push({ id, peer: current.id, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
state.lines.push({ id, peer: current.id, contact: user, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
state.engine = base64(engine.snapshot())
await save(state)
await flush(state, save, call)
@@ -266,9 +269,60 @@ export async function forwardMessage(identity: ChatIdentity, line: ChatLine, rec
await send(identity, recipient, device, content, call)
}
export function recentConversations(identity: ChatIdentity) {
return withVault<ChatState, Record<string, string>>(identity.device.id, async (state) => {
const recent: Record<string, string> = {}
for (const line of state?.lines ?? []) {
if (line.contact && (!recent[line.contact] || recent[line.contact] < line.time)) recent[line.contact] = line.time
}
return recent
}, true)
}
export function markRead(identity: ChatIdentity, user: string, peer: Peer, visible: string[], call: Call) {
return update(identity, async (state, save, factory) => {
if (!state.shareRead) return
const selected = new Set(visible)
const lines = state.lines.filter((line) => line.peer === peer.id && !line.own && !line.read && !line.recalled && selected.has(line.id)).slice(0, 64)
const group = state.groups[peer.id]
if (!lines.length || !group || state.pinned[peer.id] !== peer.publicKey) return
const current = (await directory(call, user)).find((device) => device.id === peer.id)
if (!current || current.publicKey !== peer.publicKey) return
await verifiedPeer(current, user)
const engine = factory.DeviceMls.restore(decode(state.engine))
try {
const id = crypto.randomUUID()
const bytes = engine.encrypt(decode(group), aad(id, identity.device.id, peer.id), encodeRead(lines.map((line) => line.id)))
state.outbox.push({ messageId: id, recipientDevice: peer.id, ciphertext: base64(bytes) })
for (const line of lines) line.read = true
state.engine = base64(engine.snapshot())
await save(state)
await flush(state, save, call)
} finally {
engine.free()
}
})
}
export function setReadReceipts(identity: ChatIdentity, enabled: boolean) {
return update(identity, async (state, save) => {
state.shareRead = enabled
await save(state)
})
}
export function synchronize(identity: ChatIdentity, user: string, call: Call) {
return update(identity, async (state, save, factory) => {
const peers = await directory(call, user)
const peerIDs = new Set(peers.map((peer) => peer.id))
let backfilled = false
for (const line of state.lines) {
if (!line.contact && peerIDs.has(line.peer)) {
line.contact = user
backfilled = true
}
}
if (backfilled) await save(state)
for (let page = 0; page < 4; page++) {
const inbox = await call<Incoming[]>('/inbox?after=' + state.cursor)
if (!inbox.length) break
@@ -292,12 +346,18 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
} else {
const plaintext = engine.decrypt(peer.id, key, aad(item.messageId, peer.id, identity.device.id), wire)
const content = decodeMessage(plaintext)
if (content.mutation) {
if (content.read) {
const ids = new Set(content.read)
for (const line of state.lines) {
if (line.own && line.peer === peer.id && ids.has(line.id)) line.read = true
}
} else if (content.mutation) {
const mutation = content.mutation
const changed = state.lines.find((line) => !line.own && line.peer === peer.id && line.id === mutation.id)
if (changed) applyMutation(changed, mutation)
} else if (state.lines.length < 1000) {
state.lines.push({ id: item.messageId, peer: peer.id, ...content, time: item.createdAt, own: false })
state.lines.push({ id: item.messageId, peer: peer.id, contact: user, text: content.text,
attachment: content.attachment, quote: content.quote, time: item.createdAt, own: false })
}
}
state.engine = base64(engine.snapshot())
@@ -316,7 +376,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
} catch (cause) {
deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试'
}
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError,
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, shareRead: state.shareRead === true,
unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) }
})
}
+2 -1
View File
@@ -47,13 +47,14 @@ async function unsealKey(value: VaultRecord['key']) {
}
}
export async function withVault<T, R>(device: string, update: (state: T | undefined, save: (state: T) => Promise<void>) => Promise<R>) {
export async function withVault<T, R>(device: string, update: (state: T | undefined, save: (state: T) => Promise<void>) => Promise<R>, readOnly = false) {
const scope = (window.xhchat?.apiBase ?? location.origin) + '/' + device
const additionalData = new TextEncoder().encode(scope)
return navigator.locks.request('xhchat-chat:' + scope, async () => {
const db = await database()
try {
const stored = await record(db, scope)
if (!stored && readOnly) return await update(undefined, async () => { throw new Error('会话尚未启用') })
const wrapped = stored?.key ?? await newKey()
const key = await unsealKey(wrapped)
const state = stored?.iv && stored.sealed
+8
View File
@@ -93,6 +93,14 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.message-actions { margin-top: 5px; }
.message-actions .plain { font-size: .78em; padding: 2px 6px; }
.chat-link { border: 0; background: transparent; color: var(--green); text-decoration: underline; padding: 0; overflow-wrap: anywhere; font: inherit; }
.conversation-layout { display: grid; grid-template-columns: minmax(140px, 210px) minmax(0, 1fr); min-width: 0; }
.conversation-list { display: grid; align-content: start; gap: 6px; padding: 14px; border-right: 1px solid var(--line); min-width: 0; }
.conversation-list a { text-decoration: none; }
.conversation-list a.router-link-exact-active { background: var(--green-soft); }
@media (max-width: 840px) {
.conversation-layout { grid-template-columns: minmax(0, 1fr); }
.conversation-list { border-right: 0; border-bottom: 1px solid var(--line); max-height: 185px; overflow: auto; }
}
.account-footer { display: grid; gap: 12px; margin-top: auto; }
.account-footer p { color: var(--muted); font-size: 13px; }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); margin: 0 8px 1px 4px; }
+104 -8
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { directory, enableChat, forwardMessage, localMessageAction, mutateMessage, send, synchronize, trust } from '../chat/chat'
import { directory, enableChat, forwardMessage, localMessageAction, markRead, mutateMessage, recentConversations, send, setReadReceipts, synchronize, trust } from '../chat/chat'
import type { ChatLine, Peer } from '../chat/chat'
import type { Contact } from '../contacts'
import { downloadAttachment } from '../chat/attachments'
@@ -27,11 +27,23 @@ const destinationDevice = ref('')
const forwardDevices = ref<Peer[]>([])
const error = ref('')
const busy = ref(false)
const contacts = ref<Contact[]>([])
const recent = ref<Record<string, string>>({})
const conversationQuery = ref('')
const history = ref<HTMLOListElement>()
const shareRead = ref(false)
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '')
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
const conversations = computed(() => {
const query = conversationQuery.value.trim().toLowerCase()
return contacts.value.filter((item) => item.state === 'friend' &&
[item.alias, item.username].some((value) => value.toLowerCase().includes(query)))
.sort((a, b) => (recent.value[b.id] ?? '').localeCompare(recent.value[a.id] ?? '') ||
(a.alias || a.username).localeCompare(b.alias || b.username))
})
const lines = computed(() => {
const query = search.value.trim().toLowerCase()
return (view.value?.lines ?? []).filter((line) => line.peer === selected.value &&
@@ -64,6 +76,20 @@ function openLink(url: string) {
if (internalBrowser) void execute(() => internalBrowser(url))
}
let timer: ReturnType<typeof setInterval>
let receiptTimer: ReturnType<typeof setTimeout> | undefined
async function loadConversations() {
const identity = session.identity
if (!identity) return
try {
const [people, dates] = await Promise.all([session.contacts(), recentConversations(identity)])
if (session.identity?.device.id !== identity.device.id) return
contacts.value = people
recent.value = dates
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法加载会话'
}
}
async function execute(action: () => Promise<void>) {
if (busy.value || !session.identity) return
@@ -75,6 +101,7 @@ async function execute(action: () => Promise<void>) {
error.value = cause instanceof Error ? cause.message : '加密聊天暂不可用'
} finally {
busy.value = false
scheduleReceipt()
}
}
@@ -85,9 +112,52 @@ async function refresh() {
const current = await synchronize(identity, contact, session.authorized)
if (target.value !== contact) return
view.value = current
shareRead.value = current.shareRead
for (const line of current.lines) {
if (line.contact && (!recent.value[line.contact] || recent.value[line.contact] < line.time)) {
recent.value[line.contact] = line.time
}
}
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
}
function scheduleReceipt() {
clearTimeout(receiptTimer)
if (!view.value?.shareRead || busy.value || !trusted.value) return
receiptTimer = setTimeout(async () => {
await nextTick()
const identity = session.identity
const selectedPeer = peer.value
const list = history.value
if (busy.value || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
const bounds = list.getBoundingClientRect()
const ids = Array.from(list.querySelectorAll<HTMLElement>('[data-unread]')).filter((row) => {
const rect = row.getBoundingClientRect()
return Math.min(rect.bottom, bounds.bottom, innerHeight) - Math.max(rect.top, bounds.top, 0) >= Math.min(rect.height, 24)
}).map((row) => row.dataset.unread!).slice(0, 64)
if (!ids.length) return
await execute(async () => {
await markRead(identity, target.value, selectedPeer, ids, session.authorized)
await refresh()
})
}, 300)
}
function toggleReceipts(event: Event) {
const checked = (event.target as HTMLInputElement).checked
shareRead.value = checked
void execute(async () => {
if (!session.identity) return
try {
await setReadReceipts(session.identity, checked)
} catch (cause) {
shareRead.value = !checked
throw cause
}
await refresh()
})
}
function enable() {
void execute(async () => {
if (!session.identity) return
@@ -212,10 +282,23 @@ watch(selected, () => {
recalling.value = undefined
forwarding.value = undefined
draft.value = ''
scheduleReceipt()
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
onMounted(() => { timer = setInterval(sync, 10_000) })
onBeforeUnmount(() => clearInterval(timer))
watch(() => [session.contactChanges, session.connection], () => void loadConversations())
watch([search, favoritesOnly], scheduleReceipt)
onMounted(() => {
void loadConversations()
timer = setInterval(sync, 10_000)
window.addEventListener('focus', scheduleReceipt)
document.addEventListener('visibilitychange', scheduleReceipt)
})
onBeforeUnmount(() => {
clearInterval(timer)
clearTimeout(receiptTimer)
window.removeEventListener('focus', scheduleReceipt)
document.removeEventListener('visibilitychange', scheduleReceipt)
})
</script>
<template>
@@ -224,7 +307,16 @@ onBeforeUnmount(() => clearInterval(timer))
<h1>加密聊天</h1>
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
</header>
<div class="device-content chat-page">
<div class="conversation-layout">
<aside class="conversation-list" aria-label="会话列表">
<label>查找会话<input v-model="conversationQuery" type="search" maxlength="120"></label>
<RouterLink v-for="contact in conversations" :key="contact.id" class="contact-item" :to="'/chat/' + contact.id">
<span class="avatar" aria-hidden="true">{{ contact.username[0]?.toUpperCase() }}</span>
<span><strong>{{ contact.alias || contact.username }}</strong><small v-if="recent[contact.id]">{{ new Date(recent[contact.id]).toLocaleDateString('zh-CN') }}</small></span>
</RouterLink>
<p v-if="!conversations.length" class="muted">{{ conversationQuery ? '没有匹配的会话。' : '添加好友后可开始聊天。' }}</p>
</aside>
<div class="device-content chat-page">
<p v-if="error" class="error" role="alert">{{ error }}</p>
<button v-if="!ownCode" type="button" class="primary" :disabled="busy" @click="enable">启用本机加密聊天</button>
<template v-else>
@@ -253,9 +345,11 @@ onBeforeUnmount(() => clearInterval(timer))
<div class="chat-filters">
<label>搜索本机消息<input v-model="search" type="search" maxlength="120"></label>
<label class="chat-checkbox"><input v-model="favoritesOnly" type="checkbox">只看收藏</label>
<label class="chat-checkbox"><input type="checkbox" :checked="shareRead" :disabled="busy" @change="toggleReceipts">发送已读回执</label>
</div>
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }">
<ol ref="history" class="chat-lines" aria-label="消息记录" aria-live="polite" @scroll.passive="scheduleReceipt">
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }"
:data-unread="!line.own && !line.read && !line.recalled ? line.id : undefined">
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<span v-if="line.recalled" class="muted">消息已撤回</span>
<button v-else-if="line.attachment" type="button" class="plain" :disabled="busy"
@@ -264,6 +358,7 @@ onBeforeUnmount(() => clearInterval(timer))
type="button" class="chat-link" @click="openLink(part.url)">{{ part.text }}</button><a v-else-if="part.url"
class="chat-link" :href="part.url" target="_blank" rel="noopener noreferrer">{{ part.text }}</a><template v-else>{{ part.text }}</template></template></span>
<small v-if="view?.unsent.includes(line.id)">待发送</small>
<small v-else-if="line.own && line.read && !line.recalled">已读</small>
<small v-if="line.edited && !line.recalled">已编辑</small>
<div class="message-actions">
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy || Boolean(editing)" @click="reply = line">引用</button>
@@ -319,8 +414,9 @@ onBeforeUnmount(() => clearInterval(timer))
</form>
</template>
</template>
<p v-else>在联系人详情打开聊天。</p>
<p v-else>选择一个联系人开始聊天。</p>
</template>
</div>
</div>
</section>
</template>