合并 main:同步聊天、风控诊断与迁移基线
This commit is contained in:
commit
a6c0d36ee9
89 files changed
+2974
-365
No files matched your search
@@ -7,6 +7,7 @@ import {
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../../../shared/api-contract';
|
||||
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 聊天账号选择器读取非敏感账号摘要。 */
|
||||
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
|
||||
@@ -68,6 +69,6 @@ export const sendChatImage = async (input: {
|
||||
return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options });
|
||||
};
|
||||
|
||||
// markChatRead 标记聊天消息已读。
|
||||
export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options);
|
||||
/** 向平台确认指定会话中的入站消息已读。 */
|
||||
export const markChatRead = async (accountId: string, chatId: string, messageIDs: ChatReadReceipt[], options?: RequestControlOptions): Promise<OperationResponse> =>
|
||||
post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIDs }, options);
|
||||
@@ -99,7 +99,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
expect(hook.result.current.accounts[0]).toMatchObject(accountFixture);
|
||||
expect(hook.result.current.activeChatID).toBe('chat-1');
|
||||
expect(hook.result.current.messages).toEqual([messageFixture]);
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', [
|
||||
{ messageId: 'message-1', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 },
|
||||
], expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.unreadForAccount('account-1')).toBe(0);
|
||||
await act(
|
||||
// emptySendAction 在没有草稿时阻止文字发送。
|
||||
@@ -191,6 +193,31 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('会话刷新不会让当前打开会话重新显示未读', /* 当前回调验证已读状态与慢刷新响应的竞态边界。 */ async () => {
|
||||
// hook 是当前会话已读后执行刷新的 Hook 渲染结果。
|
||||
const hook = renderHook(
|
||||
// refreshHookFactory 创建会话刷新竞态场景。
|
||||
() => useChat(),
|
||||
);
|
||||
await waitFor(
|
||||
// activeChatAssertion 等待默认会话完成消息读取。
|
||||
() => expect(hook.result.current.activeChatID).toBe('chat-1'),
|
||||
);
|
||||
await waitFor(
|
||||
// readAssertion 等待初始消息读取将本地未读数归零。
|
||||
() => expect(hook.result.current.unreadForAccount('account-1')).toBe(0),
|
||||
);
|
||||
// staleSessionPage 模拟服务端延迟返回的旧未读计数。
|
||||
const staleSessionPage = { ...sessionFixture, unread_count: 4 };
|
||||
getSessionPageMock.mockResolvedValueOnce({ sessions: [staleSessionPage], has_more: false });
|
||||
await act(
|
||||
// refreshAction 执行返回旧未读数据的会话刷新。
|
||||
async () => hook.result.current.reloadSessions('account-1'),
|
||||
);
|
||||
expect(hook.result.current.unreadForAccount('account-1')).toBe(0);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('WebSocket 连接和消息事件更新聊天状态', /* 当前回调验证实时连接和消息回调边界。 */ async () => {
|
||||
// secondSession 是用于覆盖实时会话排序比较器的第二条会话。
|
||||
const secondSession = { ...sessionFixture, chat_id: 'chat-2', last_message_at: 2, unread_count: 0 };
|
||||
@@ -221,7 +248,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
|
||||
() => latestSocket?.onmessage?.({ data: JSON.stringify({ message: incomingMessage }) }),
|
||||
);
|
||||
expect(hook.result.current.messages).toContainEqual(incomingMessage);
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1');
|
||||
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', [
|
||||
{ messageId: 'message-3', sessionId: 'chat-1', cid: 'chat-1@goofish', conversationType: 1 },
|
||||
]);
|
||||
await act(
|
||||
// invalidMessageAction 触发非法消息帧并保持状态稳定。
|
||||
() => latestSocket?.onmessage?.({ data: '{broken' }),
|
||||
|
||||
@@ -3,7 +3,7 @@ import type React from 'react';
|
||||
import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis';
|
||||
import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api';
|
||||
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import type { ChatFeatureState, ChatLiveState, SessionsByAccount } from './types';
|
||||
|
||||
/** Chat Hook 对外暴露的状态、引用和交互动作。 */
|
||||
@@ -156,10 +156,16 @@ export const useChat = (): UseChatResult => {
|
||||
// page 页码。
|
||||
const page = await getChatSessionPage(accountID, undefined, { signal: controller.signal }, true);
|
||||
if (!isCurrentChatRequest(sessionSequence.current, sequence, controller.signal)) return [];
|
||||
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.sessions }));
|
||||
// sessions 保留当前打开会话的本地已读状态,避免刷新响应迟到后重新展示未读徽标。
|
||||
const sessions = page.sessions.map(/* session 按当前活跃会话覆写已读计数。 */ session => (
|
||||
accountID === activeAccountRef.current && session.chat_id === activeChatRef.current
|
||||
? { ...session, unread_count: 0 }
|
||||
: session
|
||||
));
|
||||
setSessionsByAccount(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: sessions }));
|
||||
setContactCursors(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.next_cursor }));
|
||||
setHasMoreContacts(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, [accountID]: page.has_more }));
|
||||
return page.sessions;
|
||||
return sessions;
|
||||
} catch (/* error 表示错误。 */ error) {
|
||||
if (isCurrentChatRequest(sessionSequence.current, sequence, controller.signal) && !isChatAbortError(error)) setError(error instanceof Error ? error.message : '同步会话失败');
|
||||
return [];
|
||||
@@ -271,11 +277,11 @@ export const useChat = (): UseChatResult => {
|
||||
const controller = new AbortController();
|
||||
messageController.current = controller;
|
||||
setMessagesLoading(true);
|
||||
void Promise.all([
|
||||
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
|
||||
markChatRead(activeAccountID, activeChatID, { signal: controller.signal }),
|
||||
]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([page]) => {
|
||||
void getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }).then(/* 当前回调处理用户交互或异步状态变化。 */ page => {
|
||||
if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return;
|
||||
// readReceipts 只确认可被平台接受的普通入站消息。
|
||||
const readReceipts = collectChatReadReceipts(page.messages, activeChatID);
|
||||
void markChatRead(activeAccountID, activeChatID, readReceipts, { signal: controller.signal });
|
||||
setMessages(page.messages);
|
||||
setHasOlder(page.has_more);
|
||||
setHistoryCursor(page.next_cursor);
|
||||
@@ -394,12 +400,16 @@ export const useChat = (): UseChatResult => {
|
||||
...row,
|
||||
last_message: message.content,
|
||||
last_message_at: message.sent_at,
|
||||
unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
|
||||
unread_count: message.direction === 'incoming' && message.message_type !== 'system' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count,
|
||||
} : row).sort(/* 当前回调处理集合中的单个元素。 */ (a, b) => b.last_message_at - a.last_message_at) };
|
||||
});
|
||||
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
|
||||
setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeLiveMessage(current, message));
|
||||
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
|
||||
if (message.direction === 'incoming' && message.message_type !== 'system') {
|
||||
// readReceipts 为当前实时消息生成平台要求的会话读取回执。
|
||||
const readReceipts = collectChatReadReceipts([message], message.chat_id);
|
||||
void markChatRead(accountID, message.chat_id, readReceipts);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略非聊天格式的 WebSocket 帧,后续 REST 查询会恢复权威状态。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
import { collectChatReadReceipts, filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state';
|
||||
|
||||
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
|
||||
const sessionFixture: ChatSession[] = [
|
||||
@@ -11,6 +11,21 @@ const sessionFixture: ChatSession[] = [
|
||||
// messageFixture 是覆盖消息去重和实时替换的最小消息数据。
|
||||
const messageFixture: ChatMessage = { id: 1, account_id: 'a1', chat_id: 'c1', message_key: 'm1', direction: 'incoming', sender_id: 'b1', sender_name: '张三', message_type: 'text', content: '旧消息', status: 'received', sent_at: 1 };
|
||||
|
||||
test('Chat 已读回执排除系统消息和平台内部消息',
|
||||
// 已读回执测试确保接口仅接收可确认的普通入站消息。
|
||||
() => {
|
||||
// messages 覆盖普通消息、系统通知、内部标记及出站消息。
|
||||
const messages: ChatMessage[] = [
|
||||
messageFixture,
|
||||
{ ...messageFixture, id: 2, message_key: 'in-local', message_type: 'text' },
|
||||
{ ...messageFixture, id: 3, message_key: 'system-1', message_type: 'system' },
|
||||
{ ...messageFixture, id: 4, message_key: 'outgoing-1', direction: 'outgoing' },
|
||||
];
|
||||
expect(collectChatReadReceipts(messages, 'c1')).toEqual([
|
||||
{ messageId: 'm1', sessionId: 'c1', cid: 'c1@goofish', conversationType: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('Chat 会话筛选和历史消息合并保持账号内顺序',
|
||||
// 会话状态测试验证搜索、未读筛选和历史消息去重语义。
|
||||
() => {
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
import type { ChatMessage, ChatSession } from '../../../shared/api-contract';
|
||||
import type { ChatReadReceipt } from './types';
|
||||
|
||||
/** 将可确认的普通入站消息转换为平台已读回执。 */
|
||||
export const collectChatReadReceipts = (messages: ChatMessage[], chatID: string): ChatReadReceipt[] => messages
|
||||
.filter(/* currentMessage 只保留平台可接受的普通入站消息。 */ currentMessage => (
|
||||
currentMessage.direction === 'incoming'
|
||||
&& currentMessage.message_type !== 'system'
|
||||
&& !currentMessage.message_key.startsWith('in-')
|
||||
))
|
||||
.map(/* currentMessage 为每条消息构造其所属会话的已读确认。 */ currentMessage => ({
|
||||
messageId: currentMessage.message_key,
|
||||
sessionId: chatID,
|
||||
cid: `${chatID}@goofish`,
|
||||
conversationType: 1,
|
||||
}));
|
||||
|
||||
/** 按搜索条件筛选会话列表。 */
|
||||
export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => {
|
||||
|
||||
@@ -6,6 +6,18 @@ export type SessionsByAccount = Record<string, ChatSession[]>;
|
||||
/** Chat 实时连接状态。 */
|
||||
export type ChatLiveState = 'connecting' | 'online' | 'offline';
|
||||
|
||||
/** 平台已读接口要求的单条消息回执。 */
|
||||
export interface ChatReadReceipt {
|
||||
/** 平台消息去重键。 */
|
||||
messageId: string;
|
||||
/** 所属平台会话标识。 */
|
||||
sessionId: string;
|
||||
/** 平台会话复合标识。 */
|
||||
cid: string;
|
||||
/** 平台定义的单聊会话类型。 */
|
||||
conversationType: number;
|
||||
}
|
||||
|
||||
/** Chat Hook 的状态与交互能力。 */
|
||||
export type ChatFeatureState = {
|
||||
/** 当前启用账号列表。 */
|
||||
|
||||
Reference in new issue
Block a user