| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722 |
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
- import { flushSync } from 'react-dom';
- import { useNavigate, useSearchParams, useLocation } from 'react-router-dom';
- import { useTranslation } from 'react-i18next';
- import { message as antMessage } from 'antd';
- import { v4 as uuidv4 } from 'uuid';
- import { useAppStore } from '@/store';
- import { AudioRecorder, type FrequencyFrame } from '@/utils/audioRecorder';
- import { AudioPlayer } from '@/utils/audioPlayer';
- import { WebSocketManager } from '@/utils/websocket';
- import { prepareMobileAudio, requestVolumeControl, isMobileDevice } from '@/utils/audioHelper';
- import {
- setStorage,
- getStorage,
- getUserLevel,
- getHasSharedAvatar,
- STORAGE_KEYS,
- markRouteVisited,
- getUserId,
- getVisitedRoutes,
- setUserLevel,
- getCurrentBackgroundImageUrl,
- getCurrentBackgroundImageId,
- getCurrentBackgroundImageOpacity,
- syncBackgroundImageToStorage,
- setUserName,
- getUserToken,
- setUserToken,
- clearUserSessionAndRedirectToBegin,
- ROUTE_ORDER,
- } from '@/utils/storage';
- import { onScreenResize, calculateLayout, type CalculatedLayout, updateTooSmallFlag } from '@/utils/screenSize';
- import { performanceLogger } from '@/utils/logger';
- import {
- getUserInfo,
- updateUserUIState,
- getUserUIState,
- getAvatarGifs,
- getIntimacy,
- lightUpIntimacy,
- getIntimacyStatus,
- type AvatarGifSet,
- ensureSession,
- getApiBaseUrl,
- getApiHeaders,
- } from '@/utils/api';
- import { px2vmin } from '@/utils/viewport';
- import type { Message, EnergyStoneSpawnMessage } from '@/types';
- import '@/styles/chatbot-fix.css';
- import { getOssUrl } from '@/utils/oss';
- const tapToChat = getOssUrl('TapToChat.svg');
- const cancelIcon = getOssUrl('cancel-icon.png');
- const sendIcon = getOssUrl('send-icon.png');
- const tooltipsCancel = getOssUrl('tooltips-cancel.svg');
- const tooltipsSend = getOssUrl('tooltips-send.svg');
- /** 是否展示聊天页的 4 个引导 tips(Tap to Chat / 取消 / 发送 / 进度条) */
- const ENABLE_CHATBOT_TIPS = false;
- const luyinDefault = getOssUrl('luyin-default.png');
- const luyinDisable = getOssUrl('luyin-disable.png');
- const settingIcon = getOssUrl('setting-icon.png');
- const funcLockIcon = getOssUrl('func-Lock.png');
- const profileMenuIcon = getOssUrl('profile-icon.png');
- const shopMenuIcon = getOssUrl('shop-icon.png');
- const worldMenuIcon = getOssUrl('world-icon.png');
- const diaryMenuIcon = getOssUrl('diary-icon.png');
- const ccCloseIcon = getOssUrl('cc-close-icon.png');
- const ccOpenIcon = getOssUrl('cc-open-icon.png');
- const missionEnergyStone = getOssUrl('Mission-Energy-Stone.png');
- const conversationEnergyStone = getOssUrl('Conversation-Energy-Stone.png');
- const missionEnergyStoneHint = getOssUrl('Mission-Energy-Stone-hint.png');
- const conversationEnergyStoneHint = getOssUrl('Conversation-Energy-Stone-hint.png');
- const heartFilled = getOssUrl('Heart.png');
- const heartBroken = getOssUrl('Heart_broken.png');
- const conversationEnergyStoneCountBg = getOssUrl('conversion-energy-stone-count.png');
- const YpImage = getOssUrl('yp.png');
- const audioWaveGif = getOssUrl('audio-wave.gif');
- const bgChattingUrl = getOssUrl('bg-chatting.png');
- import { useEnergyStones, type EnergyStoneEventPayload } from '@/hooks/useEnergyStones';
- import { MissionEnergyStoneModal } from '@/components/MissionEnergyStoneModal';
- import { IntimacyModal } from '@/components/IntimacyModal';
- const MAX_RECORDING_DURATION_MS = 60_000;
- const AVATAR_C_UNLOCK_THRESHOLD_MS = 60_000;
- const COUNTDOWN_THRESHOLD_MS = 10_000;
- const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws';
- // 控制台调试开关:生产环境关闭,避免多余日志
- const shouldLogDebug = false;
- const debugLog = (...args: unknown[]) => {
- if (!shouldLogDebug) return;
- // 使用 console.debug 统一输出调试日志
- // eslint-disable-next-line no-console
- console.debug(...args);
- };
- // GIF URL 兜底常量(基础形象)
- const FALLBACK_DEFAULT_AVATAR_GIF = getOssUrl('01-Default.gif');
- const FALLBACK_POSITIVE_EMOTION_GIF = getOssUrl('04-Positive-emotion.gif');
- const FALLBACK_NEGATIVE_EMOTION_GIF = getOssUrl('05-Negative-emotion.gif');
- const FALLBACK_TALKING_GIF = getOssUrl('06-talking.gif');
- // GIF URL 兜底常量(注册赠送形象:带帽子)
- const FALLBACK_REGISTERED_DEFAULT_AVATAR_GIF = getOssUrl('01-Default-Registered.gif');
- const FALLBACK_REGISTERED_POSITIVE_EMOTION_GIF = getOssUrl('04-Positive-emotion-Registered.gif');
- const FALLBACK_REGISTERED_NEGATIVE_EMOTION_GIF = getOssUrl('05-Negative-emotion-Registered.gif');
- const FALLBACK_REGISTERED_TALKING_GIF = getOssUrl('06-talking-Registered.gif');
- // 形象 ID 常量(与后端/迁移脚本一致)
- const AVATAR_ID_DEFAULT = 'avatar_default';
- const AVATAR_ID_REGISTERED = 'avatar_registered_cap';
- type AvatarState = 'default' | 'positive' | 'negative' | 'talking';
- // 情绪分类函数
- const getEmotionCategory = (emotion: string): 'positive' | 'negative' | 'neutral' => {
- // 正向情绪
- const positiveEmotions = ['happy', 'excited', 'encouraging', 'satisfied', 'friendly'];
- // 反向情绪
- const negativeEmotions = ['sad', 'angry', 'worried', 'confused', 'sorry'];
-
- if (positiveEmotions.includes(emotion)) {
- return 'positive';
- }
- if (negativeEmotions.includes(emotion)) {
- return 'negative';
- }
- // neutral, surprised, thoughtful 等归为中性
- return 'neutral';
- };
- // 获取情绪 GIF 播放时长(毫秒)
- // 统一:正向 2050ms,负向 4290ms(与形象无关)
- const getEmotionGifDuration = (_avatarId: string | null, emotionCategory: 'positive' | 'negative'): number => {
- if (emotionCategory === 'positive') {
- return 2050;
- }
- if (emotionCategory === 'negative') {
- return 4290;
- }
- return 0;
- };
- export const ChatBotPage = () => {
- const { t: tCommon } = useTranslation('common');
- const { t: tProfile } = useTranslation('profile');
- const navigate = useNavigate();
- const [searchParams] = useSearchParams();
- const location = useLocation();
- const {
- currentState,
- currentRequestId,
- conversationProgress,
- progressLoopCount,
- setState,
- setRequestId,
- setEmotion,
- setRecognizedText,
- setError,
- setConnected,
- setProgress,
- reset,
- isConnected,
- recognizedText,
- } = useAppStore();
- const recorderRef = useRef<AudioRecorder | null>(null);
- const playerRef = useRef<AudioPlayer | null>(null);
- const wsRef = useRef<WebSocketManager | null>(null);
- const chunkIndexRef = useRef(0);
- const connectionLostRef = useRef(false);
- // 首句 greeting 请求 ID(来自后端的 greeting_xxx)
- const greetingRequestIdRef = useRef<string | null>(null);
- // 标记首句是否处于“可播放/可显示”状态;一旦用户开始录音则置为 true,后续 greeting 全部丢弃
- const greetingSuppressedRef = useRef(false);
- // 标记当前是否正在播放首句音频,便于在开始录音时精确打断
- const isGreetingActiveRef = useRef(false);
- // 标记首句 greeting 是否已经发起,避免重复触发
- const hasGreetingStartedRef = useRef(false);
- // 标记在 WebSocket 尚未完成初始化时是否需要在连接成功后自动触发首句 greeting
- const pendingGreetingRef = useRef(false);
- const activeRequestIdRef = useRef<string | null>(null);
- const cancelledRequestIdsRef = useRef<Set<string>>(new Set());
- const mobileAudioPreparedRef = useRef(false);
- // 如果亲密度弹窗正在展示,则不播放首句 greeting(直接丢弃相关消息)
- const delayGreetingRef = useRef(false);
- // 字幕相关状态(默认从 localStorage 读取,若无则为 false)
- const [subtitleOn, setSubtitleOn] = useState(() => {
- return getStorage(STORAGE_KEYS.SUBTITLE_ON) === 'true';
- });
- const subtitleContainerRef = useRef<HTMLDivElement | null>(null);
- const [subtitleVisible, setSubtitleVisible] = useState(false);
- const subtitleOnRef = useRef(subtitleOn);
- // 字幕自动滚动相关:仅当字幕消失时停止,无其他取消逻辑
- const subtitleAutoScrollRafRef = useRef<number | null>(null);
- const subtitleLastFrameTimeRef = useRef<number | null>(null);
- const sendTimeRef = useRef<number>(0);
- const isMountedRef = useRef(true);
- const [, setUserLevelValue] = useState(() => getUserLevel());
- const [, setHasSharedAvatarState] = useState(() => getHasSharedAvatar());
- // 背景图片 URL
- const [backgroundImageUrl, setBackgroundImageUrl] = useState<string | null>(() => {
- // 初始化时从 localStorage 获取背景图片 URL
- const url = getCurrentBackgroundImageUrl();
- return url || null;
- });
- // 背景图片 ID(只保留 setter,因为变量本身未使用)
- const [, setBackgroundImageId] = useState<string | null>(() => {
- return getCurrentBackgroundImageId();
- });
- // 初始化时检查 localStorage,确保第一次打开时立即显示提示(由 ENABLE_CHATBOT_TIPS 控制是否展示)
- const [showTapToChat, setShowTapToChat] = useState(() => {
- if (!ENABLE_CHATBOT_TIPS) return false;
- const hasShown = getStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT);
- if (hasShown) return false;
- return true;
- });
- const sendingTimeoutRef = useRef<number | null>(null);
- const updateRequestId = useCallback(
- (id: string | null) => {
- activeRequestIdRef.current = id;
- setRequestId(id);
- },
- [setRequestId]
- );
- useEffect(() => {
- activeRequestIdRef.current = currentRequestId;
- }, [currentRequestId]);
- const [showCancelTooltip, setShowCancelTooltip] = useState(false);
- const [showSendTooltip, setShowSendTooltip] = useState(false);
- const [showProgressBarTooltip, setShowProgressBarTooltip] = useState(false);
- const [showMissionStoneModal, setShowMissionStoneModal] = useState(false);
- const [energyStoneModalType, setEnergyStoneModalType] = useState<'mission' | 'conversation'>('mission');
- const [showIntimacyModal, setShowIntimacyModal] = useState(false);
- const [showFuncMenuPopup, setShowFuncMenuPopup] = useState(false);
- const [intimacyHeartCount, setIntimacyHeartCount] = useState(3);
- const [intimacyDaysSinceLastVisit, setIntimacyDaysSinceLastVisit] = useState(0);
- const [intimacyLoading, setIntimacyLoading] = useState(false);
- const [canLightUpToday, setCanLightUpToday] = useState(true);
- // 同步亲密度弹窗状态到 ref,供 WebSocket 消息处理时使用
- useEffect(() => {
- delayGreetingRef.current = showIntimacyModal;
- }, [showIntimacyModal]);
- // 明确触发首句 greeting:由前端控制时机(如亲密度弹窗关闭后)
- const startGreeting = () => {
- // 已经发起过首句,或用户已开始录音(选择以用户为准)时,不再触发 greeting
- if (hasGreetingStartedRef.current || greetingSuppressedRef.current) {
- debugLog('[首句] 已经发起过或用户已开始录音,跳过 start_greeting');
- return;
- }
- const ws = wsRef.current;
- if (!ws) {
- // WebSocket 尚未初始化完成:标记为待发送,等连接成功后由回调统一触发
- debugLog('[首句] WebSocket 未初始化,标记 pendingGreetingRef = true,等待连接成功后再发送 start_greeting');
- pendingGreetingRef.current = true;
- return;
- }
- // 一旦真正发送首句 greeting,则清除待发送标记
- pendingGreetingRef.current = false;
- hasGreetingStartedRef.current = true;
- const requestId = `greeting_${uuidv4().replace(/-/g, '').slice(0, 8)}`;
- debugLog('[首句] 发送 start_greeting 消息', { requestId });
- ws.send({
- type: 'start_greeting',
- requestId,
- });
- };
- const [conversationStoneCount, setConversationStoneCount] = useState<number>(0);
- const [hasClickedMissionStone, setHasClickedMissionStone] = useState(() => {
- return getStorage(STORAGE_KEYS.HAS_CLICKED_MISSION_STONE) === 'true';
- });
- const [hasClickedConversationStone, setHasClickedConversationStone] = useState(() => {
- return getStorage(STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE) === 'true';
- });
- const [hasShownProgressBarTooltip, setHasShownProgressBarTooltip] = useState(() => {
- const stored = getStorage(STORAGE_KEYS.HAS_SHOWN_PROGRESS_BAR_TOOLTIP);
- return stored === 'true';
- });
- const progressBarTooltipTimerRef = useRef<number | null>(null);
- const progressBarTooltipRef = useRef<HTMLImageElement | null>(null);
- const pendingStoneIdRef = useRef<string | null>(null);
- const [isAvatarCUnlocked, setIsAvatarCUnlocked] = useState(() => {
- const stored = getStorage(STORAGE_KEYS.AVATAR_C_UNLOCKED);
- return stored === 'true';
- });
- const avatarCUnlockedRef = useRef(isAvatarCUnlocked);
- useEffect(() => {
- avatarCUnlockedRef.current = isAvatarCUnlocked;
- }, [isAvatarCUnlocked]);
- // 累计总说话时长(仅作为从后端同步后的本地缓存,进度和解锁逻辑均以后端为准)
- const totalSpeechDurationRef = useRef<number>(
- isAvatarCUnlocked ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
- );
-
- // 用于动画的显示进度(平滑过渡)
- const [displayProgress, setDisplayProgress] = useState(0);
- const animationFrameRef = useRef<number>();
- const totalProgressRef = useRef(0);
- // 默认置为 true,避免组件初次挂载或路由返回时尚未完成数据同步就触发历史进度动画。
- const shouldSkipProgressAnimationRef = useRef(true);
- // 保存上一次的进度状态,用于计算动画起始值
- const prevProgressStateRef = useRef<{ progress: number; loopCount: number }>({
- progress: 0,
- loopCount: 0,
- });
- const recordingTimerRef = useRef<number | null>(null);
- const recordingDeadlineRef = useRef<number>(0);
- const handleSendRef = useRef<() => void>();
- const [remainingTimeMs, setRemainingTimeMs] = useState<number | null>(null);
- const pushFrequencyFrame = useCallback((_frame: FrequencyFrame) => {
- // 底部声波纹已移除,不再推送数据
- }, []);
- const resetFrequencyVisualization = useCallback(() => {}, []);
- // 清理字幕文本中的情感前缀(例如 [EMOTION: happy] 你好 → 你好)
- const cleanSubtitleText = useCallback((text: string): string => {
- if (!text) return '';
- // 1) 去掉开头的 [EMOTION:xxx] 或 [emotion:xxx](支持中英文冒号)
- let cleaned = text.replace(/^\s*\[emotion[::][^\]]*]\s*/i, '');
- // 2) 兼容早期格式:去掉开头的【...】或[...] 这一类简单情感标签
- cleaned = cleaned.replace(/^\s*[\[【][^[\]【】]{1,16}[\]】]\s*/, '');
- return cleaned.trim();
- }, []);
- // 同步字幕开关状态到 ref,便于在 AudioPlayer 回调中读取最新值
- useEffect(() => {
- subtitleOnRef.current = subtitleOn;
- }, [subtitleOn]);
- // 只要语音在播报就持续向下滚动,不主动停;仅当字幕消失(不可见或容器卸载)时停止
- const subtitleScrollActiveRef = useRef({ subtitleVisible, currentState });
- const subtitleScrollStepCountRef = useRef(0);
- const subtitleScrollTargetRef = useRef(0);
- const subtitleLastTextLengthRef = useRef(0);
- // recognizedText 更新后恢复滚动位置,避免重渲染把 scrollTop 重置为 0
- useLayoutEffect(() => {
- if (!recognizedText || currentState !== 'playing') return;
- const el = subtitleContainerRef.current;
- if (!el) return;
- const max = el.scrollHeight - el.clientHeight;
- if (max <= 0) return;
- const target = Math.min(subtitleScrollTargetRef.current, max);
- if (target > 0) {
- el.scrollTop = target;
- }
- }, [recognizedText, currentState]);
- useEffect(() => {
- subtitleScrollActiveRef.current = { subtitleVisible, currentState };
- if (!subtitleVisible || currentState !== 'playing') return;
- if (!recognizedText) return;
- const container = subtitleContainerRef.current;
- if (!container) return;
- const textLen = recognizedText.length;
- subtitleLastTextLengthRef.current = textLen;
- // 已有滚动在跑时不再取消、不重启,避免 contentIncreased 时反复重启导致 scrollTop 停在约 1
- if (subtitleAutoScrollRafRef.current !== null) {
- console.log('[SubtitleScroll] effect skip', { reason: 'RAF already running', textLen });
- return () => {};
- }
- subtitleLastFrameTimeRef.current = null;
- subtitleScrollStepCountRef.current = 0;
- subtitleScrollTargetRef.current = container.scrollTop;
- console.log('[SubtitleScroll] effect start', {
- textLen,
- scrollTop: container.scrollTop,
- maxScroll: container.scrollHeight - container.clientHeight,
- });
- const step = (timestamp: number) => {
- const active = subtitleScrollActiveRef.current;
- if (!active.subtitleVisible || active.currentState !== 'playing') {
- console.log('[SubtitleScroll] step stop', { reason: 'active ref', active });
- subtitleAutoScrollRafRef.current = null;
- subtitleLastFrameTimeRef.current = null;
- return;
- }
- const el = subtitleContainerRef.current;
- if (!el) {
- console.log('[SubtitleScroll] step stop', { reason: 'el null' });
- subtitleAutoScrollRafRef.current = null;
- subtitleLastFrameTimeRef.current = null;
- return;
- }
- const maxScrollTop = el.scrollHeight - el.clientHeight;
- if (maxScrollTop <= 0) {
- subtitleAutoScrollRafRef.current = requestAnimationFrame(step);
- return;
- }
- const maxScrollTopCurrent = el.scrollHeight - el.clientHeight;
- const targetRef = subtitleScrollTargetRef.current;
- // 每帧用 targetRef 恢复并推进,不依赖 el.scrollTop(重渲染会把它打回导致卡住)
- const currentScroll = Math.min(Math.max(targetRef, 0), maxScrollTopCurrent);
- el.scrollTop = currentScroll;
- const nearBottom = currentScroll >= maxScrollTopCurrent - 3;
- if (nearBottom) {
- el.scrollTop = maxScrollTopCurrent;
- subtitleScrollTargetRef.current = maxScrollTopCurrent;
- } else {
- const last = subtitleLastFrameTimeRef.current;
- subtitleLastFrameTimeRef.current = timestamp;
- if (last != null) {
- const deltaMs = timestamp - last;
- const linesPerSecond = 0.2;
- const speedPerSecond = (el.clientHeight / 3) * linesPerSecond;
- const delta = (speedPerSecond * deltaMs) / 1000;
- // 基于 targetRef 推进,不读 el.scrollTop,避免被重渲染重置后推进缓慢
- const nextTop = Math.min(currentScroll + delta, maxScrollTopCurrent);
- el.scrollTop = nextTop;
- subtitleScrollTargetRef.current = nextTop;
- const n = (subtitleScrollStepCountRef.current += 1);
- if (n === 1 || n % 90 === 0) {
- console.log('[SubtitleScroll] step scroll', {
- step: n,
- scrollTop: Math.round(nextTop * 10) / 10,
- max: maxScrollTopCurrent,
- delta: Math.round(delta * 10) / 10,
- pct: Math.round((nextTop / maxScrollTopCurrent) * 100),
- });
- }
- }
- }
- subtitleAutoScrollRafRef.current = requestAnimationFrame(step);
- };
- subtitleAutoScrollRafRef.current = requestAnimationFrame((ts) => {
- subtitleLastFrameTimeRef.current = ts;
- subtitleAutoScrollRafRef.current = requestAnimationFrame(step);
- });
- return () => {};
- }, [recognizedText, subtitleVisible, currentState]);
-
- // V2: 完全计算式布局系统
- const [, setLayout] = useState<CalculatedLayout>(() => {
- const initialLayout = calculateLayout();
- return initialLayout;
- });
- // 对话能量石数量(用于顶部状态展示)
- const fetchConversationStoneCount = useCallback(async (userId: string) => {
- try {
- const apiBaseUrl = getApiBaseUrl();
- const request = async () =>
- fetch(`${apiBaseUrl}/api/users/${userId}/energy-stones/count`, {
- method: 'GET',
- headers: getApiHeaders(),
- });
- let response = await request();
- if (response.status === 401) {
- console.warn('[ChatBotPage] 请求能量石数量接口返回 401,认为会话失效,准备清空本地并跳转 /begin', {
- userId,
- });
- clearUserSessionAndRedirectToBegin();
- return;
- }
- if (response.ok) {
- const data = await response.json();
- if (data.success && data.data) {
- setConversationStoneCount(data.data.conversation_count || 0);
- }
- }
- } catch (error) {
- console.error('[ChatBotPage] 获取对话能量石数量失败:', error);
- }
- }, []);
- // GIF 切换定时器(情绪 GIF 播放一次后切回 talking/default)
- const emotionGifTimerRef = useRef<number | null>(null);
- // 待处理情绪缓存:收到 emotion 消息时先缓存,等音频真正开始播放时再驱动情绪动画
- const pendingEmotionRef = useRef<string | null>(null);
- // 已收到 isLast 的 requestId:同轮滞后 chunk 不再重置流、不再次触发 onStart
- const responseCompleteRequestIdRef = useRef<string | null>(null);
- // 已为该 requestId 触发过「流开始」(传过至少一个 chunk 且未 skipStreamReset);同一 request 后续所有 chunk 一律 skipStreamReset,保证一次对话多段音频只触发一次 onStart、只闪一次开心
- const streamStartedForRequestIdRef = useRef<string | null>(null);
- // 本段播放是否已显示过情绪 GIF(开心/难过);兜底:若 onStart 被意外触发两次,第二次只切 talking
- const emotionGifShownForStreamRef = useRef<boolean>(false);
- // 本轮对话是否已播放过情感 GIF(仅点击录音时重置):强制一轮只播一次
- const emotionGifPlayedThisRoundRef = useRef<boolean>(false);
- // 当前正在累积字幕的 requestId;同一次对话多段音频的文字做拼接,新请求时重置
- const subtitleAccumulatorRequestIdRef = useRef<string | null>(null);
- const timingRef = useRef({
- recordStart: 0,
- recordEnd: 0,
- firstAudioReceived: 0,
- emotionReceived: 0,
- });
- // 使用 Web Animations API 驱动飞行动画,避免部分端 CSS 动画被覆盖
- const runStoneAnimation = useCallback(
- (container: HTMLElement | null, dx: number, dy: number) => {
- if (!container) return;
- const img = container.querySelector('.energy-stone') as HTMLElement | null;
- const keyframes: Keyframe[] = [
- {
- transform: 'translate(-50%, -50%) translate3d(0, 0, 0)',
- opacity: 1,
- offset: 0,
- },
- {
- transform: `translate(-50%, -50%) translate3d(${dx}px, ${dy}px, 0)`,
- opacity: 1,
- offset: 0.85,
- },
- {
- transform: `translate(-50%, -50%) translate3d(${dx}px, ${dy}px, 0)`,
- opacity: 0,
- offset: 1,
- },
- ];
- const timing: KeyframeAnimationOptions = {
- duration: 1400,
- easing: 'ease-in-out',
- fill: 'forwards',
- };
- try {
- container.animate(keyframes, timing);
- if (img) {
- img.animate(
- [
- { transform: 'translate(-50%, -50%)', opacity: 1, offset: 0 },
- { transform: 'translate(-50%, -50%)', opacity: 1, offset: 0.85 },
- { transform: 'translate(-50%, -50%)', opacity: 0, offset: 1 },
- ],
- timing
- );
- }
- } catch (error) {
- // 如果 WAAPI 不可用,忽略,保留 CSS 动画兜底
- console.warn('[EnergyStone] WAAPI animate failed, fallback to CSS animation', error);
- }
- },
- []
- );
- // 当前形象ID(支持后端返回/本地缓存)
- const [currentAvatarId, setCurrentAvatarId] = useState<string | null>(() => {
- return getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
- });
- const [avatarGifSets, setAvatarGifSets] = useState<Record<string, AvatarGifSet>>({
- [AVATAR_ID_DEFAULT]: {
- default: FALLBACK_DEFAULT_AVATAR_GIF,
- positive: FALLBACK_POSITIVE_EMOTION_GIF,
- negative: FALLBACK_NEGATIVE_EMOTION_GIF,
- talking: FALLBACK_TALKING_GIF,
- },
- [AVATAR_ID_REGISTERED]: {
- default: FALLBACK_REGISTERED_DEFAULT_AVATAR_GIF,
- positive: FALLBACK_REGISTERED_POSITIVE_EMOTION_GIF,
- negative: FALLBACK_REGISTERED_NEGATIVE_EMOTION_GIF,
- talking: FALLBACK_REGISTERED_TALKING_GIF,
- },
- });
- const resolveAvatarGifSet = useCallback(
- (avatarId: string | null | undefined): AvatarGifSet => {
- const fallback = avatarGifSets[AVATAR_ID_DEFAULT];
- if (!avatarId) {
- debugLog(`[resolveAvatarGifSet] avatarId 为 null,返回默认形象`);
- return fallback;
- }
- const set = avatarGifSets[avatarId];
- const result = {
- default: set?.default || fallback.default,
- positive: set?.positive || fallback.positive,
- negative: set?.negative || fallback.negative,
- talking: set?.talking || fallback.talking,
- };
- debugLog(`[resolveAvatarGifSet] avatarId=${avatarId}, set存在=${!!set}, result=`, result);
- return result;
- },
- [avatarGifSets],
- );
- const avatarGifSet = useMemo(() => {
- const gifSet = resolveAvatarGifSet(currentAvatarId);
- debugLog(`[avatarGifSet] currentAvatarId=${currentAvatarId}, gifSet=`, gifSet);
- return gifSet;
- }, [currentAvatarId, resolveAvatarGifSet]);
- const [currentAvatarGif, setCurrentAvatarGif] = useState<string>(() => {
- const storedId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
- return resolveAvatarGifSet(storedId).default;
- });
- const setGifByState = useCallback(
- (state: AvatarState) => {
- // 实时获取最新的 avatarGifSet,避免闭包问题
- const latestAvatarId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
- // 使用最新的 avatarGifSets 状态来计算 GIF
- const fallback = avatarGifSets[AVATAR_ID_DEFAULT];
- let latestGifSet: AvatarGifSet;
- if (!latestAvatarId) {
- latestGifSet = fallback;
- } else {
- const set = avatarGifSets[latestAvatarId];
- latestGifSet = {
- default: set?.default || fallback.default,
- positive: set?.positive || fallback.positive,
- negative: set?.negative || fallback.negative,
- talking: set?.talking || fallback.talking,
- };
- }
- const nextGif = latestGifSet[state] || latestGifSet.default;
- debugLog(`[setGifByState] state=${state}, currentAvatarId=${currentAvatarId}, latestAvatarId=${latestAvatarId}, nextGif=${nextGif}`);
- setCurrentAvatarGif(nextGif);
- },
- [avatarGifSet, currentAvatarId, avatarGifSets],
- );
- const showDefaultGif = useCallback(() => setGifByState('default'), [setGifByState]);
- const showPositiveGif = useCallback(() => setGifByState('positive'), [setGifByState]);
- const showNegativeGif = useCallback(() => setGifByState('negative'), [setGifByState]);
- const showTalkingGif = useCallback(() => setGifByState('talking'), [setGifByState]);
- // 用 ref 保存最新回调,避免 player 的 onEnd/onBeforeEnd/onStart 闭包陈旧导致形象不同步
- const showDefaultGifRef = useRef(showDefaultGif);
- const showTalkingGifRef = useRef(showTalkingGif);
- const showPositiveGifRef = useRef(showPositiveGif);
- const showNegativeGifRef = useRef(showNegativeGif);
- showDefaultGifRef.current = showDefaultGif;
- showTalkingGifRef.current = showTalkingGif;
- showPositiveGifRef.current = showPositiveGif;
- showNegativeGifRef.current = showNegativeGif;
- // 动画/对话层切到下一层(进入 idle)后,立即将对话层形象设为 default,保证下次对话从 default 开始
- const prevAvatarStateRef = useRef(currentState);
- useEffect(() => {
- if (prevAvatarStateRef.current !== 'idle' && currentState === 'idle') {
- showDefaultGif();
- }
- prevAvatarStateRef.current = currentState;
- }, [currentState, showDefaultGif]);
- // 预加载动画形象的 GIF
- const preloadAvatarGifs = useCallback(
- (avatarId: string | null) => {
- const gifSet = resolveAvatarGifSet(avatarId);
- const gifUrls = [gifSet.default, gifSet.positive, gifSet.negative, gifSet.talking];
-
- // 使用 Image 对象预加载所有 GIF
- gifUrls.forEach((url) => {
- if (url) {
- const img = new Image();
- img.src = url;
- // 静默处理加载错误,避免影响主流程
- img.onerror = () => {
- console.warn(`[预加载] GIF 加载失败: ${url}`);
- };
- }
- });
-
- debugLog(`[预加载] 已开始预加载形象 ${avatarId || 'default'} 的所有 GIF`);
- },
- [resolveAvatarGifSet]
- );
- // 拉取头像 GIF 配置
- useEffect(() => {
- const fetchAvatarGifs = async () => {
- try {
- const res = await getAvatarGifs();
- if (!res.success || !res.data) {
- return;
- }
- setAvatarGifSets((prev) => {
- const next = { ...prev };
- const applyPartial = (key: string, partial?: Partial<AvatarGifSet>) => {
- if (!partial) return;
- const base = next[key] || prev[AVATAR_ID_DEFAULT];
- next[key] = {
- default: partial.default || base.default,
- positive: partial.positive || base.positive,
- negative: partial.negative || base.negative,
- talking: partial.talking || base.talking,
- };
- };
- applyPartial(AVATAR_ID_DEFAULT, res.data.avatar_default);
- applyPartial(AVATAR_ID_REGISTERED, res.data.avatar_registered_cap);
- return next;
- });
- } catch (error) {
- // 静默降级使用兜底
- console.warn('获取头像 GIF 配置失败,使用兜底资源', error);
- }
- };
- fetchAvatarGifs();
- }, []);
- // 当 avatarGifSets 更新或 currentAvatarId 变化时,预加载当前形象的 GIF
- useEffect(() => {
- if (Object.keys(avatarGifSets).length > 0) {
- // 如果 currentAvatarId 为 null,预加载默认形象
- const avatarIdToPreload = currentAvatarId || AVATAR_ID_DEFAULT;
- preloadAvatarGifs(avatarIdToPreload);
- }
- }, [avatarGifSets, currentAvatarId, preloadAvatarGifs]);
- // 监听 storage(跨标签页同步当前形象)
- useEffect(() => {
- const handleStorage = (event: StorageEvent) => {
- if (event.key === STORAGE_KEYS.CURRENT_AVATAR_ID) {
- setCurrentAvatarId(event.newValue);
- }
- if (event.key === STORAGE_KEYS.IS_LOGGED_IN && event.newValue === 'false') {
- // 游客回退默认形象
- setCurrentAvatarId(AVATAR_ID_DEFAULT);
- }
- };
- window.addEventListener('storage', handleStorage);
- return () => {
- window.removeEventListener('storage', handleStorage);
- };
- }, []);
- // 监听路由变化,同步 localStorage 中的 currentAvatarId(处理从其他页面返回的情况)
- useEffect(() => {
- if (location.pathname === '/chatbot') {
- const storedAvatarId = getStorage(STORAGE_KEYS.CURRENT_AVATAR_ID);
- // 只有当 localStorage 中的值与当前状态不一致时才更新
- if (storedAvatarId !== currentAvatarId) {
- debugLog(`[ChatBotPage] 检测到 localStorage 中的形象ID变化: ${currentAvatarId} -> ${storedAvatarId}`);
- setCurrentAvatarId(storedAvatarId);
- // 立即更新显示的 GIF,使用最新的 avatarGifSets
- const newGifSet = resolveAvatarGifSet(storedAvatarId);
- debugLog(`[ChatBotPage] 更新显示的 GIF: ${newGifSet.default}`);
- setCurrentAvatarGif(newGifSet.default);
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [location.pathname]);
- // 当形象变化时立即更新显示 GIF
- useEffect(() => {
- showDefaultGif();
- }, [avatarGifSet, showDefaultGif]);
- const syncUserLevel = useCallback((level: number) => {
- setUserLevel(level);
- setUserLevelValue(level);
- }, []);
- const unlockAvatarC = useCallback(() => {
- if (avatarCUnlockedRef.current) {
- return;
- }
- avatarCUnlockedRef.current = true;
- setIsAvatarCUnlocked(true);
- setStorage(STORAGE_KEYS.AVATAR_C_UNLOCKED, 'true');
- const userId = getUserId();
- if (userId) {
- updateUserUIState(userId, {
- avatar_c_unlocked: true,
- }).catch(() => {
- // 同步失败不影响主流程
- });
- }
- }, []);
- const emitStoneEvent = useCallback(
- (stoneId: string, event: 'click' | 'timeout', position: EnergyStoneEventPayload) => {
- if (!wsRef.current) {
- return;
- }
- wsRef.current.send({
- type: 'energy_stone_event',
- requestId: stoneId,
- stoneId,
- event,
- clientTs: Date.now(),
- position,
- });
- },
- []
- );
- const resolveStoneSize = useCallback(
- (_stoneType: 'mission' | 'conversation') => {
- // 设计稿统一尺寸 48px,基于 vw/vh 最小值
- return 48;
- },
- []
- );
- // 创建一个隐藏的容器元素用于 useEnergyStones hook 计算位置
- const hiddenEnergyStoneZoneRef = useRef<HTMLDivElement>(null);
- const { stones: energyStones, spawnStone, handleStoneClick } = useEnergyStones(hiddenEnergyStoneZoneRef, {
- onEvent: emitStoneEvent,
- resolveStoneSize,
- });
- // 当能量石开始消失时,设置动画的起点和终点(处理超时自动消失的情况)
- useEffect(() => {
- const timers: number[] = [];
- const resetAnimation = (element?: HTMLElement | null) => {
- if (!element) {
- return;
- }
- element.style.animation = 'none';
- // 强制重排,确保重新读取起点坐标
- void element.offsetWidth;
- element.style.animation = '';
- };
- energyStones.forEach((stone) => {
- const container = document.querySelector(
- `[data-stone-id="${stone.stoneId}"]`
- ) as HTMLElement | null;
- // 非消失状态,移除就绪标记,避免错误启动动画
- if (!stone.fading) {
- container?.removeAttribute('data-anim-ready');
- return;
- }
- // 使用 setTimeout 确保 DOM 已更新
- const timer = window.setTimeout(() => {
- const target = document.querySelector(
- `[data-stone-id="${stone.stoneId}"]`
- ) as HTMLElement | null;
- if (!target) {
- return;
- }
- const rect = target.getBoundingClientRect();
- const startLeft = rect.left + rect.width / 2; // 中心点 x 坐标(像素)
- const startTop = rect.top + rect.height / 2; // 中心点 y 坐标(像素)
- // 计算终点位置(动画形象中心,距离顶部60%位置)
- const viewportWidth = window.innerWidth;
- const viewportHeight = window.innerHeight;
- // 计算终点 top 位置(像素)
- const endTopPx = Math.min(
- (452 * Math.min(viewportWidth, 600) / 375),
- (452 / 812) * viewportHeight
- );
- const endLeft = viewportWidth / 2; // 50% 位置(像素)
- const dx = endLeft - startLeft;
- const dy = endTopPx - startTop;
- // 设置 CSS 变量,用于动画(使用像素值)
- target.style.setProperty('--animation-start-left', `${startLeft}px`);
- target.style.setProperty('--animation-start-top', `${startTop}px`);
- target.style.setProperty('--animation-end-left', `${endLeft}px`);
- target.style.setProperty('--animation-end-top', `${endTopPx}px`);
- target.style.setProperty('--animation-dx', `${dx}px`);
- target.style.setProperty('--animation-dy', `${dy}px`);
- // 强制写入动画样式,避免某些终端上样式覆盖/未生效
- target.style.left = `${startLeft}px`;
- target.style.top = `${startTop}px`;
- target.style.transform = 'translate(-50%, -50%) translate3d(0, 0, 0)';
- target.style.animation = 'energyStoneMoveToAvatar 1s ease-in-out forwards';
- target.style.willChange = 'transform, opacity';
- target.style.position = 'fixed';
- target.style.pointerEvents = 'none';
- runStoneAnimation(target, dx, dy);
- // 标记动画就绪,允许 CSS 启动
- target.setAttribute('data-anim-ready', 'true');
- // 重新启动动画,确保使用更新后的起点
- resetAnimation(target);
- resetAnimation(target.querySelector('.energy-stone') as HTMLElement | null);
- resetAnimation(target.querySelector('.energy-stone-hint') as HTMLElement | null);
- }, 0);
- timers.push(timer);
- });
- return () => {
- timers.forEach((timer) => {
- window.clearTimeout(timer);
- });
- };
- }, [energyStones, runStoneAnimation]);
- const startStoneAnimationAndRemove = useCallback(
- (stoneId: string) => {
- const container = document.querySelector(
- `[data-stone-id="${stoneId}"]`
- ) as HTMLElement | null;
- if (container) {
- const rect = container.getBoundingClientRect();
- const startLeft = rect.left + rect.width / 2;
- const startTop = rect.top + rect.height / 2;
- const viewportWidth = window.innerWidth;
- const viewportHeight = window.innerHeight;
- const endTopPx = Math.min(
- (452 * Math.min(viewportWidth, 600) / 375),
- (452 / 812) * viewportHeight
- );
- const endLeft = viewportWidth / 2;
- const dx = endLeft - startLeft;
- const dy = endTopPx - startTop;
- container.style.setProperty('--animation-start-left', `${startLeft}px`);
- container.style.setProperty('--animation-start-top', `${startTop}px`);
- container.style.setProperty('--animation-end-left', `${endLeft}px`);
- container.style.setProperty('--animation-end-top', `${endTopPx}px`);
- container.style.setProperty('--animation-dx', `${dx}px`);
- container.style.setProperty('--animation-dy', `${dy}px`);
- container.style.left = `${startLeft}px`;
- container.style.top = `${startTop}px`;
- container.style.transform = 'translate(-50%, -50%) translate3d(0, 0, 0)';
- container.style.animation = 'energyStoneMoveToAvatar 1s ease-in-out forwards';
- container.style.willChange = 'transform, opacity';
- container.style.position = 'fixed';
- container.style.pointerEvents = 'none';
- runStoneAnimation(container, dx, dy);
- }
- handleStoneClick(stoneId);
- // 能量石被点击后,刷新一次顶部的对话能量石数量(从数据库读取最新值)
- const uid = getUserId();
- if (uid) {
- fetchConversationStoneCount(uid);
- }
- },
- [handleStoneClick, runStoneAnimation, fetchConversationStoneCount]
- );
- const handleMissionStoneModalClose = useCallback(() => {
- setShowMissionStoneModal(false);
- const pendingStoneId = pendingStoneIdRef.current;
- if (pendingStoneId) {
- pendingStoneIdRef.current = null;
- startStoneAnimationAndRemove(pendingStoneId);
- }
- }, [startStoneAnimationAndRemove]);
- // 能量石展示区域:宽高 & 位置按设计稿 375×812 固定,以 px2vw/px2vh/px2vmin 适配
- const stopRecordingTimer = useCallback((options?: { preserveCountdown?: boolean }) => {
- if (recordingTimerRef.current) {
- clearInterval(recordingTimerRef.current);
- recordingTimerRef.current = null;
- }
- recordingDeadlineRef.current = 0;
- if (!options?.preserveCountdown) {
- setRemainingTimeMs(null);
- }
- }, []);
- const startRecordingTimer = useCallback(() => {
- stopRecordingTimer();
- recordingDeadlineRef.current = Date.now() + MAX_RECORDING_DURATION_MS;
- setRemainingTimeMs(MAX_RECORDING_DURATION_MS);
- recordingTimerRef.current = window.setInterval(() => {
- const remaining = recordingDeadlineRef.current - Date.now();
- if (remaining <= 0) {
- setRemainingTimeMs(0);
- stopRecordingTimer({ preserveCountdown: true });
- if (useAppStore.getState().currentState === 'recording') {
- handleSendRef.current?.();
- }
- return;
- }
- setRemainingTimeMs(remaining);
- }, 250);
- }, [stopRecordingTimer]);
- useEffect(() => {
- return () => {
- stopRecordingTimer();
- };
- }, [stopRecordingTimer]);
- useEffect(() => {
- if (currentState !== 'recording') {
- stopRecordingTimer();
- }
- }, [currentState, stopRecordingTimer]);
- /** 录音 50~60 秒已用时间显示:00:50、00:51 … 01:00(仅在剩余 ≤10 秒时用) */
- const formatElapsed50to60 = (remainingMs: number): string => {
- const elapsedSeconds = Math.min(60, Math.max(50, Math.floor((MAX_RECORDING_DURATION_MS - remainingMs) / 1000)));
- const minutes = Math.floor(elapsedSeconds / 60);
- const seconds = elapsedSeconds % 60;
- return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
- };
- // 进度动画效果(支持多圈连续动画)
- useEffect(() => {
- const targetTotal = progressLoopCount * 100 + conversationProgress;
-
- // 🔍 日志:记录 useEffect 触发时的状态
- debugLog('[Progress] [useEffect] 触发:', {
- conversationProgress,
- progressLoopCount,
- targetTotal,
- prevProgressStateRef: { ...prevProgressStateRef.current },
- totalProgressRef: totalProgressRef.current,
- displayProgress,
- shouldSkipAnimation: shouldSkipProgressAnimationRef.current,
- hasActiveAnimation: !!animationFrameRef.current,
- });
- // 🔧 如果 shouldSkipProgressAnimation 为 true,说明处于初始化/同步阶段
- // 直接同步 ref 并返回,避免播放历史动画。标志由后续用户动作(如 handleSend)再置为 false。
- if (shouldSkipProgressAnimationRef.current) {
- debugLog('[Progress] [useEffect] 初始化/同步阶段,跳过动画并同步 ref');
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- animationFrameRef.current = undefined;
- }
- prevProgressStateRef.current = {
- progress: conversationProgress,
- loopCount: progressLoopCount,
- };
- totalProgressRef.current = targetTotal;
- const normalized = ((targetTotal % 100) + 100) % 100;
- setDisplayProgress(normalized);
- return;
- }
-
- // 使用上一次保存的状态值作为起始值(确保动画起始值正确)
- // 这样可以避免 displayProgress 异步更新导致的时序问题
- let prevTotal = prevProgressStateRef.current.loopCount * 100 + prevProgressStateRef.current.progress;
-
- // 立即保存当前状态到 prevProgressStateRef(供下次动画使用)
- // 这样即使本次动画还没完成,新的状态更新也能正确工作
- const currentState = {
- progress: conversationProgress,
- loopCount: progressLoopCount,
- };
-
- // 如果 prevTotal 是初始值 0,但目标值已经大于 0,说明是首次使用或状态被重置
- // 此时应该使用 totalProgressRef.current 或 displayProgress 作为起始值
- // 但如果 shouldSkipProgressAnimation 为 true,说明是初始化,应该直接使用目标值作为起始值
- if (prevTotal === 0 && targetTotal > 0) {
- if (shouldSkipProgressAnimationRef.current) {
- // 初始化场景:直接使用目标值作为起始值,避免播放动画
- debugLog('[Progress] [useEffect] 初始化场景,使用目标值作为起始值,跳过动画');
- prevTotal = targetTotal;
- prevProgressStateRef.current = currentState;
- totalProgressRef.current = targetTotal;
- } else {
- debugLog('[Progress] [useEffect] 检测到初始值情况,使用 displayProgress 或 totalProgressRef');
- // 如果 totalProgressRef 有值,使用它;否则使用 displayProgress
- if (totalProgressRef.current > 0) {
- prevTotal = totalProgressRef.current;
- debugLog('[Progress] [useEffect] 使用 totalProgressRef:', totalProgressRef.current);
- } else {
- prevTotal = displayProgress;
- debugLog('[Progress] [useEffect] 使用 displayProgress:', displayProgress);
- }
- // 更新 prevProgressStateRef 为当前显示的状态
- prevProgressStateRef.current = {
- progress: displayProgress,
- loopCount: Math.floor(totalProgressRef.current / 100),
- };
- debugLog('[Progress] [useEffect] 更新 prevProgressStateRef 为:', prevProgressStateRef.current);
- }
- }
-
- // 始终使用上一次保存的状态作为起始值,而不是 totalProgressRef.current
- // 因为 totalProgressRef.current 可能在动画过程中,不准确
- let startTotal = prevTotal;
-
- // 如果 totalProgressRef 与上一次状态不一致,同步它
- // 这样可以确保 totalProgressRef 与起始值一致,避免动画跳变
- if (!shouldSkipProgressAnimationRef.current) {
- const diffFromPrev = Math.abs(totalProgressRef.current - prevTotal);
-
- debugLog('[Progress] [useEffect] 检查 totalProgressRef 同步:', {
- diffFromPrev,
- totalProgressRef: totalProgressRef.current,
- prevTotal,
- needSync: diffFromPrev > 1,
- });
-
- // 如果差异较大(超过1%),说明可能有动画在进行,需要取消它并同步起始值
- if (diffFromPrev > 1) {
- debugLog('[Progress] [useEffect] 取消旧动画并同步 totalProgressRef');
- // 取消可能正在进行的动画
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- animationFrameRef.current = undefined;
- }
- // 同步 totalProgressRef 到起始值
- totalProgressRef.current = startTotal;
- }
- }
-
- // 立即更新 prevProgressStateRef 为当前状态(供下次动画使用)
- // 注意:这里保存的是本次动画的目标值,下次动画会使用这个值作为起始值
- prevProgressStateRef.current = currentState;
-
- const diff = targetTotal - startTotal;
-
- debugLog('[Progress] [useEffect] 计算动画参数:', {
- startTotal,
- targetTotal,
- diff,
- willAnimate: Math.abs(diff) >= 0.01 && !shouldSkipProgressAnimationRef.current,
- });
- // 如果 diff 为 0 或非常小,直接同步,不播放动画
- if (Math.abs(diff) < 0.01) {
- debugLog('[Progress] [useEffect] 跳过动画(diff 太小):', {
- diff,
- startTotal,
- targetTotal,
- });
- totalProgressRef.current = targetTotal;
- const normalized = ((targetTotal % 100) + 100) % 100;
- setDisplayProgress(normalized);
- // prevProgressStateRef 已经在上面更新了,这里不需要再次更新
- return;
- }
- // 处理整数圈:如果 diff 接近 0 且是整数圈,播放完整一圈动画
- let actualDiff = diff;
- if (Math.abs(diff) < 0.1) {
- // 判断是否是整数圈(目标值是 100 的整数倍)
- const isIntegerLoop = Math.abs(targetTotal % 100) < 0.1;
- if (isIntegerLoop && targetTotal > startTotal) {
- // 整数圈增长,播放完整一圈动画
- actualDiff = 100;
- } else if (isIntegerLoop && targetTotal < startTotal) {
- // 整数圈减少,播放完整一圈反向动画
- actualDiff = -100;
- } else {
- // 非整数圈的微小变化,直接同步
- totalProgressRef.current = targetTotal;
- const normalized = ((targetTotal % 100) + 100) % 100;
- setDisplayProgress(normalized);
- // prevProgressStateRef 已经在上面更新了,这里不需要再次更新
- return;
- }
- }
- // 每 1% 的进度约 8ms,限制在 0.4s~2.4s 之间
- const durationPerPercent = 8;
- const duration = Math.max(400, Math.min(2400, Math.abs(actualDiff) * durationPerPercent));
- const startTime = performance.now();
- debugLog('[Progress] [useEffect] 开始动画:', {
- startTotal,
- targetTotal,
- actualDiff,
- duration,
- startTime,
- });
- if (animationFrameRef.current) {
- debugLog('[Progress] [useEffect] 取消旧动画');
- cancelAnimationFrame(animationFrameRef.current);
- }
- let animationFrameCount = 0;
- const animate = (currentTime: number) => {
- animationFrameCount++;
- const elapsed = currentTime - startTime;
- const progress = Math.min(elapsed / duration, 1);
- // easeOutCubic 缓动
- const easeProgress = 1 - Math.pow(1 - progress, 3);
- const currentTotal = startTotal + actualDiff * easeProgress;
- totalProgressRef.current = currentTotal;
- const normalized = ((currentTotal % 100) + 100) % 100;
- setDisplayProgress(normalized);
- // 🔍 日志:每10帧记录一次动画进度
- if (animationFrameCount % 10 === 0 || progress >= 1) {
- debugLog('[Progress] [animate] 动画进度:', {
- frame: animationFrameCount,
- progress: (progress * 100).toFixed(2) + '%',
- currentTotal: currentTotal.toFixed(2),
- normalized: normalized.toFixed(2),
- elapsed: elapsed.toFixed(2) + 'ms',
- });
- }
- if (progress < 1) {
- animationFrameRef.current = requestAnimationFrame(animate);
- } else {
- // 动画完成后,同步到实际的目标值
- debugLog('[Progress] [animate] 动画完成:', {
- finalTotal: targetTotal,
- finalNormalized: ((targetTotal % 100) + 100) % 100,
- totalFrames: animationFrameCount,
- });
- totalProgressRef.current = targetTotal;
- const finalNormalized = ((targetTotal % 100) + 100) % 100;
- setDisplayProgress(finalNormalized);
- // prevProgressStateRef 已经在 useEffect 开始时更新了,这里不需要再次更新
- }
- };
- animationFrameRef.current = requestAnimationFrame(animate);
- return () => {
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- }
- };
- }, [conversationProgress, progressLoopCount]);
- // 监听录音状态,首次显示取消提示(由 ENABLE_CHATBOT_TIPS 控制)
- useEffect(() => {
- if (!ENABLE_CHATBOT_TIPS) return;
- let timer: number | undefined;
- if (currentState === 'recording') {
- const hasShownCancel = getStorage(STORAGE_KEYS.HAS_SHOWN_CANCEL_TOOLTIP);
- if (!hasShownCancel) {
- timer = window.setTimeout(() => {
- setShowCancelTooltip(true);
- setStorage(STORAGE_KEYS.HAS_SHOWN_CANCEL_TOOLTIP, 'true');
- const userId = getUserId();
- if (userId) {
- updateUserUIState(userId, {
- has_shown_cancel_tooltip: true,
- }).catch(() => {});
- }
- }, 200);
- } else {
- setShowCancelTooltip(false);
- }
- } else {
- setShowCancelTooltip(false);
- }
- return () => {
- if (timer !== undefined) window.clearTimeout(timer);
- };
- }, [currentState]);
- // 监听录音状态,首次显示发送提示(由 ENABLE_CHATBOT_TIPS 控制)
- useEffect(() => {
- if (!ENABLE_CHATBOT_TIPS) return;
- let timer: number | undefined;
- if (currentState === 'recording') {
- const hasShownSend = getStorage(STORAGE_KEYS.HAS_SHOWN_SEND_TOOLTIP);
- if (!hasShownSend) {
- timer = window.setTimeout(() => {
- setShowSendTooltip(true);
- setStorage(STORAGE_KEYS.HAS_SHOWN_SEND_TOOLTIP, 'true');
- const userId = getUserId();
- if (userId) {
- updateUserUIState(userId, {
- has_shown_send_tooltip: true,
- }).catch(() => {});
- }
- }, 200);
- } else {
- setShowSendTooltip(false);
- }
- } else {
- setShowSendTooltip(false);
- }
- return () => {
- if (timer !== undefined) window.clearTimeout(timer);
- };
- }, [currentState]);
- const dismissProgressBarTooltip = useCallback(() => {
- if (progressBarTooltipTimerRef.current) {
- clearTimeout(progressBarTooltipTimerRef.current);
- progressBarTooltipTimerRef.current = null;
- }
- if (progressBarTooltipRef.current) {
- progressBarTooltipRef.current.style.opacity = '0';
- progressBarTooltipRef.current.style.pointerEvents = 'none';
- progressBarTooltipRef.current.style.display = 'none';
- }
- setShowProgressBarTooltip(false);
- }, []);
- useEffect(() => {
- if (showProgressBarTooltip && progressBarTooltipRef.current) {
- progressBarTooltipRef.current.style.display = 'block';
- progressBarTooltipRef.current.style.opacity = '1';
- progressBarTooltipRef.current.style.pointerEvents = 'none';
- }
- }, [showProgressBarTooltip]);
- // 监听进度条变化,首次有进度时显示进度条提示(由 ENABLE_CHATBOT_TIPS 控制)
- useEffect(() => {
- if (!ENABLE_CHATBOT_TIPS) return;
- if (
- displayProgress > 0 &&
- !hasShownProgressBarTooltip &&
- isConnected &&
- currentState !== 'recording'
- ) {
- setShowProgressBarTooltip(true);
- setStorage(STORAGE_KEYS.HAS_SHOWN_PROGRESS_BAR_TOOLTIP, 'true');
- setHasShownProgressBarTooltip(true);
- const userId = getUserId();
- if (userId) {
- updateUserUIState(userId, {
- has_shown_progress_bar_tooltip: true,
- }).catch(() => {});
- }
- }
- }, [displayProgress, hasShownProgressBarTooltip, isConnected, currentState]);
- // 进度条提示显示后自动隐藏(2 秒)
- useEffect(() => {
- if (!showProgressBarTooltip) {
- if (progressBarTooltipTimerRef.current) {
- clearTimeout(progressBarTooltipTimerRef.current);
- progressBarTooltipTimerRef.current = null;
- }
- return;
- }
- progressBarTooltipTimerRef.current = window.setTimeout(() => {
- setShowProgressBarTooltip(false);
- progressBarTooltipTimerRef.current = null;
- }, 2000);
- return () => {
- if (progressBarTooltipTimerRef.current) {
- clearTimeout(progressBarTooltipTimerRef.current);
- progressBarTooltipTimerRef.current = null;
- }
- };
- }, [showProgressBarTooltip]);
- // 录音状态下强制隐藏进度条提示,避免在用户开始录音后残留
- useEffect(() => {
- if (currentState === 'recording') {
- dismissProgressBarTooltip();
- }
- }, [currentState, dismissProgressBarTooltip]);
- // 监听屏幕尺寸变化
- useEffect(() => {
- // 初始化时更新标记
- updateTooSmallFlag();
-
- const cleanup = onScreenResize(() => {
- const newLayout = calculateLayout();
- setLayout(newLayout); // V2: 更新完全计算式布局
-
- // 更新 data-too-small 标记
- updateTooSmallFlag();
- });
-
- return cleanup;
- }, []);
- // 同步背景图片状态的函数
- const syncBackgroundImageState = useCallback(() => {
- const bgUrl = getCurrentBackgroundImageUrl();
- const bgId = getCurrentBackgroundImageId();
- // 直接更新状态,React 会自动处理重复更新
- setBackgroundImageUrl(bgUrl);
- setBackgroundImageId(bgId);
- }, []);
- // 初始化背景图片(从 localStorage 读取)
- useEffect(() => {
- const bgUrl = getCurrentBackgroundImageUrl();
- const bgId = getCurrentBackgroundImageId();
- if (bgUrl) {
- setBackgroundImageUrl(bgUrl);
- }
- if (bgId) {
- setBackgroundImageId(bgId);
- }
- if (!bgUrl || !bgId) {
- // 如果没有背景图片,尝试从用户信息同步
- const user_id = getUserId();
- if (user_id) {
- getUserInfo(user_id).then((userInfo) => {
- if (userInfo.success && userInfo.data?.current_background_image_id) {
- syncBackgroundImageToStorage(
- userInfo.data.current_background_image_id,
- userInfo.data.current_background_image_metadata
- );
- const newBgUrl = getCurrentBackgroundImageUrl();
- const newBgId = getCurrentBackgroundImageId();
- if (newBgUrl) {
- setBackgroundImageUrl(newBgUrl);
- }
- if (newBgId) {
- setBackgroundImageId(newBgId);
- }
- }
- }).catch(() => {
- // 静默处理错误
- });
- }
- }
- }, []);
- // 能量石点击后直接消失,不再需要监听 fading 状态
- // 监听 localStorage 中背景图片的变化
- useEffect(() => {
- // 监听 storage 事件(其他标签页/窗口的变化)
- const handleStorageChange = (e: StorageEvent) => {
- if (e.key === STORAGE_KEYS.CURRENT_BACKGROUND_IMAGE_ID ||
- e.key === STORAGE_KEYS.CURRENT_BACKGROUND_IMAGE_URL) {
- syncBackgroundImageState();
- }
- };
- // 监听页面可见性变化(当页面重新获得焦点时检查)
- const handleVisibilityChange = () => {
- if (!document.hidden) {
- syncBackgroundImageState();
- }
- };
- // 定期检查背景图片变化(作为后备机制,每5秒检查一次)
- const intervalId = setInterval(() => {
- syncBackgroundImageState();
- }, 5000);
- window.addEventListener('storage', handleStorageChange);
- document.addEventListener('visibilitychange', handleVisibilityChange);
- return () => {
- window.removeEventListener('storage', handleStorageChange);
- document.removeEventListener('visibilitychange', handleVisibilityChange);
- clearInterval(intervalId);
- };
- }, [syncBackgroundImageState]);
- // 处理OAuth登录回调(QQ登录成功后直接跳转到chatbot)
- useEffect(() => {
- const oauth = searchParams.get('oauth');
- const userId = searchParams.get('user_id');
- const token = searchParams.get('token');
-
- // 如果 URL 中有 OAuth 回调参数,说明是登录成功回调
- // ✅ 确保 user_id 和 token 已设置到 localStorage(双重保险,避免时序问题)
- if (oauth === 'qq' && userId) {
- console.log(`[ChatBotPage] 🔧 检测到 QQ OAuth 回调,确保参数已设置到 localStorage - user_id=${userId}, token=${token ? '已提供' : '未提供'}`);
-
- // 1. 确保用户 ID 已设置(同步操作)
- setStorage(STORAGE_KEYS.USER_ID, userId);
-
- // 2. 如果 URL 中有 token,确保已设置(同步操作)
- if (token) {
- setUserToken(token);
- console.log(`[ChatBotPage] ✅ 已设置 token 到 localStorage`);
- }
-
- // 3. 确保登录状态已设置(同步操作)
- setStorage(STORAGE_KEYS.IS_LOGGED_IN, 'true');
-
- console.log(`[ChatBotPage] ✅ QQ OAuth 回调参数已全部设置到 localStorage`);
- antMessage.success(tCommon('qqLoginSuccess'));
-
- // 清除URL参数(延迟清除,确保 UserGuard 能读取到参数)
- setTimeout(() => {
- navigate('/chatbot', { replace: true });
- }, 100);
- }
- }, [searchParams, navigate]);
- // 初始化
- useEffect(() => {
- // 🔧 立即设置 shouldSkipProgressAnimation = true,避免在异步加载完成前触发动画
- // 这可以防止从其他页面返回时播放历史动画
- shouldSkipProgressAnimationRef.current = true;
- debugLog('[Progress] [初始化] 组件挂载,设置 shouldSkipProgressAnimation = true');
-
- // 记录用户当前所在页面
- setStorage(STORAGE_KEYS.CURRENT_PAGE, 'chatbot');
-
- // 记录路由访问
- markRouteVisited('/chatbot');
- const visited = getVisitedRoutes();
- const userId = getUserId();
- if (userId) {
- // 从数据库加载所有用户信息到 localStorage
- // 1. 先加载用户基本信息(getUserInfo)
- // 2. 再加载用户 UI 状态(getUserUIState)
- Promise.all([
- getUserInfo(userId).catch(() => null),
- getUserUIState(userId).catch(() => null),
- ]).then(([userInfoResult, uiStateResult]) => {
- // 加载用户基本信息到 localStorage
- if (userInfoResult?.success && userInfoResult.data) {
- const userInfo = userInfoResult.data;
-
- // Lyrria_user_name
- if (userInfo.username) {
- setUserName(userInfo.username);
- }
-
- // Lyrria_lumi_name
- if (userInfo.bot_name) {
- setStorage(STORAGE_KEYS.LUMI_NAME, userInfo.bot_name);
- }
-
- // Lyrria_user_level
- if (typeof userInfo.user_level === 'number') {
- syncUserLevel(userInfo.user_level);
- }
-
- // Lyrria_is_logged_in (根据 user_type 判断:registered 为已登录)
- if (userInfo.user_type === 'registered') {
- setStorage(STORAGE_KEYS.IS_LOGGED_IN, 'true');
- } else {
- setStorage(STORAGE_KEYS.IS_LOGGED_IN, 'false');
- }
-
- // Lyrria_current_background_image_id, Lyrria_current_background_image_url, Lyrria_current_background_image_opacity
- if (userInfo.current_background_image_id) {
- syncBackgroundImageToStorage(
- userInfo.current_background_image_id,
- userInfo.current_background_image_metadata
- );
- const bgUrl = getCurrentBackgroundImageUrl();
- const bgId = getCurrentBackgroundImageId();
- if (bgUrl) {
- setBackgroundImageUrl(bgUrl);
- }
- if (bgId) {
- setBackgroundImageId(bgId);
- }
- }
-
- // 初始化进度条(基于 total_speech_duration_ms)
- const totalDurationMs = userInfo.total_speech_duration_ms ?? 0;
- if (totalDurationMs > 0) {
- const PROGRESS_FULL_DURATION_MS = 30 * 1000; // 30000ms
- totalSpeechDurationRef.current = Math.max(
- totalDurationMs,
- avatarCUnlockedRef.current ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
- );
- if (totalDurationMs >= AVATAR_C_UNLOCK_THRESHOLD_MS) {
- unlockAvatarC();
- }
- const totalProgressPercent = (totalDurationMs / PROGRESS_FULL_DURATION_MS) * 100;
- const initialProgress = totalProgressPercent % 100;
- const initialLoopCount = Math.floor(totalProgressPercent / 100);
-
- debugLog('[Progress] [初始化] 设置 shouldSkipProgressAnimation = true (Promise.all)', {
- totalDurationMs,
- totalProgressPercent,
- initialProgress,
- initialLoopCount,
- });
- // 在设置进度之前,先同步 prevProgressStateRef 和 totalProgressRef,避免动画计算错误
- prevProgressStateRef.current = {
- progress: initialProgress,
- loopCount: initialLoopCount,
- };
- totalProgressRef.current = initialLoopCount * 100 + initialProgress;
- shouldSkipProgressAnimationRef.current = true;
- // 设置正确的圈数,而不是重置为 0
- setProgress(initialProgress, initialLoopCount);
- }
- }
-
- // 加载用户 UI 状态到 localStorage
- if (uiStateResult?.success && uiStateResult.data) {
- const state = uiStateResult.data;
-
- // Lyrria_current_avatar_id
- if (state.current_avatar_id) {
- setCurrentAvatarId(state.current_avatar_id);
- setStorage(STORAGE_KEYS.CURRENT_AVATAR_ID, state.current_avatar_id);
- }
-
- // Lyrria_current_page
- if (state.current_page) {
- setStorage(STORAGE_KEYS.CURRENT_PAGE, state.current_page);
- }
-
- // Lyrria_visited_routes (合并本地和数据库的路由,避免覆盖本地刚记录的路由)
- const localVisited = getVisitedRoutes();
- if (Array.isArray(state.visited_routes)) {
- // 合并本地和数据库的路由,去重并保持顺序
- const mergedRoutes = [...new Set([...localVisited, ...state.visited_routes])];
- // 按照 ROUTE_ORDER 的顺序排序
- const sortedRoutes = ROUTE_ORDER.filter(route => mergedRoutes.includes(route));
- setStorage(STORAGE_KEYS.VISITED_ROUTES, JSON.stringify(sortedRoutes));
- } else if (state.visited_routes === null || state.visited_routes === undefined) {
- // 如果数据库中是 null 或 undefined,保留本地已有的路由
- if (localVisited.length > 0) {
- setStorage(STORAGE_KEYS.VISITED_ROUTES, JSON.stringify(localVisited));
- } else {
- setStorage(STORAGE_KEYS.VISITED_ROUTES, JSON.stringify([]));
- }
- }
-
- // Lyrria_has_shown_tap_to_chat
- if (state.has_shown_tap_to_chat) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT, 'true');
- if (isConnected) {
- setShowTapToChat(false);
- }
- }
-
- // Lyrria_has_shown_cancel_tooltip
- if (state.has_shown_cancel_tooltip) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_CANCEL_TOOLTIP, 'true');
- setShowCancelTooltip(false);
- }
-
- // Lyrria_has_shown_send_tooltip
- if (state.has_shown_send_tooltip) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_SEND_TOOLTIP, 'true');
- setShowSendTooltip(false);
- }
-
- // Lyrria_has_shown_progress_bar_tooltip
- if (state.has_shown_progress_bar_tooltip) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_PROGRESS_BAR_TOOLTIP, 'true');
- setHasShownProgressBarTooltip(true);
- }
-
- // Lyrria_avatar_c_unlocked
- if (state.avatar_c_unlocked && !avatarCUnlockedRef.current) {
- avatarCUnlockedRef.current = true;
- setIsAvatarCUnlocked(true);
- setStorage(STORAGE_KEYS.AVATAR_C_UNLOCKED, 'true');
- }
-
- // Lyrria_has_shared_avatar (无论 true/false,都从数据库同步)
- setStorage(STORAGE_KEYS.HAS_SHARED_AVATAR, state.has_shared_avatar ? 'true' : 'false');
- setHasSharedAvatarState(state.has_shared_avatar);
-
- // 字幕开关偏好(无论 true/false,都从数据库同步)
- if (typeof state.subtitle_on === 'boolean') {
- setStorage(STORAGE_KEYS.SUBTITLE_ON, state.subtitle_on ? 'true' : 'false');
- setSubtitleOn(state.subtitle_on);
- }
-
- // Lyrria_has_shown_mission_stone_modal
- if (state.has_shown_mission_stone_modal) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_MISSION_STONE_MODAL, 'true');
- }
-
- // Lyrria_has_shown_conversation_stone_modal
- if (state.has_shown_conversation_stone_modal) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_CONVERSATION_STONE_MODAL, 'true');
- }
-
- // Lyrria_has_clicked_mission_stone
- if (state.has_clicked_mission_stone) {
- setStorage(STORAGE_KEYS.HAS_CLICKED_MISSION_STONE, 'true');
- setHasClickedMissionStone(true);
- }
-
- // Lyrria_has_clicked_conversation_stone
- if (state.has_clicked_conversation_stone) {
- setStorage(STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE, 'true');
- setHasClickedConversationStone(true);
- }
-
- // 补偿同步:如果本地记录为 true 但后端为 false,尝试补偿同步
- const localMissionShown = getStorage(STORAGE_KEYS.HAS_SHOWN_MISSION_STONE_MODAL) === 'true';
- if (localMissionShown && !state.has_shown_mission_stone_modal) {
- updateUserUIState(userId, {
- has_shown_mission_stone_modal: true,
- }).catch(() => {
- // 静默处理
- });
- }
- const localConversationShown =
- getStorage(STORAGE_KEYS.HAS_SHOWN_CONVERSATION_STONE_MODAL) === 'true';
- if (localConversationShown && !state.has_shown_conversation_stone_modal) {
- updateUserUIState(userId, {
- has_shown_conversation_stone_modal: true,
- }).catch(() => {
- // 静默处理
- });
- }
- const localMissionClicked = getStorage(STORAGE_KEYS.HAS_CLICKED_MISSION_STONE) === 'true';
- if (localMissionClicked && !state.has_clicked_mission_stone) {
- updateUserUIState(userId, {
- has_clicked_mission_stone: true,
- }).catch(() => {
- // 静默处理
- });
- }
- const localConversationClicked = getStorage(STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE) === 'true';
- if (localConversationClicked && !state.has_clicked_conversation_stone) {
- updateUserUIState(userId, {
- has_clicked_conversation_stone: true,
- }).catch(() => {
- // 静默处理
- });
- }
- }
- }).catch(() => {
- // 加载失败不影响主流程
- console.warn('[ChatBotPage] 从数据库加载用户信息失败');
- });
- // 同步当前页面与已访问路由
- updateUserUIState(userId, {
- current_page: 'chatbot',
- visited_routes: visited,
- }).catch(() => {
- // 同步失败不影响主流程
- });
- // 对话能量石数量(顶部状态)
- fetchConversationStoneCount(userId);
- // 亲密度:不满 3 颗心且当天未点亮时在 /chatbot 展示弹窗
- Promise.allSettled([getIntimacy(userId), getIntimacyStatus(userId)]).then((results) => {
- const intimacyRes =
- results[0].status === 'fulfilled' ? results[0].value : undefined;
- const statusRes =
- results[1].status === 'fulfilled' ? results[1].value : undefined;
- if (intimacyRes?.success && intimacyRes.data) {
- setIntimacyHeartCount(intimacyRes.data.heart_count);
- setIntimacyDaysSinceLastVisit(intimacyRes.data.days_since_last_visit);
- }
- if (statusRes?.success && statusRes.data) {
- setCanLightUpToday(statusRes.data.can_light_up_today);
- }
- const heartCount =
- intimacyRes?.data?.heart_count ?? statusRes?.data?.heart_count ?? 3;
- const canLight =
- statusRes?.data?.can_light_up_today ?? heartCount < 3;
- if (heartCount < 3 && canLight) {
- // 有亲密度弹窗时,先展示弹窗,等用户关闭后再触发首句 greeting
- setShowIntimacyModal(true);
- } else {
- // 无需展示亲密度弹窗时,直接在聊天页初始化完成后触发首句 greeting
- startGreeting();
- }
- });
- } else {
- // 没有 userId(如游客态)时,不走亲密度流程,直接尝试触发首句 greeting
- startGreeting();
- }
- const init = async () => {
- try {
- // 获取用户信息并初始化进度条(已在上面 Promise.all 中处理,这里保留作为兜底)
- const user_id = getUserId();
- if (user_id) {
- try {
- const userInfo = await getUserInfo(user_id);
- if (userInfo.success && userInfo.data) {
- // 同步用户名到 localStorage
- if (userInfo.data.username) {
- setUserName(userInfo.data.username);
- }
- // 同步机器人名字到 localStorage
- if (userInfo.data.bot_name) {
- setStorage(STORAGE_KEYS.LUMI_NAME, userInfo.data.bot_name);
- }
- // 同步用户等级
- const totalDurationMs = userInfo.data.total_speech_duration_ms ?? 0;
- if (typeof userInfo.data.user_level === 'number') {
- syncUserLevel(userInfo.data.user_level);
- }
- // 同步背景图片
- if (userInfo.data.current_background_image_id) {
- syncBackgroundImageToStorage(
- userInfo.data.current_background_image_id,
- userInfo.data.current_background_image_metadata
- );
- const bgUrl = getCurrentBackgroundImageUrl();
- const bgId = getCurrentBackgroundImageId();
- if (bgUrl) {
- setBackgroundImageUrl(bgUrl);
- }
- if (bgId) {
- setBackgroundImageId(bgId);
- }
- }
- if (totalDurationMs > 0) {
- // 根据总说话时长计算初始进度(30秒=100%)
- const PROGRESS_FULL_DURATION_MS = 30 * 1000; // 30000ms
- totalSpeechDurationRef.current = Math.max(
- totalDurationMs,
- avatarCUnlockedRef.current ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
- );
- if (totalDurationMs >= AVATAR_C_UNLOCK_THRESHOLD_MS) {
- unlockAvatarC();
- }
- // 计算总进度百分比和圈数
- const totalProgressPercent = (totalDurationMs / PROGRESS_FULL_DURATION_MS) * 100;
- const initialProgress = totalProgressPercent % 100;
- const initialLoopCount = Math.floor(totalProgressPercent / 100);
-
- debugLog('[Progress] [初始化] 设置 shouldSkipProgressAnimation = true (init)', {
- totalDurationMs,
- totalProgressPercent,
- initialProgress,
- initialLoopCount,
- });
- // 在设置进度之前,先同步 prevProgressStateRef 和 totalProgressRef,避免动画计算错误
- prevProgressStateRef.current = {
- progress: initialProgress,
- loopCount: initialLoopCount,
- };
- totalProgressRef.current = initialLoopCount * 100 + initialProgress;
- shouldSkipProgressAnimationRef.current = true;
- // 设置正确的圈数,而不是重置为 0
- setProgress(initialProgress, initialLoopCount);
- }
- }
- } catch (error) {
- // 获取用户信息失败不影响主流程,静默处理
- console.warn('获取用户信息失败:', error);
- }
- }
- // 初始化录音器
- const recorder = new AudioRecorder();
- await recorder.initialize();
- recorderRef.current = recorder;
- // 初始化播放器
- const player = new AudioPlayer();
- await player.initialize();
- // 音频即将结束前的回调:提前结束情绪/说话 GIF,避免尾部静音导致动画拖尾
- player.onBeforeEnd(() => {
- const snapshot = useAppStore.getState();
- debugLog('[AudioPlayer] onBeforeEnd: audio about to finish, early stop GIF', {
- currentState: snapshot.currentState,
- currentRequestId: snapshot.currentRequestId
- ? snapshot.currentRequestId.substring(0, 8)
- : null,
- });
- // 本次对话即将结束,提前清理情绪状态和 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 提前切回默认头像 GIF,立即生效
- flushSync(() => {
- showDefaultGifRef.current?.();
- });
- });
- // 音频开始播放回调:统一驱动情绪 GIF + talking GIF + 同步字幕显示
- player.onStart(() => {
- const appStateSnapshot = useAppStore.getState();
- const now = Date.now();
- debugLog('[AudioPlayer] 音频开始播放,准备切换情绪/说话 GIF', {
- currentState: appStateSnapshot.currentState,
- currentRequestId: appStateSnapshot.currentRequestId
- ? appStateSnapshot.currentRequestId.substring(0, 8)
- : null,
- currentEmotion: appStateSnapshot.currentEmotion,
- clientNow: now,
- });
- // 优先使用缓存的情绪(不在此处清空,在确定展示后再清,避免“情感延迟”时误判为 neutral 先播 talking)
- const cachedEmotion = pendingEmotionRef.current;
- const latestEmotion = cachedEmotion || appStateSnapshot.currentEmotion;
- const emotionCategory = getEmotionCategory(latestEmotion);
- debugLog('[AudioPlayer] onStart emotion category resolved', {
- cachedEmotion,
- latestEmotion,
- emotionCategory,
- });
- // 任何新的播放开始都应清理旧的情绪定时器,避免串台
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- debugLog('[AudioPlayer] onStart: cleared previous emotionGifTimer');
- }
- // 仅在字幕开关打开时展示字幕;用户语音不会触发此回调,因此不会显示为字幕
- if (subtitleOnRef.current && appStateSnapshot.currentState === 'playing') {
- setSubtitleVisible(true);
- } else {
- setSubtitleVisible(false);
- }
- // 用 flushSync 立即提交 GIF 状态,避免 React 批处理导致动画晚于语音 0.5~1s
- const flushShowTalking = () => flushSync(() => showTalkingGifRef.current?.());
- const flushShowPositive = () => flushSync(() => showPositiveGifRef.current?.());
- const flushShowNegative = () => flushSync(() => showNegativeGifRef.current?.());
- // 强制限定:本轮已播放过情感 GIF 则只播 talking(仅点击录音时重置,不在 onEnd 重置)
- if (emotionGifPlayedThisRoundRef.current) {
- debugLog('[AudioPlayer] onStart: 本轮已播放过情感 GIF,直接 talking');
- pendingEmotionRef.current = null;
- flushShowTalking();
- return;
- }
- // 若本段已显示过情绪 GIF(保证一次对话只播一次情感 GIF),后续只切 talking
- if (emotionGifShownForStreamRef.current) {
- debugLog('[AudioPlayer] onStart: 本段已显示过情绪 GIF,直接 talking');
- pendingEmotionRef.current = null;
- flushShowTalking();
- return;
- }
- // 已有明确正向/负向:先标记本轮已播情感(防重复),再播情感 GIF,定时结束后切 talking
- if (emotionCategory === 'positive') {
- emotionGifPlayedThisRoundRef.current = true;
- emotionGifShownForStreamRef.current = true;
- pendingEmotionRef.current = null;
- flushShowPositive();
- const duration = getEmotionGifDuration(null, 'positive');
- emotionGifTimerRef.current = window.setTimeout(() => {
- emotionGifTimerRef.current = null;
- flushShowTalking();
- debugLog('[AudioPlayer] onStart: 情感 GIF 定时结束,切 talking');
- }, duration);
- debugLog('[AudioPlayer] onStart: 已播正向情感 GIF,将在', duration, 'ms 后切 talking');
- return;
- }
- if (emotionCategory === 'negative') {
- emotionGifPlayedThisRoundRef.current = true;
- emotionGifShownForStreamRef.current = true;
- pendingEmotionRef.current = null;
- flushShowNegative();
- const duration = getEmotionGifDuration(null, 'negative');
- emotionGifTimerRef.current = window.setTimeout(() => {
- emotionGifTimerRef.current = null;
- flushShowTalking();
- debugLog('[AudioPlayer] onStart: 情感 GIF 定时结束,切 talking');
- }, duration);
- debugLog('[AudioPlayer] onStart: 已播负向情感 GIF,将在', duration, 'ms 后切 talking');
- return;
- }
- // 当前为 neutral:若尚未收到本轮情感(cached 为空),可能情感消息稍晚,延迟一帧再决定,避免先 talking 再情感再 talking
- if (cachedEmotion === null) {
- requestAnimationFrame(() => {
- const cached = pendingEmotionRef.current;
- const latest = cached ?? useAppStore.getState().currentEmotion;
- const category = getEmotionCategory(latest);
- pendingEmotionRef.current = null;
- if (emotionGifShownForStreamRef.current) {
- flushShowTalking();
- return;
- }
- if (category === 'positive') {
- emotionGifPlayedThisRoundRef.current = true;
- emotionGifShownForStreamRef.current = true;
- flushShowPositive();
- const duration = getEmotionGifDuration(null, 'positive');
- emotionGifTimerRef.current = window.setTimeout(() => {
- emotionGifTimerRef.current = null;
- flushShowTalking();
- debugLog('[AudioPlayer] onStart: 情感 GIF 定时结束,切 talking');
- }, duration);
- return;
- }
- if (category === 'negative') {
- emotionGifPlayedThisRoundRef.current = true;
- emotionGifShownForStreamRef.current = true;
- flushShowNegative();
- const duration = getEmotionGifDuration(null, 'negative');
- emotionGifTimerRef.current = window.setTimeout(() => {
- emotionGifTimerRef.current = null;
- flushShowTalking();
- debugLog('[AudioPlayer] onStart: 情感 GIF 定时结束,切 talking');
- }, duration);
- return;
- }
- emotionGifShownForStreamRef.current = true;
- flushShowTalking();
- });
- return;
- }
- // 已收到情感且为中性,直接 talking
- pendingEmotionRef.current = null;
- emotionGifShownForStreamRef.current = true;
- flushShowTalking();
- });
- // 音频播放结束回调:强制回归 default,本次对话收尾 + 隐藏字幕
- player.onEnd(() => {
- const snapshot = useAppStore.getState();
- const requestId = snapshot.currentRequestId;
- debugLog('[AudioPlayer] onEnd: audio playback finished', {
- currentState: snapshot.currentState,
- currentRequestId: requestId ? requestId.substring(0, 8) : null,
- });
- if (requestId) {
- performanceLogger.recordPlaybackEnd(requestId);
- }
- // 本次对话已结束,清理待处理情绪
- pendingEmotionRef.current = null;
- // 清理情绪 GIF 切换定时器,避免定时器稍后再次切回 talking
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- debugLog('[AudioPlayer] onEnd: cleared emotionGifTimer and reset to default GIF');
- }
- flushSync(() => {
- showDefaultGifRef.current?.();
- });
- // 播放完成后隐藏字幕并清空字幕文本
- setSubtitleVisible(false);
- setRecognizedText('');
- subtitleAccumulatorRequestIdRef.current = null;
- // 不在 onEnd 里清 responseCompleteRequestIdRef,否则 onEnd 之后才到的同轮滞后 chunk 会再次触发 onStart
- streamStartedForRequestIdRef.current = null; // 下一轮新 request 的首包可再次触发 onStart
- emotionGifShownForStreamRef.current = false;
- setState('idle');
- reset();
- });
- playerRef.current = player;
- // 初始化WebSocket前确保会话已就绪(支持用户直接刷新/直达聊天页)
- // 🔧 如果 URL 中有 OAuth 回调参数,说明正在处理登录回调,不调用 ensureSession(避免创建新用户)
- const oauthFromUrl = searchParams.get('oauth');
- const userIdFromUrl = searchParams.get('user_id');
-
- if (!oauthFromUrl || !userIdFromUrl) {
- // 只有在非 OAuth 回调时才调用 ensureSession
- try {
- await ensureSession();
- } catch (error) {
- console.error('[ChatBotPage] ensureSession 失败,无法初始化 WebSocket:', error);
- clearUserSessionAndRedirectToBegin();
- return;
- }
- } else {
- console.log(`[ChatBotPage] 检测到 OAuth 回调,跳过 ensureSession - oauth=${oauthFromUrl}, user_id=${userIdFromUrl}`);
- }
- // 初始化WebSocket(添加 user_id + token 查询参数,单活)
- const ws = new WebSocketManager();
- const token = getUserToken();
- const params = new URLSearchParams();
- if (user_id) {
- params.append('user_id', user_id);
- }
- if (token) {
- params.append('token', token);
- }
- ws.setAuth(
- { userId: user_id || undefined, token: token || undefined },
- async () => {
- // 服务端明确标记会话失效时(如在其他设备登录),直接清理本地状态并跳转到 /begin
- clearUserSessionAndRedirectToBegin();
- return false;
- }
- );
- const wsUrl = params.toString() ? `${WS_URL}?${params.toString()}` : WS_URL;
- ws.connect(wsUrl, (connected) => {
- // 如果组件已卸载,不执行任何操作
- if (!isMountedRef.current) {
- return;
- }
-
- const appState = useAppStore.getState();
- const wasConnected = appState.isConnected;
-
- setConnected(connected);
-
- if (connected) {
- // 记录WebSocket连接建立时间
- performanceLogger.recordWebSocketConnected();
-
- // 如果这是首次连接成功,处理 TapToChat 提示
- if (!connectionLostRef.current) {
- const hasShown = getStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT);
- if (!hasShown && showTapToChat) {
- // 第一次连接成功,保存标记
- setStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT, 'true');
-
- // 同步到后端 UI 状态(如果已有 user_id)
- const userId = getUserId();
- if (userId) {
- updateUserUIState(userId, {
- has_shown_tap_to_chat: true,
- }).catch(() => {
- // 同步失败不影响前端提示展示
- });
- }
- } else if (hasShown) {
- // 如果已经标记为已显示(可能是从后端同步的),现在 WebSocket 已连接,可以安全隐藏
- setShowTapToChat(false);
- }
- }
-
- // 如果在 WebSocket 初始化完成之前已经根据亲密度逻辑决定需要触发首句 greeting,
- // 则在连接成功且未被亲密度弹窗/用户录音拦截时,补发一次 start_greeting。
- if (
- pendingGreetingRef.current &&
- !hasGreetingStartedRef.current &&
- !greetingSuppressedRef.current &&
- !delayGreetingRef.current
- ) {
- debugLog('[首句] WebSocket 连接成功且存在待发送的首句 greeting,立即触发 start_greeting');
- startGreeting();
- }
- if (connectionLostRef.current) {
- antMessage.success(tCommon('voiceServiceRestored'));
- connectionLostRef.current = false;
- recorderRef.current?.stop();
- resetFrequencyVisualization();
- playerRef.current?.stop();
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- reset();
- setError(null);
- }
- return;
- }
-
- if (!wasConnected) {
- // 初次连接失败,静默等待自动重连
- return;
- }
-
- connectionLostRef.current = true;
-
- if (appState.currentRequestId) {
- performanceLogger.clearRequest(appState.currentRequestId, 'websocket_disconnected');
- }
-
- recorderRef.current?.stop();
- resetFrequencyVisualization();
- playerRef.current?.stop();
-
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
-
- antMessage.error(tCommon('voiceServiceDisconnected'));
- setError(tCommon('voiceServiceDisconnected'));
- });
- ws.onMessage('app', handleMessage);
- wsRef.current = ws;
- } catch (error) {
- antMessage.error(tCommon('initFailedCheckMic'));
- setError(tCommon('initFailedCheckMic'));
- }
- };
- init();
- return () => {
- // 标记组件已卸载,防止 WebSocket 回调显示错误消息
- isMountedRef.current = false;
- recorderRef.current?.release();
- playerRef.current?.release();
- wsRef.current?.disconnect();
- resetFrequencyVisualization();
- if (sendingTimeoutRef.current) {
- clearTimeout(sendingTimeoutRef.current);
- }
- if (animationFrameRef.current) {
- cancelAnimationFrame(animationFrameRef.current);
- }
- if (progressBarTooltipTimerRef.current) {
- clearTimeout(progressBarTooltipTimerRef.current);
- }
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- }
- // 组件卸载时不再保留任何待处理情绪,避免内存中残留过期状态
- pendingEmotionRef.current = null;
- };
- }, [resetFrequencyVisualization]);
- // 处理WebSocket消息
- const handleMessage = (message: Message) => {
- const requestId = message.requestId || currentRequestId;
- if (!requestId) {
- console.warn('[ChatBotPage] 收到缺少 requestId 的消息,已忽略', message.type);
- return;
- }
- const activeRequestId = activeRequestIdRef.current;
- const isCancelledRequest = cancelledRequestIdsRef.current.has(requestId);
-
- // 🔥 首句消息特殊处理(requestId 以 "greeting_" 开头)
- const isGreetingMessage = requestId.startsWith('greeting_');
- // 如果亲密度弹窗正在展示,则不处理任何首句相关消息(文本/情绪/音频)
- if (isGreetingMessage && delayGreetingRef.current) {
- debugLog(
- `[首句] [${requestId.substring(
- 0,
- 8,
- )}] 亲密度弹窗展示中,忽略首句消息: ${message.type}`,
- );
- return;
- }
- // 记录首句 requestId,便于后续在开始录音时发送 cancel
- if (isGreetingMessage && !greetingRequestIdRef.current) {
- greetingRequestIdRef.current = requestId;
- }
- // 如果用户已经开始录音且选择“以用户为准”,则直接丢弃所有首句相关消息
- if (isGreetingMessage && greetingSuppressedRef.current) {
- debugLog(`[首句] [${requestId.substring(0, 8)}] 已被用户录音打断,忽略首句消息: ${message.type}`);
- return;
- }
- if (isCancelledRequest && !isGreetingMessage) {
- if (message.type === 'audio_response' && message.isLast) {
- cancelledRequestIdsRef.current.delete(requestId);
- }
- debugLog(`[${message.type}] [${requestId.substring(0, 8)}] 已取消的请求,忽略响应`);
- return;
- }
-
- switch (message.type) {
- case 'text_result': {
- // 仅拼接 AI 返回的文本到字幕;用户 STT(source=user)不参与字幕
- if (message.source === 'user') {
- break;
- }
- const cleaned = cleanSubtitleText(message.text);
- // 🔥 首句消息:直接处理,不检查 activeRequestId
- if (isGreetingMessage) {
- if (message.isFinal) {
- debugLog(`[首句文本] [${requestId.substring(0, 8)}] ${cleaned}`);
- if (subtitleAccumulatorRequestIdRef.current !== requestId) {
- subtitleAccumulatorRequestIdRef.current = requestId;
- setRecognizedText(cleaned);
- } else {
- const prev = useAppStore.getState().recognizedText;
- setRecognizedText(prev ? `${prev} ${cleaned}` : cleaned);
- }
- }
- break;
- }
-
- if (activeRequestId !== null && requestId !== activeRequestId) {
- debugLog(`[文本结果] [${requestId.substring(0, 8)}] 请求ID不匹配,丢弃旧请求的文本结果`);
- break;
- }
-
- if (message.isFinal) {
- performanceLogger.recordFinalText(requestId, message.text, message.timestamp);
- } else if (!performanceLogger.hasFirstText(requestId)) {
- performanceLogger.recordFirstText(requestId, message.text, message.timestamp);
- }
- // 多段音频文字拼接:同一次对话(同一 requestId)追加,新请求则替换
- if (subtitleAccumulatorRequestIdRef.current !== requestId) {
- subtitleAccumulatorRequestIdRef.current = requestId;
- setRecognizedText(cleaned);
- } else {
- const prev = useAppStore.getState().recognizedText;
- setRecognizedText(prev ? `${prev} ${cleaned}` : cleaned);
- }
- break;
- }
- case 'user_level':
- if (typeof message.level === 'number') {
- syncUserLevel(message.level);
- }
- // 🔥 使用后端返回的 totalDurationMs 同步进度条,确保与数据库一致
- if (typeof message.totalDurationMs === 'number' && message.totalDurationMs > 0) {
- const PROGRESS_FULL_DURATION_MS = 30 * 1000; // 30000ms
- // 满足解锁阈值时实时解锁,避免必须刷新页面
- if (message.totalDurationMs >= AVATAR_C_UNLOCK_THRESHOLD_MS && !avatarCUnlockedRef.current) {
- unlockAvatarC();
- }
- // 更新本地累加器,确保与数据库一致
- totalSpeechDurationRef.current = Math.max(
- message.totalDurationMs,
- avatarCUnlockedRef.current ? AVATAR_C_UNLOCK_THRESHOLD_MS : 0
- );
- // 根据总时长计算进度条位置(只显示非整数圈的进度)
- const totalProgressPercent = (message.totalDurationMs / PROGRESS_FULL_DURATION_MS) * 100;
- const progress = totalProgressPercent % 100;
-
- // 🔍 检查当前状态,如果用户刚刚更新了进度,不要覆盖用户的更新
- const currentState = useAppStore.getState();
- const currentTotal = currentState.progressLoopCount * 100 + currentState.conversationProgress;
- const newTotal = Math.floor(totalProgressPercent / 100) * 100 + progress;
-
- debugLog('[Progress] [user_level] 收到后端同步请求', {
- totalDurationMs: message.totalDurationMs,
- progress,
- currentTotal,
- newTotal,
- requestId: requestId?.substring(0, 8),
- shouldSync: Math.abs(currentTotal - newTotal) > 0.1, // 只有差异较大时才同步
- });
-
- // 只有在差异较大时才同步(避免覆盖用户刚刚的更新)
- if (Math.abs(currentTotal - newTotal) > 0.1) {
- // 计算应该保持的圈数(基于总时长)
- const targetLoopCount = Math.floor(totalProgressPercent / 100);
- // 只在初始化时跳过动画(如果当前进度接近0)
- const isInitialSync = currentTotal < 1;
- if (isInitialSync) {
- debugLog('[Progress] [user_level] 初始化同步,跳过动画但同步进度');
- shouldSkipProgressAnimationRef.current = true;
- }
- // 无论是否初始化,都同步进度值,动画是否播放由 shouldSkipProgressAnimationRef 控制
- debugLog('[Progress] [user_level] 同步进度,设置进度值:', {
- progress,
- targetLoopCount,
- });
- // 保持当前的圈数,不重置为0
- setProgress(progress, targetLoopCount);
- } else {
- debugLog('[Progress] [user_level] 差异太小,跳过同步');
- }
- }
- break;
- case 'emotion':
- // 🔥 首句消息:直接处理,不检查 activeRequestId
- if (isGreetingMessage) {
- performanceLogger.recordEmotion(requestId, message.emotion, message.timestamp);
- setEmotion(message.emotion);
- // 🔥 仅缓存情绪,不立即切换 GIF,等待首句音频真正开始播放时再驱动动画
- pendingEmotionRef.current = message.emotion;
- break;
- }
-
- // 如果当前状态是 recording,且 requestId 不匹配当前请求,说明这是旧请求的返回,直接丢弃
- // 如果 activeRequestId 为 null,说明是新请求的开始,允许处理
- if (activeRequestId !== null && requestId !== activeRequestId) {
- debugLog(`[情绪] [${requestId.substring(0, 8)}] 请求ID不匹配,丢弃旧请求的情绪`);
- break;
- }
-
- performanceLogger.recordEmotion(requestId, message.emotion, message.timestamp);
- setEmotion(message.emotion);
- // 🔥 普通情绪消息同样只缓存,真正的情绪动画在音频开始播放时统一处理
- pendingEmotionRef.current = message.emotion;
- break;
- case 'audio_response':
- // 🔥 首句消息:直接处理,不检查状态和 activeRequestId
- if (isGreetingMessage) {
- // 首句音频:自动播放
- if (currentState !== 'playing') {
- const now = Date.now();
- emotionGifShownForStreamRef.current = false; // 新流开始,允许本段显示情绪 GIF
- debugLog(`[音频响应][首句] [${requestId.substring(0, 8)}] 首次音频块,进入 playing 状态`, {
- messageTimestamp: message.timestamp,
- clientNow: now,
- delayMs: typeof message.timestamp === 'number' ? now - message.timestamp : null,
- });
- performanceLogger.recordFirstAudio(requestId, message.timestamp);
- performanceLogger.recordPlaybackStart(requestId);
- setState('playing');
- }
- // 标记当前处于首句播放阶段,便于后续开始录音时精确打断
- isGreetingActiveRef.current = true;
- if (message.data && playerRef.current) {
- if (responseCompleteRequestIdRef.current !== null && responseCompleteRequestIdRef.current !== requestId) {
- responseCompleteRequestIdRef.current = null;
- }
- const audioData = atob(message.data);
- const audioBytes = new Uint8Array(audioData.length);
- for (let i = 0; i < audioData.length; i++) {
- audioBytes[i] = audioData.charCodeAt(i);
- }
- // 同一 request 只对「首包」触发 onStart,后续包(含第二段、第三段音频)一律 skipStreamReset
- const skipReset =
- streamStartedForRequestIdRef.current === requestId ||
- (responseCompleteRequestIdRef.current !== null && responseCompleteRequestIdRef.current === requestId);
- playerRef.current.addChunk(audioBytes, message.sampleRate || 24000, { skipStreamReset: skipReset });
- if (!skipReset) streamStartedForRequestIdRef.current = requestId;
- }
- if (message.isLast) {
- responseCompleteRequestIdRef.current = requestId;
- performanceLogger.recordLastAudio(requestId);
- playerRef.current?.markStreamEnd();
- isGreetingActiveRef.current = false;
- greetingRequestIdRef.current = null;
- }
- break;
- }
- // 如果当前状态是 recording,说明用户已经点击了录音按钮,忽略后续的音频响应
- if (currentState === 'recording') {
- debugLog(`[音频响应] [${requestId.substring(0, 8)}] 用户已开始录音,忽略音频响应`);
- break;
- }
-
- // 如果 currentRequestId 不为 null,且 requestId 不匹配当前请求,说明这是旧请求的返回,直接丢弃
- // 如果 activeRequestId 为 null,说明是新请求的开始,允许处理
- if (activeRequestId !== null && requestId !== activeRequestId) {
- debugLog(`[音频响应] [${requestId.substring(0, 8)}] 请求ID不匹配,丢弃旧请求的音频响应`, {
- activeRequestId: activeRequestId ? activeRequestId.substring(0, 8) : null,
- messageIsLast: message.isLast,
- });
- break;
- }
-
- // 清除发送超时
- if (sendingTimeoutRef.current) {
- clearTimeout(sendingTimeoutRef.current);
- sendingTimeoutRef.current = null;
- }
-
- if (currentState !== 'playing') {
- const now = Date.now();
- emotionGifShownForStreamRef.current = false; // 新流开始,允许本段显示情绪 GIF
- debugLog(`[音频响应] [${requestId.substring(0, 8)}] 首次音频块,进入 playing 状态`, {
- messageTimestamp: message.timestamp,
- clientNow: now,
- delayMs: typeof message.timestamp === 'number' ? now - message.timestamp : null,
- });
- performanceLogger.recordFirstAudio(requestId, message.timestamp);
- performanceLogger.recordPlaybackStart(requestId);
- setState('playing');
- }
- if (message.data) {
- if (responseCompleteRequestIdRef.current !== null && responseCompleteRequestIdRef.current !== requestId) {
- responseCompleteRequestIdRef.current = null;
- }
- const audioData = atob(message.data);
- const audioBytes = new Uint8Array(audioData.length);
- for (let i = 0; i < audioData.length; i++) {
- audioBytes[i] = audioData.charCodeAt(i);
- }
- debugLog(`[音频响应] [${requestId.substring(0, 8)}] 收到音频数据块`, {
- bytes: audioBytes.length,
- sampleRate: message.sampleRate || 24000,
- isLast: message.isLast,
- });
- // 同一 request 只对「首包」触发 onStart,后续包(第二段、第三段音频及滞后 chunk)一律 skipStreamReset
- const skipReset =
- streamStartedForRequestIdRef.current === requestId ||
- (responseCompleteRequestIdRef.current !== null && responseCompleteRequestIdRef.current === requestId);
- playerRef.current?.addChunk(audioBytes, message.sampleRate || 24000, {
- skipStreamReset: skipReset,
- });
- if (!skipReset) streamStartedForRequestIdRef.current = requestId;
- }
- if (message.isLast) {
- // 整个 AI 返回结束:仅在此刻标记流结束;对话结束(idle)由 onEnd 在全部播完后触发
- responseCompleteRequestIdRef.current = requestId;
- debugLog(`[音频响应] [${requestId.substring(0, 8)}] 收到 isLast=true,标记音频流结束`);
- performanceLogger.recordLastAudio(requestId);
- playerRef.current?.markStreamEnd();
- // 进度已在发送时增加,这里不再重复增加
- }
- break;
- case 'energy_stone_spawn':
- handleEnergyStoneSpawn(message);
- break;
- case 'error':
- console.error(`[错误] [${requestId?.substring(0, 8) || ''}]`, message.message, message.code);
- // 静默处理后端错误提示,避免打扰用户
- debugLog('[ServiceError]', message.message, message.code);
- setError(message.message);
- if (message.code === 'SESSION_INVALIDATED') {
- // 会话在其他设备被顶掉:清理会话并统一跳转到 /begin
- wsRef.current?.disconnect();
- antMessage.error(tCommon('sessionLoggedInElsewhere'));
- clearUserSessionAndRedirectToBegin();
- return;
- }
- // 清理情绪 GIF 切换定时器
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- performanceLogger.clearRequest(requestId, `${message.code}: ${message.message}`);
- break;
- case 'pong':
- break;
- default:
- console.warn(`[未知消息] [${requestId?.substring(0, 8) || ''}]`, message.type);
- break;
- }
- };
- // 开始录音
- const handleStartRecord = async () => {
- setShowFuncMenuPopup(false);
- // 每轮录音开始前将对话层形象置为 default,避免上一轮 talking 残留(不用 key 防闪烁)
- // 用 flushSync 同步提交,否则立即点击时与 setState('recording') 被批量更新,对话层仍用上一帧 talking 渲染
- flushSync(() => {
- showDefaultGifRef.current?.();
- });
- // 如果正在录音,忽略
- if (currentState === 'recording') {
- return;
- }
-
- // 🔥 改进:允许在连接建立过程中开始录音
- // 1. 如果 WebSocket 不存在,说明还未初始化,提示等待
- // 2. 如果 WebSocket 存在,检查是否正在连接中或已就绪
- // 3. 如果正在连接中(CONNECTING)或已就绪(OPEN),允许开始录音,消息会被缓冲
- // 4. 这样用户无感知,业务也能正常运行
- if (!wsRef.current) {
- antMessage.warning(tCommon('voiceServiceInitializing'));
- return;
- }
- // 检查 WebSocket 状态:如果正在连接中或已就绪,允许开始录音
- const isConnecting = wsRef.current.isConnecting();
- const isReady = wsRef.current.isReady();
-
- // 如果既不在连接中,也不已就绪,且 isConnected 为 false,说明连接失败
- if (!isConnecting && !isReady && !isConnected) {
- // 静默提示:语音服务重连中
- debugLog('[SendGuard] 语音服务正在重连');
- return;
- }
-
- // 如果正在连接中或已就绪,允许开始录音(消息会被缓冲)
-
- // 保存旧请求ID(用于取消和过滤旧消息)
- const oldRequestId = currentRequestId;
- const wasPlaying = currentState === 'playing' || currentState === 'sending';
-
- // 如果正在播放,先停止播放并重置状态
- if (wasPlaying) {
- // 停止音频播放(包括可能正在播放的首句)
- playerRef.current?.stop();
-
- // 清理情绪 GIF 切换定时器
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
-
- // 立即恢复默认头像 GIF
- showDefaultGif();
-
- // 取消当前的请求(如果有),丢弃上一次请求的返回
- if (oldRequestId) {
- wsRef.current?.sendCancel(oldRequestId);
- cancelledRequestIdsRef.current.add(oldRequestId);
- performanceLogger.clearRequest(oldRequestId, '用户中断播放开始新录音');
- }
-
- // 清理旧请求的状态(丢弃上一次请求的返回)
- setRecognizedText('');
- subtitleAccumulatorRequestIdRef.current = null;
- setEmotion('neutral');
-
- // 清理发送超时
- if (sendingTimeoutRef.current) {
- clearTimeout(sendingTimeoutRef.current);
- sendingTimeoutRef.current = null;
- }
- }
-
- // 其他状态(idle/error/sending)都允许开始录音
- // 一旦用户主动开始录音,则以用户为准:后续所有首句 greeting 消息全部丢弃
- greetingSuppressedRef.current = true;
- // 如果此时已经拿到首句的 requestId,则主动向后端发送 cancel,节省资源
- if (greetingRequestIdRef.current) {
- const greetingId = greetingRequestIdRef.current;
- wsRef.current?.sendCancel(greetingId);
- cancelledRequestIdsRef.current.add(greetingId);
- debugLog(`[首句] [${greetingId.substring(0, 8)}] 用户开始录音,发送 cancel 终止首句`);
- }
- // 首次点击录音按钮,隐藏 TapToChat 提示并保存标记
- if (showTapToChat) {
- setShowTapToChat(false);
- // 确保标记已保存(防止 WebSocket 连接较慢时未保存)
- const hasShown = getStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT);
- if (!hasShown) {
- setStorage(STORAGE_KEYS.HAS_SHOWN_TAP_TO_CHAT, 'true');
- // 同步到后端 UI 状态(如果已有 user_id)
- const userId = getUserId();
- if (userId) {
- updateUserUIState(userId, {
- has_shown_tap_to_chat: true,
- }).catch(() => {
- // 同步失败不影响主流程
- });
- }
- }
- }
- // 点击录音按钮时,隐藏进度条提示
- dismissProgressBarTooltip();
- // 🔥 清理播放器状态,确保上一次对话的残留状态被重置
- playerRef.current?.stop();
- // 生成新的请求ID并立即设置,确保后续消息能正确匹配
- const requestId = uuidv4();
- performanceLogger.startRequest(requestId);
- updateRequestId(requestId);
- setState('recording');
- chunkIndexRef.current = 0;
- setRecognizedText('');
- subtitleAccumulatorRequestIdRef.current = null;
- // 新一轮对话开始,允许本次 AI 回复播报时再播放一次情感 GIF
- emotionGifShownForStreamRef.current = false;
- emotionGifPlayedThisRoundRef.current = false;
- // 准备移动端音频(在设置状态之后,避免阻塞状态更新)
- // 🔥 改进:静默准备音频环境,不显示提示,用户无感知
- if (isMobileDevice() && !mobileAudioPreparedRef.current) {
- // 异步准备,不阻塞录音开始
- prepareMobileAudio()
- .then(() => {
- requestVolumeControl();
- mobileAudioPreparedRef.current = true;
- // 移除提示,让用户无感知,业务功能正常(prepareMobileAudio 和 requestVolumeControl 仍会执行)
- })
- .catch(() => {
- // 准备移动端音频失败,静默处理
- });
- }
-
- timingRef.current = {
- recordStart: Date.now(),
- recordEnd: 0,
- firstAudioReceived: 0,
- emotionReceived: 0,
- };
- // 立即启动录音,确保第一次点击就能开始
- try {
- await recorderRef.current?.start((pcmData) => {
- // 检查当前状态,如果已经不是recording,说明用户可能又点击了,忽略
- const currentStateCheck = useAppStore.getState().currentState;
- if (currentStateCheck !== 'recording') {
- return;
- }
-
- if (chunkIndexRef.current === 0) {
- performanceLogger.recordFirstChunkSent(requestId);
- }
- const uint8Array = new Uint8Array(pcmData.buffer);
- const base64 = btoa(String.fromCharCode(...Array.from(uint8Array)));
- wsRef.current?.sendAudioChunk(requestId, base64, chunkIndexRef.current);
- chunkIndexRef.current++;
- }, pushFrequencyFrame);
-
- // 录音启动成功,开始计时
- startRecordingTimer();
- } catch (error) {
- console.error(`[录音] [${requestId.substring(0, 8)}] 启动失败`, error);
- antMessage.error(tCommon('micStartFailed'));
- performanceLogger.clearRequest(requestId, 'recorder_start_failed');
- resetFrequencyVisualization();
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- setState('idle');
- reset();
- return;
- }
- };
- // 发送录音
- const handleSend = () => {
- if (currentState !== 'recording' || !currentRequestId) {
- return;
- }
- stopRecordingTimer();
-
- // 🔥 改进:允许在连接建立过程中发送录音
- // 1. 如果 WebSocket 不存在,说明还未初始化,提示错误
- // 2. 如果 WebSocket 存在,检查是否正在连接中或已就绪
- // 3. 如果正在连接中(CONNECTING)或已就绪(OPEN),允许发送,消息会被缓冲
- // 4. 这样用户无感知,业务也能正常运行
- if (!wsRef.current) {
- // 静默处理:语音服务初始化中
- debugLog('[SendGuard] 语音服务初始化中');
- recorderRef.current?.stop();
- resetFrequencyVisualization();
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- performanceLogger.clearRequest(currentRequestId, 'websocket_unready_before_send');
- reset();
- return;
- }
- // 检查 WebSocket 状态:如果正在连接中或已就绪,允许发送
- const isConnecting = wsRef.current.isConnecting();
- const isReady = wsRef.current.isReady();
-
- // 如果既不在连接中,也不已就绪,且 isConnected 为 false,说明连接失败
- if (!isConnecting && !isReady && !isConnected) {
- // 静默处理:语音服务未连接
- debugLog('[SendGuard] 语音服务未连接');
- recorderRef.current?.stop();
- resetFrequencyVisualization();
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- performanceLogger.clearRequest(currentRequestId, 'websocket_disconnected_before_send');
- reset();
- return;
- }
-
- // 如果正在连接中或已就绪,允许发送(消息会被缓冲)
- timingRef.current.recordEnd = Date.now();
- sendTimeRef.current = Date.now();
- performanceLogger.recordEnd(currentRequestId, chunkIndexRef.current);
- // 计算说话时长(毫秒)
- const speechDuration = timingRef.current.recordEnd - timingRef.current.recordStart;
-
- // 进度条与累计说话时长以后端为准:
- // 这里只负责将本次说话时长发送给后端,不在前端进行乐观更新,
- // 后端在成功处理并持久化 total_speech_duration_ms 后,会通过 totalDurationMs 同步最新进度。
- if (speechDuration > 0 && shouldSkipProgressAnimationRef.current) {
- debugLog('[Progress] [handleSend] 初始化阶段结束,后续进度同步以后端为准', {
- speechDurationMs: speechDuration,
- });
- shouldSkipProgressAnimationRef.current = false;
- }
- recorderRef.current?.stop();
- resetFrequencyVisualization();
- // 发送音频结束消息,包含说话时长信息
- wsRef.current?.sendAudioEnd(currentRequestId, chunkIndexRef.current, speechDuration);
- setState('sending');
-
- // 设置超时保护:10秒后如果还在 sending 或 playing 状态,自动重置
- if (sendingTimeoutRef.current) {
- clearTimeout(sendingTimeoutRef.current);
- }
- sendingTimeoutRef.current = window.setTimeout(() => {
- const state = useAppStore.getState().currentState;
- if (state === 'sending' || state === 'playing') {
- const shortId = currentRequestId ? currentRequestId.substring(0, 8) : '';
- console.warn(`[超时] [${shortId}] 响应超时,自动重置`);
- // 静默处理超时提示
- debugLog('[Timeout] 响应超时,自动重置');
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- setState('idle');
- reset();
- performanceLogger.clearRequest(currentRequestId, '响应超时');
- }
- }, 10000);
- };
- handleSendRef.current = handleSend;
- // 取消录音
- const handleCancel = () => {
- if (currentState !== 'recording' || !currentRequestId) return;
- const shortId = currentRequestId.substring(0, 8);
- debugLog(`[取消] [${shortId}] 取消录音`);
- recorderRef.current?.stop();
- resetFrequencyVisualization();
- stopRecordingTimer();
- // 清理解码中的情绪状态与 GIF 切换定时器
- pendingEmotionRef.current = null;
- if (emotionGifTimerRef.current) {
- clearTimeout(emotionGifTimerRef.current);
- emotionGifTimerRef.current = null;
- }
- // 恢复默认头像 GIF
- showDefaultGif();
- wsRef.current?.sendCancel(currentRequestId);
- cancelledRequestIdsRef.current.add(currentRequestId);
- performanceLogger.clearRequest(currentRequestId);
- reset();
- };
- const currentAvatarAlt = currentState === 'playing' ? 'AnimaZone Avatar Animated' : 'AnimaZone Avatar';
- const energyStoneAssets: Record<'mission' | 'conversation', string> = {
- mission: missionEnergyStone,
- conversation: conversationEnergyStone,
- };
- const energyStoneHintAssets: Record<'mission' | 'conversation', string> = {
- mission: missionEnergyStoneHint,
- conversation: conversationEnergyStoneHint,
- };
- const handleEnergyStoneSpawn = useCallback(
- (payload: EnergyStoneSpawnMessage) => {
- // 展示能量石
- spawnStone(payload);
- // 如果是对话能量石,刷新一次顶部的数量展示
- if (payload.stoneType === 'conversation') {
- const uid = getUserId();
- if (uid) {
- fetchConversationStoneCount(uid);
- }
- }
- },
- [spawnStone, fetchConversationStoneCount]
- );
- // 根据背景图片获取对应的树木装饰图片URL(默认背景下录音时切到 bg-chatting.png,发送/取消后恢复)
- const getTreesImage = (): string | null => {
- const bgId = getCurrentBackgroundImageId();
- const isDefaultBg = !bgId || bgId === 'default';
- if (isDefaultBg && currentState === 'recording') {
- return bgChattingUrl;
- }
- // 实时从 localStorage 读取最新的背景图片URL,使用背景图片作为树木装饰
- const currentBgUrl = getCurrentBackgroundImageUrl() || backgroundImageUrl;
- if (currentBgUrl && currentBgUrl.includes('init.svg')) {
- // 如果是旧的 init.svg,强制替换为 init1.svg
- return getOssUrl('init1.svg');
- }
- return currentBgUrl;
- };
- // 根据背景图片ID获取树木装饰图片的样式配置
- const getTreesImageStyle = (): React.CSSProperties => {
- const baseStyle: React.CSSProperties = {
- width: '100%',
- height: '100%',
- top: 0,
- left: 0,
- objectFit: 'cover',
- zIndex: 1,
- };
- // 从 localStorage 读取透明度配置(从数据库metadata中获取)
- const opacity = getCurrentBackgroundImageOpacity();
- return { ...baseStyle, opacity };
- };
- const defaultGifUrl = avatarGifSet?.default ?? '';
- // 双 img 固定角色:default 层永远 default;对话层 playing 时播 emotion/talking
- // 当对话层切换到下面(idle)时,直接把对话层 src 设为 default,下次对话无需再关心其是否已恢复默认
- // 仅在发送/播放时把动画/对话层置顶,录音期间保持 default 层在上,多留时间消化上一轮残留
- const showConversationOnTop = currentState === 'sending' || currentState === 'playing';
- const conversationLayerSrc = currentState === 'playing' ? (currentAvatarGif || defaultGifUrl) : defaultGifUrl;
- return (
- <div
- style={{
- position: 'relative',
- width: '100%',
- minHeight: '100dvh',
- }}
- >
- {/* 树木装饰 - 根据背景图片调整图片和样式 */}
- {getTreesImage() && (
- <img
- src={getTreesImage() || undefined}
- alt={tCommon('a11y.trees')}
- className="chatbot-trees absolute pointer-events-none"
- style={getTreesImageStyle()}
- />
- )}
- {/* 隐藏的能量石容器 - 用于 useEnergyStones hook 计算位置 */}
- <div
- ref={hiddenEnergyStoneZoneRef}
- style={{
- position: 'absolute',
- width: px2vmin(343), // 设计稿 343px,基于 vw/vh 最小值
- height: px2vmin(172), // 设计稿 172px,基于 vw/vh 最小值
- top: px2vmin(126), // 设计稿 top 126px,基于 vw/vh 最小值
- left: '50%',
- transform: 'translateX(-50%)',
- visibility: 'hidden',
- pointerEvents: 'none',
- zIndex: -1,
- }}
- />
- {/* 亲密度 + 对话能量石状态(V2 设计稿 393×852,基于 min(vw, vh)) */}
- <div
- style={{
- position: 'absolute',
- top: px2vmin(115, 'v2'),
- left: px2vmin(24, 'v2'),
- width: px2vmin(70, 'v2'),
- height: px2vmin(54, 'v2'),
- backgroundColor: 'rgba(0, 0, 0, 0.4)',
- borderRadius: px2vmin(8, 'v2'),
- boxSizing: 'border-box',
- zIndex: 6,
- }}
- >
- {/* 亲密度心形展示:顶部 6,宽 58,高 14,左右居中 */}
- <div
- style={{
- position: 'absolute',
- top: px2vmin(6, 'v2'),
- left: '50%',
- transform: 'translateX(-50%)',
- width: px2vmin(58, 'v2'),
- height: px2vmin(14, 'v2'),
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}
- >
- {Array.from({ length: 3 }, (_, index) => {
- const isFilled = index < Math.max(0, Math.min(3, intimacyHeartCount));
- return (
- <img
- key={index}
- src={isFilled ? heartFilled : heartBroken}
- alt={isFilled ? 'heart' : 'heart-broken'}
- style={{
- width: px2vmin(14, 'v2'),
- height: px2vmin(14, 'v2'),
- objectFit: 'contain',
- }}
- />
- );
- })}
- </div>
- {/* 对话能量石数量:顶部 24,宽 55,左右居中,点击弹出对话能量石说明弹窗 */}
- <div
- role="button"
- tabIndex={0}
- onClick={() => {
- setEnergyStoneModalType('conversation');
- setShowMissionStoneModal(true);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- setEnergyStoneModalType('conversation');
- setShowMissionStoneModal(true);
- }
- }}
- style={{
- position: 'absolute',
- top: px2vmin(24, 'v2'),
- left: '50%',
- transform: 'translateX(-50%)',
- width: px2vmin(55, 'v2'),
- cursor: 'pointer',
- }}
- >
- <img
- src={conversationEnergyStoneCountBg}
- alt={tProfile('chatStoneTitle')}
- style={{
- width: '100%',
- height: '100%',
- objectFit: 'contain',
- display: 'block',
- }}
- />
- <span
- style={{
- position: 'absolute',
- top: '50%',
- left: '70%',
- transform: 'translate(-50%, -50%)',
- fontSize: px2vmin(10, 'v2'),
- color: '#000',
- fontWeight: 500,
- whiteSpace: 'nowrap',
- }}
- >
- {conversationStoneCount > 999 ? '999+' : conversationStoneCount}
- </span>
- </div>
- </div>
- {/* 能量石展示区域 - 已废弃,能量石现在独立定位,不再嵌套在此容器中 */}
- {/* <div
- className="chatbot-energy-zone absolute"
- style={{
- width: px2vmin(343), // 设计稿 343px,基于 vw/vh 最小值
- height: px2vmin(172), // 设计稿 172px,基于 vw/vh 最小值
- top: px2vmin(126), // 设计稿 top 126px,基于 vw/vh 最小值
- left: '50%',
- transform: 'translateX(-50%)',
- zIndex: 4,
- pointerEvents: 'none',
- }}
- >
- <div className="energy-stone-layer" />
- </div> */}
- {/* 正式能量石 - 仅渲染对话能量石,不渲染任务能量石 */}
- {energyStones
- .filter((stone) => stone.stoneType === 'conversation')
- .map((stone) => {
- const asset = energyStoneAssets[stone.stoneType];
- const hintAsset = energyStoneHintAssets[stone.stoneType];
- const stoneSize = 48; // 设计稿 48px,基于 vw/vh 最小值
- const hintSize = 92; // 设计稿 92px,基于 vw/vh 最小值
- const shouldShowHint = stone.stoneType === 'mission'
- ? !hasClickedMissionStone
- : !hasClickedConversationStone;
-
- // 计算绝对位置:基于能量石区域的边界
- // 区域:left 50% translateX(-50%), top: px2vmin(126), width: px2vmin(343), height: px2vmin(172)
- // 能量石在区域内的百分比位置转换为绝对位置
- // left: 50% + (xRatio - 0.5) * zoneWidth
- // top: zoneTop + yRatio * zoneHeight
- const zoneTop = px2vmin(126);
- const zoneWidth = px2vmin(343);
- const zoneHeight = px2vmin(172);
- const absoluteLeft = `calc(50% + (${stone.position.xRatio} - 0.5) * ${zoneWidth})`;
- const absoluteTop = `calc(${zoneTop} + ${stone.position.yRatio} * ${zoneHeight})`;
-
- return (
- <div
- key={stone.stoneId}
- data-stone-id={stone.stoneId}
- data-fading={stone.fading ? 'true' : 'false'}
- className={`energy-stone-container ${stone.stoneType === 'mission' ? 'energy-stone-mission' : ''}`}
- style={{
- position: 'absolute',
- left: absoluteLeft,
- top: absoluteTop,
- transform: 'translate(-50%, -50%)',
- width: px2vmin(stoneSize),
- height: px2vmin(stoneSize),
- pointerEvents: 'auto',
- cursor: 'pointer',
- zIndex: 5,
- }}
- >
- {/* 光晕层 - 只在未点击时显示,但在动画过程中也显示以跟随能量石 */}
- {shouldShowHint && (
- <img
- src={hintAsset}
- alt=""
- className="energy-stone-hint"
- style={{
- position: 'absolute',
- top: '50%',
- left: '50%',
- transform: 'translate(-50%, -50%)',
- transformOrigin: 'center center',
- width: px2vmin(hintSize),
- height: px2vmin(hintSize),
- pointerEvents: 'none',
- zIndex: 0,
- opacity: stone.fading ? 0 : undefined, // 动画过程中逐渐消失
- maxWidth: 'none',
- maxHeight: 'none',
- objectFit: 'contain',
- }}
- />
- )}
- {/* 能量石按钮 */}
- <button
- type="button"
- className="energy-stone"
- data-type={stone.stoneType}
- data-fading={stone.fading ? 'true' : 'false'}
- style={{
- position: 'absolute',
- top: '50%',
- left: '50%',
- transform: 'translate(-50%, -50%)',
- transformOrigin: 'center center',
- width: px2vmin(stoneSize),
- height: px2vmin(stoneSize),
- zIndex: stone.fading ? 100 : 1,
- pointerEvents: stone.fading ? 'none' : 'auto',
- }}
- onClick={async () => {
- // 更新点击状态(控制光晕显示)
- const clickedStorageKey = stone.stoneType === 'mission'
- ? STORAGE_KEYS.HAS_CLICKED_MISSION_STONE
- : STORAGE_KEYS.HAS_CLICKED_CONVERSATION_STONE;
-
- const hasClicked = getStorage(clickedStorageKey);
- const isFirstClick = hasClicked !== 'true';
-
- // 检查是否是第一次点击,决定是否显示弹窗
- const storageKey = stone.stoneType === 'mission'
- ? STORAGE_KEYS.HAS_SHOWN_MISSION_STONE_MODAL
- : STORAGE_KEYS.HAS_SHOWN_CONVERSATION_STONE_MODAL;
- const hasShown = getStorage(storageKey);
- const isFirstShowModal = hasShown !== 'true';
-
- // 更新点击状态(控制光晕显示)
- if (isFirstClick) {
- setStorage(clickedStorageKey, 'true');
- if (stone.stoneType === 'mission') {
- setHasClickedMissionStone(true);
- } else {
- setHasClickedConversationStone(true);
- }
- }
-
- // 准备需要同步到数据库的字段
- const userId = getUserId();
- const updatePayload: Record<string, boolean> = {};
-
- // 如果是第一次点击,需要更新点击状态
- if (isFirstClick) {
- if (stone.stoneType === 'mission') {
- updatePayload.has_clicked_mission_stone = true;
- } else {
- updatePayload.has_clicked_conversation_stone = true;
- }
- }
-
- // 如果是第一次显示弹窗,需要更新弹窗状态
- if (isFirstShowModal) {
- setEnergyStoneModalType(stone.stoneType);
- setShowMissionStoneModal(true);
- pendingStoneIdRef.current = stone.stoneId;
- if (stone.stoneType === 'mission') {
- updatePayload.has_shown_mission_stone_modal = true;
- } else {
- updatePayload.has_shown_conversation_stone_modal = true;
- }
- }
- // 非首次弹窗,直接播放动画并移除能量石
- if (!isFirstShowModal) {
- startStoneAnimationAndRemove(stone.stoneId);
- }
-
- // 合并同步到数据库(一次性更新所有需要更新的字段)
- if (userId && Object.keys(updatePayload).length > 0) {
- try {
- await updateUserUIState(userId, updatePayload);
- debugLog('[能量石] 能量石状态已同步到数据库:', updatePayload);
-
- // 同步成功后更新 localStorage
- if (isFirstShowModal) {
- setStorage(storageKey, 'true');
- }
- } catch (error) {
- console.error('同步能量石状态到数据库失败:', error);
- // 同步失败时,如果只是点击状态失败,不影响弹窗显示
- // 但如果是弹窗状态失败,需要回滚弹窗显示
- if (isFirstShowModal) {
- // 弹窗已经显示,但同步失败,记录错误以便后续补偿
- console.warn('[能量石] 弹窗状态同步失败,但弹窗已显示');
- }
- }
- } else if (!userId) {
- // 没有 userId(游客态),仅更新本地
- if (isFirstShowModal) {
- setStorage(storageKey, 'true');
- }
- debugLog('[能量石] 游客状态,仅更新本地,等待后续补偿同步');
- } else {
- // 没有需要更新的字段,直接更新 localStorage(如果显示弹窗)
- if (isFirstShowModal) {
- setStorage(storageKey, 'true');
- }
- }
- }}
- aria-label={stone.stoneType === 'mission' ? tProfile('missionStoneTitle') : tProfile('chatStoneTitle')}
- >
- <img src={asset} alt="" aria-hidden="true" />
- </button>
- </div>
- );
- })}
- {/* AnimaZone 动画形象 - 双 img 固定角色:default 层永远 default;对话层 emotion→talking,放下时静默换 default */}
- <div
- className="chatbot-anima-zone-avatar absolute"
- style={{
- width: px2vmin(238),
- height: px2vmin(238),
- top: px2vmin(292),
- left: '50%',
- transform: 'translateX(-50%)',
- opacity: 1,
- zIndex: 2,
- }}
- >
- <img
- src={defaultGifUrl || undefined}
- alt={currentAvatarAlt}
- loading="eager"
- decoding="async"
- style={{
- position: 'absolute',
- inset: 0,
- width: '100%',
- height: '100%',
- objectFit: 'contain',
- pointerEvents: 'none',
- zIndex: showConversationOnTop ? 0 : 1,
- opacity: showConversationOnTop ? 0 : 1,
- }}
- />
- <img
- src={conversationLayerSrc || undefined}
- alt={currentAvatarAlt}
- loading="eager"
- decoding="async"
- style={{
- position: 'absolute',
- inset: 0,
- width: '100%',
- height: '100%',
- objectFit: 'contain',
- pointerEvents: 'none',
- zIndex: showConversationOnTop ? 1 : 0,
- opacity: showConversationOnTop ? 1 : 0,
- }}
- />
- </div>
- {/* 字幕区域 - 设计稿 393×852:top 500,高 92,宽 312,左右居中 */}
- {subtitleOn && subtitleVisible && recognizedText && currentState === 'playing' && (
- <div
- ref={subtitleContainerRef}
- className="chatbot-subtitle-container"
- style={{
- position: 'absolute',
- // 设计稿 393×852:top 500px → 使用 px2vmin 按 min(vw, vh) 适配
- top: px2vmin(530, 'v2'),
- left: '50%',
- transform: 'translateX(-50%)',
- // 设计稿宽度 312px、高度 92px
- width: px2vmin(312, 'v2'),
- height: px2vmin(72, 'v2'),
- borderRadius: px2vmin(16),
- backgroundColor: 'rgba(0, 0, 0, 0.4)',
- color: '#F5F3F0',
- fontSize: px2vmin(14),
- lineHeight: px2vmin(20),
- padding: px2vmin(12),
- boxSizing: 'border-box',
- // 方案 A:完整文本 + 可滚动,但通过样式隐藏滚动条
- overflowY: 'auto',
- WebkitOverflowScrolling: 'touch',
- zIndex: 20,
- }}
- >
- {recognizedText}
- </div>
- )}
- {/* Yp 图片 - 设计稿 393×852,相对动画形象顶部 191,64×14 */}
- <div
- className="absolute"
- style={{
- top: `calc(${px2vmin(292)} + ${px2vmin(191)})`,
- left: '50%',
- transform: 'translateX(-50%)',
- width: px2vmin(64),
- height: px2vmin(14),
- zIndex: 10,
- }}
- >
- <img
- src={YpImage}
- alt={tCommon('a11y.yp')}
- className="w-full h-full object-contain"
- style={{ width: '100%', height: '100%' }}
- draggable={false}
- />
- </div>
- {/* 录音时按钮区域上方:0~50 秒显示 audio-wave.gif,50~60 秒显示 00:50…01:00 后自动发送 */}
- {currentState === 'recording' && (
- <div
- className="absolute left-1/2 -translate-x-1/2 flex items-center justify-center pointer-events-none"
- style={{
- width: px2vmin(64),
- height: px2vmin(32),
- top: px2vmin(592 - 32 - 8),
- zIndex: 19,
- backgroundColor: 'rgba(0, 0, 0, 0.4)',
- borderRadius: 20,
- }}
- >
- {remainingTimeMs !== null && remainingTimeMs <= COUNTDOWN_THRESHOLD_MS ? (
- <span
- style={{
- fontSize: px2vmin(14),
- color: 'rgba(245, 243, 240, 1)',
- fontWeight: 600,
- }}
- >
- {formatElapsed50to60(remainingTimeMs)}
- </span>
- ) : (
- <img
- src={audioWaveGif}
- alt=""
- className="w-full h-full object-contain"
- draggable={false}
- />
- )}
- </div>
- )}
- {/* 按钮区域 - 设计稿 393×852:top 592,高 98,宽 312,左右居中 */}
- <div
- className="chatbot-progress-container absolute"
- style={{
- width: px2vmin(312),
- height: px2vmin(98),
- top: px2vmin(592),
- left: '50%',
- transform: 'translateX(-50%)',
- zIndex: 20,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}
- >
- {/* 左侧 - 非录音:功能菜单按钮 48×47;录音:取消按钮(以区域中心为界,距中心 16.67) */}
- <div
- className="absolute"
- style={{
- left: 0,
- width: currentState === 'recording' ? '50%' : undefined,
- top: '50%',
- transform: 'translateY(-50%)',
- height: px2vmin(98),
- display: 'flex',
- alignItems: 'center',
- justifyContent: currentState === 'recording' ? 'flex-end' : 'center',
- paddingRight: currentState === 'recording' ? px2vmin(16.67) : 0,
- position: 'relative',
- }}
- >
- {currentState !== 'recording' && (
- <>
- <button
- type="button"
- className="touch-manipulation cursor-pointer border-0 bg-transparent p-0"
- onClick={() => setShowFuncMenuPopup((prev) => !prev)}
- style={{
- width: px2vmin(48),
- height: px2vmin(47),
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- }}
- aria-label={tCommon('a11y.menu')}
- >
- <img
- src={settingIcon}
- alt={tCommon('a11y.menu')}
- className="pointer-events-none w-full h-full object-contain"
- draggable={false}
- />
- </button>
- {showFuncMenuPopup && (
- <>
- <div
- className="fixed inset-0 z-30"
- style={{ left: 0, right: 0, top: 0, bottom: 0 }}
- aria-hidden
- onClick={() => setShowFuncMenuPopup(false)}
- />
- <div
- className="absolute z-40 flex flex-col rounded-lg"
- style={{
- left: 0,
- bottom: '100%',
- marginBottom: px2vmin(2, 'v2'),
- width: px2vmin(126, 'v2'),
- height: px2vmin(166, 'v2'),
- backgroundColor: 'rgba(0, 0, 0, 0.4)',
- padding: px2vmin(8, 'v2'),
- display: 'grid',
- gridTemplateColumns: '1fr 1fr',
- gridTemplateRows: '1fr 1fr',
- gap: px2vmin(8, 'v2'),
- boxSizing: 'border-box',
- }}
- >
- {[
- {
- key: 'profile',
- label: tCommon('profile'),
- icon: profileMenuIcon,
- enabled: true,
- onClick: () => {
- setShowFuncMenuPopup(false);
- navigate('/profile');
- },
- },
- {
- key: 'shop',
- label: tCommon('shop'),
- icon: shopMenuIcon,
- enabled: false,
- },
- {
- key: 'world',
- label: tCommon('world'),
- icon: worldMenuIcon,
- enabled: false,
- },
- {
- key: 'journal',
- label: tCommon('journal'),
- icon: diaryMenuIcon,
- enabled: false,
- },
- ].map((item) => (
- <button
- key={item.key}
- type="button"
- className="touch-manipulation border-0 bg-transparent p-0 flex flex-col items-center justify-center gap-0"
- disabled={!item.enabled}
- onClick={item.enabled ? item.onClick : undefined}
- style={{
- cursor: item.enabled ? 'pointer' : 'default',
- opacity: item.enabled ? 1 : 1,
- }}
- >
- <div
- style={{
- position: 'relative',
- width: px2vmin(48, 'v2'),
- height: px2vmin(48, 'v2'),
- border: 'none',
- flexShrink: 0,
- }}
- >
- <img
- src={item.icon}
- alt=""
- className="w-full h-full object-cover"
- draggable={false}
- style={{
- width: px2vmin(48, 'v2'),
- height: px2vmin(48, 'v2'),
- borderRadius: px2vmin(20, 'v2'),
- }}
- />
- {!item.enabled && (
- <img
- src={funcLockIcon}
- alt=""
- className="absolute pointer-events-none"
- draggable={false}
- style={{
- width: px2vmin(12, 'v2'),
- height: px2vmin(12, 'v2'),
- top: 0,
- right: 0,
- zIndex: 1,
- }}
- />
- )}
- </div>
- <span
- style={{
- fontSize: 12,
- lineHeight: '16px',
- color: '#F5F3F0',
- opacity: item.enabled ? 1 : 0.6,
- marginTop: px2vmin(4, 'v2'),
- }}
- >
- {item.label}
- </span>
- </button>
- ))}
- </div>
- </>
- )}
- </>
- )}
- {currentState === 'recording' && (
- <div
- className="chatbot-action-buttons flex items-center justify-center cursor-pointer touch-manipulation relative"
- onClick={handleCancel}
- style={{
- width: px2vmin(56),
- height: px2vmin(54),
- userSelect: 'none',
- overflow: 'visible',
- }}
- >
- <img src={cancelIcon} alt={tCommon('a11y.cancel')} className="pointer-events-none w-full h-full object-contain" draggable={false} />
- {ENABLE_CHATBOT_TIPS && showCancelTooltip && (
- <img
- src={tooltipsCancel}
- alt={tCommon('a11y.cancelTooltip')}
- className="chatbot-tooltips absolute pointer-events-none"
- style={{
- width: px2vmin(109),
- height: px2vmin(91),
- bottom: '110%',
- left: '-150%',
- zIndex: 10,
- }}
- />
- )}
- </div>
- )}
- </div>
- {/* 中间 - 非录音:录音开始按钮 84×82;录音:倒计时(最后10秒) */}
- <div
- className="absolute flex items-center justify-center"
- style={{
- left: '50%',
- top: '50%',
- transform: 'translate(-50%, -50%)',
- }}
- >
- {currentState !== 'recording' && (
- <div
- className={`chatbot-record-button touch-manipulation flex items-center justify-center ${isConnected ? 'cursor-pointer' : 'cursor-not-allowed'}`}
- onClick={handleStartRecord}
- style={{
- width: px2vmin(84),
- height: px2vmin(82),
- opacity: isConnected ? 1 : 0.55,
- userSelect: 'none',
- overflow: 'visible',
- position: 'relative',
- }}
- role="button"
- tabIndex={-1}
- aria-disabled={!isConnected}
- >
- <img
- src={isConnected ? luyinDefault : luyinDisable}
- alt={tCommon('a11y.record')}
- className="pointer-events-none w-full h-full object-contain"
- draggable={false}
- />
- {ENABLE_CHATBOT_TIPS && showTapToChat && isConnected && (
- <img
- src={tapToChat}
- alt={tCommon('a11y.tapToChat')}
- className="chatbot-tooltips absolute pointer-events-none"
- style={{
- width: px2vmin(128),
- height: px2vmin(100),
- top: '-100%',
- right: '-100%',
- zIndex: 10,
- }}
- />
- )}
- </div>
- )}
- </div>
- {/* 右侧 - 非录音:字幕开关 48×47;录音:发送按钮(以区域中心为界,距中心 16.67) */}
- <div
- className="absolute"
- style={{
- left: currentState === 'recording' ? '50%' : undefined,
- right: 0,
- width: currentState === 'recording' ? '50%' : undefined,
- top: '50%',
- transform: 'translateY(-50%)',
- height: px2vmin(98),
- display: 'flex',
- alignItems: 'center',
- justifyContent: currentState === 'recording' ? 'flex-start' : 'center',
- paddingLeft: currentState === 'recording' ? px2vmin(16.67) : 0,
- }}
- >
- {currentState !== 'recording' && (
- <button
- type="button"
- className="touch-manipulation cursor-pointer border-0 bg-transparent p-0 flex items-center justify-center"
- onClick={() => {
- setSubtitleOn((prev) => {
- const next = !prev;
- // 持久化到 localStorage
- setStorage(STORAGE_KEYS.SUBTITLE_ON, next ? 'true' : 'false');
- // 同步到后端用户 UI 状态
- const uid = getUserId();
- if (uid) {
- updateUserUIState(uid, { subtitle_on: next }).catch(() => {
- // 同步失败不影响前端展示
- });
- }
- return next;
- });
- }}
- style={{
- width: px2vmin(48),
- height: px2vmin(47),
- }}
- aria-label={subtitleOn ? 'Close subtitle' : 'Open subtitle'}
- >
- <img
- src={subtitleOn ? ccOpenIcon : ccCloseIcon}
- alt={subtitleOn ? 'Subtitle on' : 'Subtitle off'}
- className="pointer-events-none w-full h-full object-contain"
- draggable={false}
- />
- </button>
- )}
- {currentState === 'recording' && (
- <div
- className="chatbot-action-buttons flex items-center justify-center cursor-pointer touch-manipulation relative"
- onClick={handleSend}
- style={{
- width: px2vmin(56),
- height: px2vmin(54),
- userSelect: 'none',
- overflow: 'visible',
- }}
- >
- <img src={sendIcon} alt={tCommon('a11y.send')} className="pointer-events-none w-full h-full object-contain" draggable={false} />
- {ENABLE_CHATBOT_TIPS && showSendTooltip && (
- <img
- src={tooltipsSend}
- alt={tCommon('a11y.sendTooltip')}
- className="chatbot-tooltips absolute pointer-events-none"
- style={{
- width: px2vmin(111),
- height: 'auto',
- bottom: '110%',
- right: '-150%',
- zIndex: 10,
- }}
- />
- )}
- </div>
- )}
- </div>
- </div>
- {/* 能量石弹窗 */}
- <MissionEnergyStoneModal
- visible={showMissionStoneModal}
- onClose={handleMissionStoneModalClose}
- stoneType={energyStoneModalType}
- />
- {/* 亲密度弹窗:不满 3 颗心时展示,点击「点亮」增加一颗并关闭 */}
- <IntimacyModal
- visible={showIntimacyModal}
- heartCount={intimacyHeartCount}
- daysSinceLastVisit={intimacyDaysSinceLastVisit}
- canLightUpToday={canLightUpToday}
- loading={intimacyLoading}
- onClose={() => {
- setShowIntimacyModal(false);
- // 弹窗关闭后,如果尚未触发 greeting 且用户也未开始录音,则由前端显式发起首句
- startGreeting();
- }}
- onLightUp={() => {
- const uid = getUserId();
- if (!uid) return;
- setIntimacyLoading(true);
- lightUpIntimacy(uid)
- .then((res) => {
- if (res?.success && res.data) {
- setIntimacyHeartCount(res.data.heart_count);
- setShowIntimacyModal(false);
- // 点亮成功并关闭弹窗后,同样按需触发首句 greeting
- startGreeting();
- }
- })
- .finally(() => setIntimacyLoading(false));
- }}
- />
- </div>
- );
- };
|