useConversations.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. "use client";
  2. import { useCallback, useEffect, useMemo, useRef, useState } from "react";
  3. import {
  4. fetchConversations,
  5. searchConversations,
  6. } from "../../agent/services/conversationApi";
  7. import type { ConversationListType } from "../../agent/services/conversationApi";
  8. import type { ConversationStatus } from "../../agent/services/conversationApi";
  9. import {
  10. ConversationSummary,
  11. MessageItem,
  12. VisitorStatusUpdatePayload,
  13. } from "../../agent/types";
  14. import { useWebSocket } from "./useWebSocket";
  15. import { WSMessage } from "@/lib/websocket";
  16. import { ChatWebSocketPayload } from "../../agent/types";
  17. import { buildMessagePreview } from "@/utils/format";
  18. import { getAgentWSToken } from "@/utils/storage";
  19. const sortByUpdatedAtDesc = (list: ConversationSummary[]) =>
  20. [...list].sort(
  21. (a, b) =>
  22. new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
  23. );
  24. import type { ConversationFilter } from "@/components/dashboard/ConversationHeader";
  25. const PAGE_SIZE = 50;
  26. const POLL_INTERVAL_MS = 15000;
  27. interface UseConversationsOptions {
  28. agentId?: number | null;
  29. filter?: ConversationFilter;
  30. /** 内部对话(知识库测试)时传 "internal",默认访客对话 "visitor" */
  31. listType?: ConversationListType;
  32. /** 会话状态:open(进行中)/ closed(历史) */
  33. status?: ConversationStatus;
  34. /** 为 false 时不加载列表、不轮询(非会话页使用) */
  35. enabled?: boolean;
  36. /** 轮询间隔毫秒;0 表示不轮询 */
  37. pollIntervalMs?: number;
  38. }
  39. export function useConversations(options?: UseConversationsOptions) {
  40. const {
  41. agentId,
  42. filter = "all",
  43. listType = "visitor",
  44. status = "open",
  45. enabled = true,
  46. pollIntervalMs = POLL_INTERVAL_MS,
  47. } = options || {};
  48. const [conversations, setConversations] = useState<ConversationSummary[]>([]);
  49. const [filteredConversations, setFilteredConversations] = useState<
  50. ConversationSummary[]
  51. >([]);
  52. const [selectedConversationId, setSelectedConversationId] = useState<
  53. number | null
  54. >(null);
  55. const [searchQuery, setSearchQuery] = useState("");
  56. const [loading, setLoading] = useState(enabled);
  57. const [loadingMore, setLoadingMore] = useState(false);
  58. const [isInitialLoad, setIsInitialLoad] = useState(enabled);
  59. const [hasMore, setHasMore] = useState(false);
  60. const [totalUnread, setTotalUnread] = useState(0);
  61. const pageRef = useRef(1);
  62. const prevListTypeRef = useRef(listType);
  63. const searchRef = useRef("");
  64. const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  65. const wsToken = getAgentWSToken() ?? undefined;
  66. const applyFilter = useCallback(
  67. (list: ConversationSummary[]): ConversationSummary[] => {
  68. if (!agentId) {
  69. return list;
  70. }
  71. switch (filter) {
  72. case "mine":
  73. return list.filter((conv) => conv.has_participated === true);
  74. case "others":
  75. return list.filter((conv) => conv.has_participated !== true);
  76. case "all":
  77. default:
  78. return list;
  79. }
  80. },
  81. [agentId, filter]
  82. );
  83. const mergeConversationPages = useCallback(
  84. (
  85. prev: ConversationSummary[],
  86. nextItems: ConversationSummary[],
  87. replace: boolean
  88. ) => {
  89. if (replace) {
  90. return nextItems;
  91. }
  92. const map = new Map<number, ConversationSummary>();
  93. for (const item of prev) {
  94. map.set(item.id, item);
  95. }
  96. for (const item of nextItems) {
  97. map.set(item.id, item);
  98. }
  99. return sortByUpdatedAtDesc(Array.from(map.values()));
  100. },
  101. []
  102. );
  103. const loadConversations = useCallback(
  104. async (opts?: { append?: boolean }) => {
  105. if (!enabled) {
  106. return;
  107. }
  108. const append = opts?.append ?? false;
  109. if (append) {
  110. setLoadingMore(true);
  111. } else {
  112. setLoading(true);
  113. pageRef.current = 1;
  114. }
  115. try {
  116. if (listType === "internal" && !agentId) {
  117. setConversations([]);
  118. setFilteredConversations([]);
  119. setSelectedConversationId(null);
  120. setHasMore(false);
  121. setTotalUnread(0);
  122. return;
  123. }
  124. const page = append ? pageRef.current + 1 : 1;
  125. const result = await fetchConversations(
  126. agentId ?? undefined,
  127. listType === "internal"
  128. ? { type: "internal", status, page, page_size: PAGE_SIZE }
  129. : { status, page, page_size: PAGE_SIZE }
  130. );
  131. pageRef.current = page;
  132. setHasMore(result.has_more);
  133. setTotalUnread(result.total_unread);
  134. setConversations((prev) => {
  135. const merged = mergeConversationPages(prev, result.items, !append);
  136. if (!searchRef.current.trim()) {
  137. const filtered =
  138. listType === "internal" ? merged : applyFilter(merged);
  139. const sorted = sortByUpdatedAtDesc(filtered);
  140. setFilteredConversations(sorted);
  141. if (!append) {
  142. setSelectedConversationId((prevSelected) => {
  143. if (prevSelected && sorted.some((c) => c.id === prevSelected)) {
  144. return prevSelected;
  145. }
  146. return sorted.length > 0 ? sorted[0].id : null;
  147. });
  148. }
  149. }
  150. return merged;
  151. });
  152. } catch (error) {
  153. console.error(error);
  154. } finally {
  155. if (append) {
  156. setLoadingMore(false);
  157. } else {
  158. setLoading(false);
  159. setIsInitialLoad(false);
  160. }
  161. }
  162. },
  163. [enabled, applyFilter, agentId, listType, status, mergeConversationPages]
  164. );
  165. const loadMoreConversations = useCallback(async () => {
  166. if (!enabled || loading || loadingMore || !hasMore || searchRef.current.trim()) {
  167. return;
  168. }
  169. await loadConversations({ append: true });
  170. }, [enabled, loading, loadingMore, hasMore, loadConversations]);
  171. useEffect(() => {
  172. if (!enabled) {
  173. setLoading(false);
  174. setIsInitialLoad(false);
  175. return;
  176. }
  177. void loadConversations();
  178. }, [enabled, loadConversations]);
  179. // 切换 listType(访客对话 ↔ 知识库测试)时立即清空,避免串台
  180. useEffect(() => {
  181. if (prevListTypeRef.current !== listType) {
  182. prevListTypeRef.current = listType;
  183. setConversations([]);
  184. setFilteredConversations([]);
  185. setSelectedConversationId(null);
  186. setHasMore(false);
  187. setTotalUnread(0);
  188. pageRef.current = 1;
  189. searchRef.current = "";
  190. setSearchQuery("");
  191. }
  192. }, [listType]);
  193. useEffect(() => {
  194. if (!enabled || !agentId || pollIntervalMs <= 0) {
  195. return;
  196. }
  197. const interval = setInterval(() => {
  198. void loadConversations();
  199. }, pollIntervalMs);
  200. return () => clearInterval(interval);
  201. }, [enabled, agentId, pollIntervalMs, loadConversations]);
  202. useEffect(() => {
  203. if (isInitialLoad) {
  204. return;
  205. }
  206. const filtered = listType === "internal" ? conversations : applyFilter(conversations);
  207. setFilteredConversations(sortByUpdatedAtDesc(filtered));
  208. }, [filter, listType, conversations, isInitialLoad, applyFilter]);
  209. useEffect(() => {
  210. if (!enabled || isInitialLoad) {
  211. return;
  212. }
  213. const handler = setTimeout(async () => {
  214. const query = searchQuery.trim();
  215. searchRef.current = query;
  216. if (!query) {
  217. const filtered = listType === "internal" ? conversations : applyFilter(conversations);
  218. setFilteredConversations(sortByUpdatedAtDesc(filtered));
  219. return;
  220. }
  221. if (listType === "internal") {
  222. setFilteredConversations(
  223. sortByUpdatedAtDesc(
  224. conversations.filter((c) =>
  225. (c.last_message?.content ?? "").toLowerCase().includes(query.toLowerCase())
  226. )
  227. )
  228. );
  229. setLoading(false);
  230. return;
  231. }
  232. try {
  233. setLoading(true);
  234. const data = await searchConversations(query, agentId ?? undefined, {
  235. status,
  236. type: listType,
  237. });
  238. const filtered = applyFilter(data);
  239. setFilteredConversations(sortByUpdatedAtDesc(filtered));
  240. } catch (error) {
  241. console.error(error);
  242. setFilteredConversations([]);
  243. } finally {
  244. setLoading(false);
  245. }
  246. }, 300);
  247. return () => clearTimeout(handler);
  248. }, [enabled, searchQuery, conversations, isInitialLoad, applyFilter, agentId, listType, status]);
  249. const selectConversation = useCallback((conversationId: number | null) => {
  250. setSelectedConversationId((prev) =>
  251. prev === conversationId ? prev : conversationId
  252. );
  253. }, []);
  254. const updateConversation = useCallback(
  255. (
  256. conversationId: number,
  257. updater: (conversation: ConversationSummary) => ConversationSummary,
  258. options?: { skipResort?: boolean }
  259. ) => {
  260. const applyUpdate = (list: ConversationSummary[]) => {
  261. let changed = false;
  262. const next = list.map((conv) => {
  263. if (conv.id === conversationId) {
  264. changed = true;
  265. return updater(conv);
  266. }
  267. return conv;
  268. });
  269. if (!changed) {
  270. return list;
  271. }
  272. if (options?.skipResort) {
  273. return next;
  274. }
  275. return sortByUpdatedAtDesc(next);
  276. };
  277. setConversations((prev) => applyUpdate(prev));
  278. setFilteredConversations((prev) => {
  279. if (searchRef.current && !prev.some((item) => item.id === conversationId)) {
  280. return prev;
  281. }
  282. return applyUpdate(prev);
  283. });
  284. },
  285. []
  286. );
  287. const setAllConversations = useCallback(
  288. (data: ConversationSummary[]) => {
  289. setConversations(data);
  290. if (!searchRef.current.trim()) {
  291. const filtered = applyFilter(data);
  292. setFilteredConversations(filtered);
  293. }
  294. },
  295. [applyFilter]
  296. );
  297. const hasConversation = useCallback(
  298. (conversationId: number) => {
  299. return conversations.some((conv) => conv.id === conversationId);
  300. },
  301. [conversations]
  302. );
  303. const scheduleRefreshConversations = useCallback(() => {
  304. if (!enabled) {
  305. return;
  306. }
  307. if (refreshTimerRef.current) {
  308. clearTimeout(refreshTimerRef.current);
  309. }
  310. refreshTimerRef.current = setTimeout(() => {
  311. void loadConversations();
  312. }, 500);
  313. }, [enabled, loadConversations]);
  314. const globalConversationId = conversations.length > 0 ? conversations[0].id : null;
  315. const handleGlobalWebSocketMessage = useCallback(
  316. (event: WSMessage<ChatWebSocketPayload>) => {
  317. if (event.type === "visitor_status_update" && event.data) {
  318. const payload = event.data as VisitorStatusUpdatePayload;
  319. if (payload?.conversation_id && payload.is_online === true) {
  320. updateConversation(payload.conversation_id, (conv) => ({
  321. ...conv,
  322. last_seen_at: new Date().toISOString(),
  323. }));
  324. }
  325. } else if (event.type === "new_message" && event.data) {
  326. const message = event.data as MessageItem;
  327. if (typeof message?.conversation_id !== "number") {
  328. return;
  329. }
  330. const isConversationExists = hasConversation(message.conversation_id);
  331. if (!isConversationExists) {
  332. scheduleRefreshConversations();
  333. return;
  334. }
  335. const isSystemMessage =
  336. (message.message_type ?? "user_message") === "system_message";
  337. const isVisitorMessage = !message.sender_is_agent && !isSystemMessage;
  338. const preview = buildMessagePreview(message.content ?? "");
  339. updateConversation(message.conversation_id, (conv) => ({
  340. ...conv,
  341. updated_at: message.created_at,
  342. last_seen_at: isVisitorMessage
  343. ? message.created_at
  344. : conv.last_seen_at ?? null,
  345. unread_count: isVisitorMessage
  346. ? message.conversation_id === selectedConversationId
  347. ? 0
  348. : (conv.unread_count ?? 0) + 1
  349. : conv.unread_count ?? 0,
  350. last_message: {
  351. id: message.id,
  352. content: preview,
  353. sender_is_agent: message.sender_is_agent,
  354. message_type: message.message_type ?? "user_message",
  355. is_read: Boolean(message.is_read),
  356. read_at: message.read_at ?? null,
  357. created_at: message.created_at,
  358. },
  359. }));
  360. if (isVisitorMessage && message.conversation_id !== selectedConversationId) {
  361. setTotalUnread((n) => n + 1);
  362. }
  363. }
  364. },
  365. [
  366. hasConversation,
  367. scheduleRefreshConversations,
  368. selectedConversationId,
  369. updateConversation,
  370. ]
  371. );
  372. useEffect(() => {
  373. return () => {
  374. if (refreshTimerRef.current) {
  375. clearTimeout(refreshTimerRef.current);
  376. }
  377. };
  378. }, []);
  379. useWebSocket<ChatWebSocketPayload>({
  380. conversationId: globalConversationId,
  381. enabled: Boolean(enabled && globalConversationId && agentId),
  382. isVisitor: false,
  383. agentId: agentId ?? undefined,
  384. wsToken,
  385. onMessage: handleGlobalWebSocketMessage,
  386. onError: () => {},
  387. onClose: () => {},
  388. });
  389. return useMemo(
  390. () => ({
  391. conversations,
  392. filteredConversations,
  393. selectedConversationId,
  394. searchQuery,
  395. loading,
  396. loadingMore,
  397. isInitialLoad,
  398. hasMore,
  399. totalUnread,
  400. setSearchQuery,
  401. selectConversation,
  402. refresh: () => loadConversations(),
  403. loadMore: loadMoreConversations,
  404. updateConversation,
  405. setAllConversations,
  406. hasConversation,
  407. }),
  408. [
  409. conversations,
  410. filteredConversations,
  411. selectedConversationId,
  412. searchQuery,
  413. loading,
  414. loadingMore,
  415. isInitialLoad,
  416. hasMore,
  417. totalUnread,
  418. selectConversation,
  419. loadConversations,
  420. loadMoreConversations,
  421. updateConversation,
  422. setAllConversations,
  423. hasConversation,
  424. ]
  425. );
  426. }