重构 GlobalChatbox 组件,拆分为多个模块

This commit is contained in:
2026-04-03 14:07:27 +08:00
parent 56b4777dbd
commit d763876f86
5 changed files with 666 additions and 589 deletions
@@ -0,0 +1,54 @@
import type { PersistedChatState } from "./GlobalChatbox.types";
export const createId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
export const CHAT_STORAGE_KEY = "tjwater_copilot_chat_state_v1";
const THINK_TAG_ALIAS_PATTERN = /<\s*(\/?)\s*(thinking|reasoning|thought)\b[^>]*>/gi;
export const PRESET_PROMPTS = [
"帮我分析当前管网压力异常点,并按风险等级排序。",
"基于当前状态,给出今天的巡检优先级和建议路线。",
"帮我生成一份今日运行简报,包含问题、原因和建议。",
];
export const normalizeThoughtTagToken = (token: string): string =>
token.replace(THINK_TAG_ALIAS_PATTERN, (_, closingSlash: string) =>
closingSlash ? "</think>" : "<think>",
);
export const stripMarkdown = (md: string): string =>
md
.replace(/```[\s\S]*?```/g, "")
.replace(/`([^`]+)`/g, "$1")
.replace(/!\[.*?\]\(.*?\)/g, "")
.replace(/\[([^\]]+)\]\(.*?\)/g, "$1")
.replace(/#{1,6}\s+/g, "")
.replace(/\*\*\*(.+?)\*\*\*/g, "$1")
.replace(/\*\*(.+?)\*\*/g, "$1")
.replace(/\*(.+?)\*/g, "$1")
.replace(/~~(.+?)~~/g, "$1")
.replace(/>\s+/g, "")
.replace(/[-*+]\s+/g, "")
.replace(/\d+\.\s+/g, "")
.replace(/\n{2,}/g, "\n")
.replace(/<[^>]+>/g, "")
.trim();
export const getInitialChatState = (): PersistedChatState => {
if (typeof window === "undefined") {
return { messages: [], conversationId: undefined };
}
try {
const storedRaw = window.localStorage.getItem(CHAT_STORAGE_KEY);
if (!storedRaw) return { messages: [], conversationId: undefined };
const parsed = JSON.parse(storedRaw) as PersistedChatState;
if (!Array.isArray(parsed.messages)) {
console.error("[GlobalChatbox] Invalid persisted messages format.");
window.localStorage.removeItem(CHAT_STORAGE_KEY);
return { messages: [], conversationId: undefined };
}
return { messages: parsed.messages, conversationId: parsed.conversationId };
} catch (error) {
console.error("[GlobalChatbox] Failed to read persisted chat state:", error);
window.localStorage.removeItem(CHAT_STORAGE_KEY);
return { messages: [], conversationId: undefined };
}
};