/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { Toast, Pagination } from '@/components/ui'; import { toastConstants } from '../constants'; import React from 'react'; import i18next from 'i18next'; import { THINK_TAG_REGEX, MESSAGE_ROLES, } from '../constants/playground.constants'; import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile'; // 官方价折扣计算(纯函数):管理端与市场页共用 import { buildOfficialComparison, formatDiscountLabel } from './officialPrice'; import { clearUserData, getUserData, isSafePostLoginRedirect } from './data'; const HTMLToastContent = ({ htmlContent }) => { return
; }; export default HTMLToastContent; export function isAdmin() { let user = getUserData(); if (!user) return false; return user.role >= 10; } export function isRoot() { let user = getUserData(); if (!user) return false; return user.role >= 100; } // 优先级:localStorage(/api/status 已落地)> window.__WL_BRAND__(index.html 内联脚本写入, // 反映后端启动注入的系统配置)> 终极兜底 'Weelinking' / '/logo.svg'(完全未配置部署)。 // 关键场景:冷启动 + localStorage 还没被 /api/status 灌满的窗口期, // 登录页、注册页、密码重置页、顶栏、聊天头像 5 处都通过本函数读品牌; // 不接 window 这一层就会闪一下 'Weelinking' + 羽毛 logo,违背白牌。 // 字面串 'undefined' / 'null' 也视为空(来源:helpers/data.js 把 undefined 字段 setItem 时 // 会被 String() 转成字面串),否则 会变成破图。 const isBlankLS = (v) => !v || v === 'undefined' || v === 'null'; // localStorage 在 Safari 隐私模式 / 部分企业 IT 锁定下 getItem 会抛 SecurityError。 // 单独包一层防御,让调用方拿到 null 走后续 window/终极兜底,而不是直接掀掉组件。 function lsGet(key) { try { return localStorage.getItem(key); } catch { return null; } } export function getSystemName() { let system_name = lsGet('system_name'); if (isBlankLS(system_name)) { system_name = (typeof window !== 'undefined' && window.__WL_BRAND__ && window.__WL_BRAND__.name) || ''; } if (!system_name) return 'Weelinking'; return system_name; } export function getLogo() { let logo = lsGet('logo'); if (isBlankLS(logo)) { logo = (typeof window !== 'undefined' && window.__WL_BRAND__ && window.__WL_BRAND__.logo) || ''; } if (!logo) return '/logo.svg'; return logo; } export function getUserIdFromLocalStorage() { let user = getUserData(); if (!user) return -1; return user.id; } export { copyText as copy } from './clipboard'; // isMobile 函数已移除,请改用 useIsMobile Hook let showErrorOptions = { autoClose: toastConstants.ERROR_TIMEOUT }; let showSuccessOptions = { autoClose: toastConstants.SUCCESS_TIMEOUT }; let showInfoOptions = { autoClose: toastConstants.INFO_TIMEOUT }; let showNoticeOptions = { autoClose: false }; const isMobileScreen = window.matchMedia( `(max-width: ${MOBILE_BREAKPOINT - 1}px)`, ).matches; if (isMobileScreen) { showErrorOptions.position = 'top-center'; // showErrorOptions.transition = 'flip'; showSuccessOptions.position = 'top-center'; // showSuccessOptions.transition = 'flip'; showInfoOptions.position = 'top-center'; // showInfoOptions.transition = 'flip'; showNoticeOptions.position = 'top-center'; // showNoticeOptions.transition = 'flip'; } let redirectingToLogin = false; const reportedRequestErrors = new WeakSet(); export function redirectToExpiredLogin() { if (redirectingToLogin) return; redirectingToLogin = true; clearUserData(); const { pathname, search, hash } = window.location; const currentPath = `${pathname}${search}${hash}`; const redirect = isSafePostLoginRedirect(currentPath) ? `&redirect=${encodeURIComponent(currentPath)}` : ''; window.location.replace(`/org/login?expired=true${redirect}`); } export function showError(error, { redirectOnUnauthorized = true } = {}) { if ( error?.code === 'ERR_CANCELED' || error === 'canceled' || (redirectingToLogin && error === 'Request failed with status code 401') ) return; if (error?.isAxiosError || error?.name === 'AxiosError') { if (reportedRequestErrors.has(error)) return; reportedRequestErrors.add(error); const status = error.response?.status; if (status === 401 && redirectOnUnauthorized) { redirectToExpiredLogin(); return; } if (status === 405) { Toast.info({ key: 'http-error:405', content: i18next.t('本站仅作演示之用,无服务端!'), }); return; } let content; if (!error.response) { content = i18next.t('错误:网络请求失败,请检查网络连接'); } else if (status === 429) { content = i18next.t('错误:请求次数过多,请稍后再试!'); } else if (status === 500) { content = i18next.t('错误:服务器内部错误,请联系管理员!'); } else { content = i18next.t('错误:{{message}}', { message: error.response.data?.message || error.message, }); } Toast.error({ key: `http-error:${content}`, content }); return; } console.error(error); Toast.error( i18next.t('错误:{{message}}', { message: error?.message || error }), ); } export function showWarning(message) { Toast.warning(message); } export function showSuccess(message) { Toast.success(message); } export function showInfo(message) { Toast.info(message); } export function showNotice(message, isHTML = false) { if (isHTML) { Toast.info({ content: , duration: 0, }); } else { Toast.info(message); } } export function removeTrailingSlash(url) { if (!url) return ''; if (url.endsWith('/')) { return url.slice(0, -1); } else { return url; } } export function getTodayStartTimestamp() { var now = new Date(); now.setHours(0, 0, 0, 0); return Math.floor(now.getTime() / 1000); } export function timestamp2string(timestamp) { let date = new Date(timestamp * 1000); let year = date.getFullYear().toString(); let month = (date.getMonth() + 1).toString(); let day = date.getDate().toString(); let hour = date.getHours().toString(); let minute = date.getMinutes().toString(); let second = date.getSeconds().toString(); if (month.length === 1) { month = '0' + month; } if (day.length === 1) { day = '0' + day; } if (hour.length === 1) { hour = '0' + hour; } if (minute.length === 1) { minute = '0' + minute; } if (second.length === 1) { second = '0' + second; } return ( year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second ); } export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') { let date = new Date(timestamp * 1000); // let year = date.getFullYear().toString(); let month = (date.getMonth() + 1).toString(); let day = date.getDate().toString(); let hour = date.getHours().toString(); if (day === '24') { console.log('timestamp', timestamp); } if (month.length === 1) { month = '0' + month; } if (day.length === 1) { day = '0' + day; } if (hour.length === 1) { hour = '0' + hour; } let str = month + '-' + day; if (dataExportDefaultTime === 'hour') { str += ' ' + hour + ':00'; } else if (dataExportDefaultTime === 'week') { let nextWeek = new Date(timestamp * 1000 + 6 * 24 * 60 * 60 * 1000); let nextMonth = (nextWeek.getMonth() + 1).toString(); let nextDay = nextWeek.getDate().toString(); if (nextMonth.length === 1) { nextMonth = '0' + nextMonth; } if (nextDay.length === 1) { nextDay = '0' + nextDay; } str += ' - ' + nextMonth + '-' + nextDay; } return str; } export function downloadTextAsFile(text, filename) { let blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); let url = URL.createObjectURL(blob); let a = document.createElement('a'); a.href = url; a.download = filename; a.click(); } export const verifyJSON = (str) => { try { JSON.parse(str); } catch (e) { return false; } return true; }; /** * 比较两个对象的属性,找出有变化的属性,并返回包含变化属性信息的数组 * @param {Object} oldObject - 旧对象 * @param {Object} newObject - 新对象 * @return {Array} 包含变化属性信息的数组,每个元素是一个对象,包含 key, oldValue 和 newValue */ export function compareObjects(oldObject, newObject) { const changedProperties = []; // 比较两个对象的属性 for (const key in oldObject) { if (oldObject.hasOwnProperty(key) && newObject.hasOwnProperty(key)) { if (oldObject[key] !== newObject[key]) { changedProperties.push({ key: key, oldValue: oldObject[key], newValue: newObject[key], }); } } } return changedProperties; } // playground message // 生成唯一ID let messageId = 4; export const generateMessageId = () => `${messageId++}`; // 提取消息中的文本内容 export const getTextContent = (message) => { if (!message || !message.content) return ''; if (Array.isArray(message.content)) { const textContent = message.content.find((item) => item.type === 'text'); return textContent?.text || ''; } return typeof message.content === 'string' ? message.content : ''; }; // 处理 think 标签 export const processThinkTags = (content, reasoningContent = '') => { if (!content || !content.includes('')) { return { content, reasoningContent }; } const thoughts = []; const replyParts = []; let lastIndex = 0; let match; THINK_TAG_REGEX.lastIndex = 0; while ((match = THINK_TAG_REGEX.exec(content)) !== null) { replyParts.push(content.substring(lastIndex, match.index)); thoughts.push(match[1]); lastIndex = match.index + match[0].length; } replyParts.push(content.substring(lastIndex)); const processedContent = replyParts .join('') .replace(/<\/?think>/g, '') .trim(); const thoughtsStr = thoughts.join('\n\n---\n\n'); const processedReasoningContent = reasoningContent && thoughtsStr ? `${reasoningContent}\n\n---\n\n${thoughtsStr}` : reasoningContent || thoughtsStr; return { content: processedContent, reasoningContent: processedReasoningContent, }; }; // 处理未完成的 think 标签 export const processIncompleteThinkTags = (content, reasoningContent = '') => { if (!content) return { content: '', reasoningContent }; const lastOpenThinkIndex = content.lastIndexOf(''); if (lastOpenThinkIndex === -1) { return processThinkTags(content, reasoningContent); } const fragmentAfterLastOpen = content.substring(lastOpenThinkIndex); if (!fragmentAfterLastOpen.includes('')) { const unclosedThought = fragmentAfterLastOpen .substring(''.length) .trim(); const cleanContent = content.substring(0, lastOpenThinkIndex); const processedReasoningContent = unclosedThought ? reasoningContent ? `${reasoningContent}\n\n---\n\n${unclosedThought}` : unclosedThought : reasoningContent; return processThinkTags(cleanContent, processedReasoningContent); } return processThinkTags(content, reasoningContent); }; // 构建消息内容(包含图片) export const buildMessageContent = ( textContent, imageUrls = [], imageEnabled = false, uploadedFiles = [], ) => { if ( !textContent && (!imageUrls || imageUrls.length === 0) && uploadedFiles.length === 0 ) { return ''; } const validImageUrls = imageUrls.filter((url) => url && url.trim() !== ''); const hasMultiModal = (imageEnabled && validImageUrls.length > 0) || uploadedFiles.length > 0; if (hasMultiModal) { // OpenAI / Claude 等多模态接口对 {type:'text', text:''} 的空文本 part 容错不一致, // 部分会直接 400。仅在确有文本时才 push 文本 part;纯附件场景就是纯多媒体数组。 const parts = []; const trimmedText = (textContent || '').trim(); if (trimmedText !== '') { parts.push({ type: 'text', text: textContent }); } if (imageEnabled && validImageUrls.length > 0) { parts.push( ...validImageUrls.map((url) => ({ type: 'image_url', image_url: { url: url.trim() }, })), ); } for (const file of uploadedFiles) { if (file.type === 'image') { parts.push({ type: 'image_url', image_url: { url: file.url }, }); } else { parts.push({ type: 'file', file: { filename: file.name, file_name: file.name, file_data: file.url, }, }); } } return parts; } return textContent || ''; }; // 把毫秒时间戳格式化为"几分钟前"风格的相对时间,超过 7 天回落到日期。 // 用于消息时间戳:避免一连串绝对时间堆在长会话里挤眼,hover 时再看具体时刻就够了。 export const formatRelativeTime = (msTimestamp, t) => { if (!msTimestamp) return ''; const now = Date.now(); const diff = now - msTimestamp; if (diff < 0) return t('刚刚'); const sec = Math.floor(diff / 1000); if (sec < 30) return t('刚刚'); if (sec < 60) return t('{{n}} 秒前', { n: sec }); const min = Math.floor(sec / 60); if (min < 60) return t('{{n}} 分钟前', { n: min }); const hour = Math.floor(min / 60); if (hour < 24) return t('{{n}} 小时前', { n: hour }); const day = Math.floor(hour / 24); if (day < 7) return t('{{n}} 天前', { n: day }); // 超过一周直接显示绝对日期,避免"30天前"这种含糊 const d = new Date(msTimestamp); const pad = (n) => ('0' + n).slice(-2); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }; // 把字节数格式化为人类可读字符串:"1.2 MB", "456 KB", "789 B" // decimals 默认 1 位小数,足够表达体验中心场景;0 字节直接返回 '0 B' export const formatBytes = (bytes, decimals = 1) => { const num = Number(bytes); if (!Number.isFinite(num) || num <= 0) return '0 B'; const k = 1024; const units = ['B', 'KB', 'MB', 'GB', 'TB']; const i = Math.min(units.length - 1, Math.floor(Math.log(num) / Math.log(k))); const value = num / Math.pow(k, i); // 小于 1KB 时不带小数;KB 及以上保留指定位数 const fixed = i === 0 ? Math.round(value).toString() : value.toFixed(decimals); return `${parseFloat(fixed)} ${units[i]}`; }; // 创建新消息 export const createMessage = (role, content, options = {}) => ({ role, content, createAt: Date.now(), id: generateMessageId(), ...options, }); // 创建加载中的助手消息。options 透传扩展字段,常用于: // - inWebSearch: 用户开了联网搜索,加载态显示"正在联网搜索…"提示,与单纯 spinner 区分 // - processingAttachments: 本轮 user 消息附带 N 个文件 → 后端要先 inline base64 // 再发上游,期间客户端没有任何流,loading 显示"正在处理 N 个附件…"明确告诉用户 // 系统在做事,不要急着重发 export const createLoadingAssistantMessage = (options = {}) => createMessage(MESSAGE_ROLES.ASSISTANT, '', { reasoningContent: '', isReasoningExpanded: true, isThinkingComplete: false, hasAutoCollapsed: false, status: 'loading', ...options, }); // 格式化消息用于API请求 export const formatMessageForAPI = (message) => { if (!message) return null; return { role: message.role, content: message.content, }; }; // 历史消息中的文件/图片附件,从「最后一条 user 消息」之外的所有消息里剥离, // 避免每轮把同一份附件重复送给上游模型 — 既省 token,又规避 COS 私有桶预签名 URL 过期。 // 剥离后在文本里追加短占位符(如 [已发送附件: a.pdf, b.png]),让模型知道历史上有过附件, // 避免它回复"你没给我文件"。本函数是纯函数,绝不修改入参,让上层 React.memo 安全工作。 export const stripHistoryAttachments = (messages) => { if (!Array.isArray(messages) || messages.length === 0) return messages; // 倒序找最后一条 user 消息下标 —— 这条要保留完整附件给本轮上游 let lastUserIdx = -1; for (let i = messages.length - 1; i >= 0; i--) { if (messages[i]?.role === MESSAGE_ROLES.USER) { lastUserIdx = i; break; } } if (lastUserIdx < 0) return messages; // 没 user 消息(不太可能),不动 // 从 image_url 或 file part 里提取一个可读的展示名 // image_url 通常只是 URL(UUID 命名 + 长签名串),原始文件名拿不到,统一显示为"图片" // 避免占位符里出现一长串无意义 UUID 浪费 token + 误导模型 const partDisplayName = (p) => { if (p?.type === 'file') { return p.file?.filename || p.file?.file_name || i18next.t('文件'); } if (p?.type === 'image_url') { return i18next.t('图片'); } return ''; }; // 若附件超过 5 个,列前 5 个加「等 N 个」省略 — 防止占位符本身爆 token。 // 同名附件合并为 "name×N":image_url 全显示为"图片"会出现 "图片, 图片, 图片" // 的丑陋重复 + 浪费 token;合并后变 "图片×3",更紧凑且让模型知道总张数。 const buildPlaceholder = (names) => { if (names.length === 0) return ''; const counts = new Map(); const order = []; for (const n of names) { if (!counts.has(n)) order.push(n); counts.set(n, (counts.get(n) || 0) + 1); } const grouped = order.map((n) => counts.get(n) > 1 ? `${n}×${counts.get(n)}` : n, ); if (grouped.length <= 5) { return `\n\n${i18next.t('[已发送附件: {{names}}]', { names: grouped.join(', '), })}`; } return `\n\n${i18next.t('[已发送附件: {{names}} 等 {{total}} 个]', { names: grouped.slice(0, 5).join(', '), total: names.length, })}`; }; // 白名单识别"要剥离的附件 part",其余 part(text / 未来可能的 audio / video 等)一律保留, // 避免静默丢失未知类型 part —— 即使当前体验中心只用 text/file/image_url,也对得起函数语义。 const isAttachmentPart = (p) => p?.type === 'file' || p?.type === 'image_url'; let mutated = false; const next = messages.map((m, idx) => { if (idx === lastUserIdx) return m; if (!m || !Array.isArray(m.content)) return m; const attachmentNames = []; const remaining = []; for (const part of m.content) { if (isAttachmentPart(part)) { attachmentNames.push(partDisplayName(part)); } else { remaining.push(part); } } if (attachmentNames.length === 0) return m; // 这条没附件,不动 mutated = true; const placeholder = buildPlaceholder(attachmentNames); // 剩余全是 text part(最常见场景)→ 合并成 string,更广兼容性 const allText = remaining.every((p) => p?.type === 'text'); if (allText) { const text = remaining .map((p) => (typeof p?.text === 'string' ? p.text : '')) .filter(Boolean) .join('\n'); return { ...m, content: (text + placeholder).trim() }; } // 还有非文本 part(理论可能,如 audio)→ 保持 array,把占位符塞进第一个 text part; // 没有 text part 就在最前面 unshift 一个,保证模型一定能读到附件信息 const newContent = remaining.slice(); const firstTextIdx = newContent.findIndex((p) => p?.type === 'text'); if (firstTextIdx >= 0) { newContent[firstTextIdx] = { ...newContent[firstTextIdx], text: (newContent[firstTextIdx].text || '') + placeholder, }; } else { newContent.unshift({ type: 'text', text: placeholder.trim() }); } return { ...m, content: newContent }; }); return mutated ? next : messages; }; // 验证消息是否有效 export const isValidMessage = (message) => { return message && message.role && (message.content || message.content === ''); }; // 计算相对时间(几天前、几小时前等) export const getRelativeTime = (publishDate) => { if (!publishDate) return ''; const now = new Date(); const pubDate = new Date(publishDate); // 如果日期无效,返回原始字符串 if (isNaN(pubDate.getTime())) return publishDate; const diffMs = now.getTime() - pubDate.getTime(); const diffSeconds = Math.floor(diffMs / 1000); const diffMinutes = Math.floor(diffSeconds / 60); const diffHours = Math.floor(diffMinutes / 60); const diffDays = Math.floor(diffHours / 24); const diffWeeks = Math.floor(diffDays / 7); const diffMonths = Math.floor(diffDays / 30); const diffYears = Math.floor(diffDays / 365); // 如果是未来时间,显示具体日期 if (diffMs < 0) { return formatDateString(pubDate); } // 根据时间差返回相应的描述 if (diffSeconds < 60) { return i18next.t('刚刚'); } else if (diffMinutes < 60) { return i18next.t('{{n}} 分钟前', { n: diffMinutes }); } else if (diffHours < 24) { return i18next.t('{{n}} 小时前', { n: diffHours }); } else if (diffDays < 7) { return i18next.t('{{n}} 天前', { n: diffDays }); } else if (diffWeeks < 4) { return i18next.t('{{n}} 周前', { n: diffWeeks }); } else if (diffMonths < 12) { return i18next.t('{{n}} 个月前', { n: diffMonths }); } else if (diffYears < 2) { return i18next.t('{{n}} 年前', { n: 1 }); } else { // 超过2年显示具体日期 return formatDateString(pubDate); } }; // 格式化日期字符串 export const formatDateString = (date) => { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; }; // 格式化日期时间字符串(包含时间) export const formatDateTimeString = (date) => { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}`; }; export { getTableCompactMode, setTableCompactMode, } from './tableCompactMode.js'; // ------------------------------- // Select 组件统一过滤逻辑 // 使用方式: