index.html 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>聚德策划大师-大健康AI文案撰写</title>
  7. <meta name="description" content="聚德AI短视频脚本撰写器 - 专业高效的文案创作平台">
  8. <meta name="theme-color" content="#6366f1" media="(prefers-color-scheme: light)">
  9. <meta name="theme-color" content="#0f172a" media="(prefers-color-scheme: dark)">
  10. <meta name="color-scheme" content="light dark">
  11. <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  12. <link rel="stylesheet" href="{{ url_for('static', filename='css/modal.css') }}">
  13. <link rel="stylesheet" href="{{ url_for('static', filename='css/components/copy-button.css') }}">
  14. <link rel="icon" href="{{ url_for('static', filename='logo.png') }}">
  15. <link rel="stylesheet" href="{{ url_for('static', filename='css/github.min.css') }}">
  16. <link rel="stylesheet" href="{{ url_for('static', filename='css/highlightjs.min.css') }}">
  17. <link rel="stylesheet" href="{{ url_for('static', filename='css/fonts.css') }}">
  18. <!-- 思考过程样式 -->
  19. <style>
  20. /* AI思考过程样式 */
  21. .thought-container {
  22. background-color: #f3f0fa;
  23. border-left: 3px solid #7952b3;
  24. padding: 10px 15px;
  25. margin: 10px 0 10px 0;
  26. border-radius: 0 4px 4px 0;
  27. font-style: italic;
  28. color: #7952b3;
  29. position: relative;
  30. font-size: 0.98em;
  31. }
  32. .thought-container::before {
  33. content: "思考过程";
  34. display: block;
  35. font-size: 0.75rem;
  36. color: #7952b3;
  37. font-weight: 600;
  38. margin-bottom: 4px;
  39. font-style: normal;
  40. }
  41. .thought-toggle-btn {
  42. position: absolute;
  43. top: 8px;
  44. right: 12px;
  45. background: none;
  46. border: none;
  47. color: #7952b3;
  48. font-size: 1.1em;
  49. cursor: pointer;
  50. z-index: 2;
  51. padding: 2px 6px;
  52. border-radius: 3px;
  53. transition: background 0.2s;
  54. }
  55. .thought-toggle-btn:hover {
  56. background: #e5e1f6;
  57. }
  58. /* 思考过程内容区域样式 - 连续文本块 */
  59. .thought-content {
  60. overflow-y: auto;
  61. max-height: 500px;
  62. transition: max-height 0.35s cubic-bezier(.4, 0, .2, 1), padding 0.3s;
  63. will-change: max-height;
  64. /* 自定义滚动条样式 */
  65. scrollbar-width: thin;
  66. scrollbar-color: #d1c4e9 #f3f0fa;
  67. white-space: normal;
  68. /* 正常换行处理 */
  69. word-wrap: break-word;
  70. /* 长单词换行 */
  71. line-height: 1.4;
  72. /* 适中的行高 */
  73. text-align: left;
  74. /* 左对齐 */
  75. }
  76. /* Webkit浏览器的滚动条样式 */
  77. .thought-content::-webkit-scrollbar {
  78. width: 8px;
  79. }
  80. .thought-content::-webkit-scrollbar-track {
  81. background: #f3f0fa;
  82. border-radius: 4px;
  83. }
  84. .thought-content::-webkit-scrollbar-thumb {
  85. background: linear-gradient(135deg, #d1c4e9, #b39ddb);
  86. border-radius: 4px;
  87. border: 1px solid #f3f0fa;
  88. transition: background 0.2s ease;
  89. }
  90. .thought-content::-webkit-scrollbar-thumb:hover {
  91. background: linear-gradient(135deg, #b39ddb, #9575cd);
  92. }
  93. .thought-content::-webkit-scrollbar-thumb:active {
  94. background: linear-gradient(135deg, #9575cd, #7e57c2);
  95. }
  96. .thought-container.collapsed .thought-content {
  97. max-height: 0;
  98. padding: 0 !important;
  99. }
  100. .thought-container.collapsed::before {
  101. content: "思考过程(已收起)";
  102. }
  103. .thought-container p {
  104. margin: 0;
  105. font-style: italic;
  106. color: #7952b3;
  107. background: none;
  108. border-bottom: none;
  109. padding-bottom: 0;
  110. line-height: 1.6;
  111. }
  112. .thought-container p:last-child {
  113. border-bottom: none;
  114. }
  115. /* 对话项样式优化 */
  116. .conversation-meta {
  117. display: flex;
  118. justify-content: space-between;
  119. align-items: center;
  120. margin-top: 4px;
  121. font-size: 0.75rem;
  122. color: #666;
  123. opacity: 0.8;
  124. }
  125. .message-count {
  126. font-size: 0.7rem;
  127. }
  128. .last-time {
  129. font-size: 0.7rem;
  130. color: #999;
  131. }
  132. .conversation-item.active .conversation-meta {
  133. color: rgba(99, 102, 241, 0.8);
  134. }
  135. .conversation-item.active .last-time {
  136. color: rgba(99, 102, 241, 0.6);
  137. }
  138. /* 对话状态指示器样式 */
  139. .conversation-item.streaming .conversation-title {
  140. color: #10b981;
  141. font-weight: 500;
  142. }
  143. .conversation-item.paused .conversation-title {
  144. color: #f59e0b;
  145. font-weight: 500;
  146. }
  147. .conversation-item.streaming .conversation-meta {
  148. color: #10b981;
  149. }
  150. .conversation-item.paused .conversation-meta {
  151. color: #f59e0b;
  152. }
  153. /* 当前活跃对话指示器 */
  154. .conversation-item.active {
  155. background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(99, 102, 241, 0.05));
  156. border-left: 3px solid #6366f1;
  157. position: relative;
  158. }
  159. /* 对话切换动画 */
  160. .conversation-item {
  161. transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  162. cursor: pointer;
  163. }
  164. .conversation-item:hover {
  165. background: rgba(99, 102, 241, 0.05);
  166. transform: translateX(2px);
  167. }
  168. .conversation-item.active:hover {
  169. background: linear-gradient(135deg, rgba(99, 102, 241, 0.15), rgba(99, 102, 241, 0.08));
  170. }
  171. /* 对话状态点指示器 */
  172. .conversation-status-dot {
  173. position: absolute;
  174. top: 12px;
  175. right: 12px;
  176. width: 8px;
  177. height: 8px;
  178. border-radius: 50%;
  179. opacity: 0;
  180. transition: opacity 0.3s ease;
  181. }
  182. .conversation-item.streaming .conversation-status-dot {
  183. background: #10b981;
  184. opacity: 1;
  185. animation: pulse-dot 2s infinite;
  186. }
  187. .conversation-item.paused .conversation-status-dot {
  188. background: #f59e0b;
  189. opacity: 1;
  190. animation: pulse-dot 2s infinite;
  191. }
  192. .conversation-item.active .conversation-status-dot {
  193. background: #6366f1;
  194. opacity: 1;
  195. }
  196. @keyframes pulse-dot {
  197. 0% {
  198. opacity: 1;
  199. transform: scale(1);
  200. }
  201. 50% {
  202. opacity: 0.5;
  203. transform: scale(1.2);
  204. }
  205. 100% {
  206. opacity: 1;
  207. transform: scale(1);
  208. }
  209. }
  210. /* 编辑按钮样式 - 与复制按钮保持一致 */
  211. .edit-button {
  212. position: absolute;
  213. width: 32px;
  214. height: 32px;
  215. background: var(--primary-indigo);
  216. color: white;
  217. border: none;
  218. border-radius: 50%;
  219. display: flex;
  220. align-items: center;
  221. justify-content: center;
  222. cursor: pointer;
  223. z-index: 1001;
  224. box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
  225. transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease;
  226. opacity: 0;
  227. bottom: 8px;
  228. right: 48px;
  229. /* 位于复制按钮左侧 */
  230. }
  231. /* 悬停时显示编辑按钮 */
  232. .message.user:hover .edit-button {
  233. opacity: 1;
  234. }
  235. .edit-button:hover {
  236. transform: scale(1.1);
  237. box-shadow: 0 6px 10px rgba(0, 0, 0, 0.25);
  238. }
  239. .edit-button svg {
  240. width: 18px;
  241. height: 18px;
  242. }
  243. /* 内联编辑样式 */
  244. .message-editing {
  245. position: relative;
  246. }
  247. .edit-form {
  248. display: flex;
  249. flex-direction: column;
  250. gap: 12px;
  251. padding: 16px;
  252. background: #f8f9fa;
  253. border: 2px solid #6366f1;
  254. border-radius: 12px;
  255. margin: 8px 0;
  256. width: 600px;
  257. }
  258. .edit-textarea {
  259. width: 100%;
  260. min-height: 80px;
  261. padding: 12px;
  262. border: none;
  263. border-radius: 8px;
  264. font-size: 14px;
  265. line-height: 1.5;
  266. resize: vertical;
  267. font-family: inherit;
  268. background: white;
  269. }
  270. .edit-textarea:focus {
  271. outline: none;
  272. box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
  273. }
  274. .edit-actions {
  275. display: flex;
  276. gap: 12px;
  277. justify-content: flex-end;
  278. }
  279. .edit-cancel-btn {
  280. padding: 4px 10px;
  281. background: white;
  282. border: 1px solid #ddd;
  283. border-radius: 6px;
  284. color: #666;
  285. cursor: pointer;
  286. font-size: 14px;
  287. transition: all 0.2s ease;
  288. }
  289. .edit-cancel-btn:hover {
  290. background: #f5f5f5;
  291. border-color: #ccc;
  292. }
  293. .edit-send-btn {
  294. padding: 4px 10px;
  295. background: #6366f1;
  296. border: none;
  297. border-radius: 6px;
  298. color: white;
  299. cursor: pointer;
  300. font-size: 14px;
  301. transition: all 0.2s ease;
  302. }
  303. .edit-send-btn:hover {
  304. background: #5b5cf6;
  305. }
  306. .edit-send-btn:disabled {
  307. background: #ccc;
  308. cursor: not-allowed;
  309. }
  310. </style>
  311. </head>
  312. <body>
  313. <div class="glass-particles"></div>
  314. <!-- 移动端侧边栏切换按钮 -->
  315. <button class="sidebar-toggle" id="sidebar-toggle" style="display: none;">
  316. <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  317. <path d="M3 12h18M3 6h18M3 18h18" stroke="currentColor" stroke-width="2" stroke-linecap="round"
  318. stroke-linejoin="round" />
  319. </svg>
  320. </button>
  321. <!-- 移动端侧边栏遮罩层 -->
  322. <div class="sidebar-overlay" id="sidebar-overlay"></div>
  323. <div class="chat-container">
  324. <!-- 历史记录侧边栏 -->
  325. <div class="history-sidebar" id="history-sidebar">
  326. <div class="sidebar-header">
  327. <button class="new-chat-btn" id="new-chat-btn">
  328. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  329. <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round"
  330. stroke-linejoin="round" />
  331. </svg>
  332. 开启新对话
  333. </button>
  334. </div>
  335. <div class="history-content">
  336. <!-- 历史记录将通过JavaScript动态加载 -->
  337. <div class="history-loading" id="history-loading"
  338. style="display: flex; align-items: center; justify-content: center; padding: 20px; color: #666;">
  339. <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"
  340. style="margin-right: 8px; animation: spin 1s linear infinite;">
  341. <path d="M21 12a9 9 0 11-6.219-8.56" stroke="currentColor" stroke-width="2"
  342. stroke-linecap="round" stroke-linejoin="round" />
  343. </svg>
  344. 正在加载历史记录...
  345. </div>
  346. <div class="history-empty" id="history-empty"
  347. style="display: none; text-align: center; padding: 40px 20px; color: #999;">
  348. <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"
  349. style="margin-bottom: 16px; opacity: 0.5;">
  350. <path d="M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z"
  351. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
  352. </svg>
  353. <div style="font-size: 16px; margin-bottom: 8px;">暂无历史记录</div>
  354. <div style="font-size: 14px; opacity: 0.7;">开始新的对话吧!</div>
  355. </div>
  356. </div>
  357. </div>
  358. <!-- 主聊天区域 -->
  359. <div class="main-chat-area">
  360. <header class="glass-header">
  361. <div class="logo-title-container">
  362. <img src="{{ url_for('static', filename='logo.png') }}" alt="聚德AI短视频脚本撰写" class="header-logo">
  363. <h1>聚德策划大师-大健康AI文案撰写<span class="version-tag">v 1.6.3</span></h1>
  364. <a class="logo-title-link" href="https://wj.qq.com/s2/23610733/1a16/" target="_blank"
  365. class="jude-link">问题反馈</a>
  366. </div>
  367. <div class="buttons-container">
  368. <!-- 智能体选择(仅智能策划大师) -->
  369. <div id="agent-dropdown" class="glass-btn" style="position: relative;">
  370. <img id="agent-trigger-icon" src="{{ url_for('static', filename='img/planning.png') }}"
  371. alt="平台图标" width="16" height="16" onerror="this.style.display='none'">
  372. <span id="agent-trigger-text">智能策划大师</span>
  373. <svg width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  374. <path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
  375. stroke-linejoin="round" />
  376. </svg>
  377. <div id="agent-menu" class="glass-panel"
  378. style="display:none; position: absolute; top: calc(100% + 6px); left: 0; z-index: 1001; min-width: 220px;">
  379. <ul style="list-style: none; margin: 0; padding: 6px;">
  380. <li class="agent-option" data-agent="planning"
  381. style="display:flex; align-items:center; gap:8px; padding:12px; border-radius:8px; cursor:pointer; transition: all 0.2s ease; user-select: none;"
  382. onmouseover="this.style.background='rgba(99, 102, 241, 0.1)'"
  383. onmouseout="this.style.background=''">
  384. <img src="{{ url_for('static', filename='img/planning.png') }}" alt="智能策划大师"
  385. width="16" height="16" onerror="this.style.display='none'">
  386. <div style="display:flex; flex-direction:column;">
  387. <span style="font-weight: 500;">智能策划大师</span>
  388. </div>
  389. </li>
  390. <li class="agent-option" data-agent="pathology"
  391. style="display:flex; align-items:center; gap:8px; padding:12px; border-radius:8px; cursor:pointer; transition: all 0.2s ease; user-select: none;"
  392. onmouseover="this.style.background='rgba(99, 102, 241, 0.1)'"
  393. onmouseout="this.style.background=''">
  394. <img src="{{ url_for('static', filename='img/videoaccount.svg') }}" alt="病理分析"
  395. width="16" height="16" onerror="this.style.display='none'">
  396. <div style="display:flex; flex-direction:column;">
  397. <span style="font-weight: 500;">病理分析</span>
  398. </div>
  399. </li>
  400. <!-- 投放诊断 -->
  401. <li class="agent-option" data-agent="diagnosis"
  402. style="display:flex; align-items:center; gap:8px; padding:12px; border-radius:8px; cursor:pointer; transition: all 0.2s ease; user-select: none;"
  403. onmouseover="this.style.background='rgba(99, 102, 241, 0.1)'"
  404. onmouseout="this.style.background=''">
  405. <img src="{{ url_for('static', filename='img/diagnosis.svg') }}" alt="投放诊断"
  406. width="16" height="16" onerror="this.style.display='none'">
  407. <div style="display:flex; flex-direction:column;">
  408. <span style="font-weight: 500;">投放诊断</span>
  409. </div>
  410. </li>
  411. </ul>
  412. </div>
  413. </div>
  414. <button id="reset-btn" class="btn glass-btn">
  415. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  416. <path
  417. d="M4 4V9H4.58152M19.9381 11C19.446 7.05369 16.0796 4 12 4C8.64262 4 5.76829 6.06817 4.58152 9M4.58152 9H9M20 20V15H19.4185M19.4185 15C18.2317 17.9318 15.3574 20 12 20C7.92038 20 4.55399 16.9463 4.06189 13M19.4185 15H15"
  418. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
  419. </svg>
  420. 重置对话
  421. </button>
  422. <!-- 用户信息 -->
  423. <div class="user-info" id="user-info" style="display: none;">
  424. <div class="user-details">
  425. <div class="user-avatar" id="user-avatar">
  426. <img id="avatar-img" src="" alt="用户头像" onerror="this.style.display='none'">
  427. <div id="avatar-fallback" class="avatar-fallback"></div>
  428. </div>
  429. <div class="user-text">
  430. <div class="user-info-row">
  431. <span class="user-name" id="user-name"></span>
  432. <span class="user-type" id="user-type"></span>
  433. </div>
  434. <div class="user-info-row">
  435. <span class="user-title" id="user-title" style="display: none;"></span>
  436. </div>
  437. </div>
  438. </div>
  439. <div class="user-dropdown" id="user-dropdown" style="display: none;">
  440. <div class="user-dropdown-content">
  441. <button id="logout-btn" class="btn glass-btn logout-btn">
  442. <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
  443. xmlns="http://www.w3.org/2000/svg">
  444. <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 3l4 4-4 4M21 7H9"
  445. stroke="currentColor" stroke-width="2" stroke-linecap="round"
  446. stroke-linejoin="round" />
  447. </svg>
  448. 退出登录
  449. </button>
  450. </div>
  451. </div>
  452. </div>
  453. </div>
  454. </header>
  455. <!-- 移动端菜单切换按钮 -->
  456. <div class="chat-main-content">
  457. <div id="chat-messages" class="chat-messages glass-panel">
  458. <div class="message bot">
  459. <div class="message-content">您好,我是聚德策划大师。请输入您需要的内容,例如:
  460. <ul>
  461. <li>请输入需要撰写的产品或疾病名称</li>
  462. <li>补充目标人群、投放场景、文案风格</li>
  463. </ul>
  464. </div>
  465. <div class="message-content">我将为您输出可直接使用的营销文案、脚本方向和优化建议。</div>
  466. </div>
  467. </div>
  468. <div class="chat-input-container glass-panel">
  469. <textarea id="user-input" placeholder="请输入需要撰写的品类名和要求..." rows="1"></textarea>
  470. <button id="send-btn" class="glass-btn-primary" aria-label="发送消息">
  471. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  472. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2"
  473. stroke-linecap="round" stroke-linejoin="round" />
  474. </svg>
  475. </button>
  476. </div>
  477. </div>
  478. </div>
  479. </div>
  480. <!-- 页面启动保护:避免脚本异常时出现纯白屏 -->
  481. <script>
  482. (function () {
  483. function showFatalScreen (msg) {
  484. if (document.getElementById('fatal-boot-error')) return;
  485. const box = document.createElement('div');
  486. box.id = 'fatal-boot-error';
  487. box.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#f8fafc;color:#1f2937;display:flex;align-items:center;justify-content:center;padding:24px;';
  488. box.innerHTML = `
  489. <div style="max-width:680px;background:#fff;border:1px solid #e5e7eb;border-radius:10px;box-shadow:0 10px 20px rgba(0,0,0,.08);padding:20px;">
  490. <h3 style="margin:0 0 10px;font-size:18px;">页面加载失败</h3>
  491. <p style="margin:0 0 12px;line-height:1.6;">${msg || '检测到关键脚本加载异常,已阻止白屏。请先刷新页面,若仍失败请联系管理员清理缓存并检查静态资源发布。'}</p>
  492. <div style="display:flex;gap:10px;">
  493. <button onclick="location.reload()" style="border:0;background:#4f46e5;color:#fff;border-radius:6px;padding:8px 14px;cursor:pointer;">刷新页面</button>
  494. <button onclick="location.href='/login'" style="border:1px solid #d1d5db;background:#fff;color:#111827;border-radius:6px;padding:8px 14px;cursor:pointer;">重新登录</button>
  495. </div>
  496. </div>
  497. `;
  498. document.body.appendChild(box);
  499. }
  500. window.__bootFailedScripts = [];
  501. window.__onScriptLoadError = function (src) {
  502. window.__bootFailedScripts.push(src || 'unknown');
  503. showFatalScreen('关键静态资源加载失败:' + window.__bootFailedScripts.join(', '));
  504. };
  505. window.addEventListener('error', function (e) {
  506. if (e && e.message) {
  507. showFatalScreen('页面初始化异常:' + e.message);
  508. }
  509. });
  510. window.addEventListener('unhandledrejection', function (e) {
  511. const reason = e && e.reason ? (e.reason.message || String(e.reason)) : '未知Promise异常';
  512. showFatalScreen('页面初始化异常:' + reason);
  513. });
  514. window.addEventListener('load', function () {
  515. setTimeout(function () {
  516. if (window.__bootFailedScripts.length > 0) return;
  517. if (typeof window.fetch !== 'function') {
  518. showFatalScreen('浏览器环境异常:fetch不可用。');
  519. }
  520. }, 1200);
  521. });
  522. })();
  523. </script>
  524. <!-- 核心JS库 -->
  525. <script src="{{ url_for('static', filename='js/highlight.min.js') }}"
  526. onerror="window.__onScriptLoadError('highlight.min.js')"></script>
  527. <script src="{{ url_for('static', filename='js/marked.min.js') }}"
  528. onerror="window.__onScriptLoadError('marked.min.js')"></script>
  529. <script src="{{ url_for('static', filename='js/showdown.min.js') }}"
  530. onerror="window.__onScriptLoadError('showdown.min.js')"></script>
  531. <script src="{{ url_for('static', filename='js/copy-buttons.js') }}"
  532. onerror="window.__onScriptLoadError('copy-buttons.js')"></script>
  533. <script src="{{ url_for('static', filename='js/chat.js') }}"
  534. onerror="window.__onScriptLoadError('chat.js')"></script>
  535. <!-- 认证和用户信息管理 -->
  536. <!-- 自定义弹框 -->
  537. <!-- 删除确认弹框 -->
  538. <div id="delete-modal" class="custom-modal">
  539. <div class="modal-overlay"></div>
  540. <div class="modal-content">
  541. <div class="modal-header">
  542. <h3 class="modal-title">删除对话</h3>
  543. <button class="modal-close" onclick="closeModal('delete-modal')">
  544. <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  545. <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"
  546. stroke-linejoin="round" />
  547. </svg>
  548. </button>
  549. </div>
  550. <div class="modal-body">
  551. <div class="modal-icon delete-icon">
  552. <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  553. <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"
  554. stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
  555. <path d="M10 11v6M14 11v6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
  556. stroke-linejoin="round" />
  557. </svg>
  558. </div>
  559. <p class="modal-message">确定要删除这个对话吗?删除后将无法恢复。</p>
  560. </div>
  561. <div class="modal-footer">
  562. <button class="btn btn-secondary" onclick="closeModal('delete-modal')">取消</button>
  563. <button class="btn btn-danger" id="confirm-delete-btn">删除</button>
  564. </div>
  565. </div>
  566. </div>
  567. <!-- 重命名弹框 -->
  568. <div id="rename-modal" class="custom-modal">
  569. <div class="modal-overlay"></div>
  570. <div class="modal-content">
  571. <div class="modal-header">
  572. <h3 class="modal-title">重命名对话</h3>
  573. <button class="modal-close" onclick="closeModal('rename-modal')">
  574. <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  575. <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"
  576. stroke-linejoin="round" />
  577. </svg>
  578. </button>
  579. </div>
  580. <div class="modal-body">
  581. <div class="form-group">
  582. <input type="text" id="rename-input" class="form-input" placeholder="请输入新的对话标题" maxlength="50">
  583. <div class="form-hint">最多50个字符</div>
  584. </div>
  585. </div>
  586. <div class="modal-footer">
  587. <button class="btn btn-secondary" onclick="closeModal('rename-modal')">取消</button>
  588. <button class="btn btn-primary" id="confirm-rename-btn">保存</button>
  589. </div>
  590. </div>
  591. </div>
  592. <!-- 消息提示弹框 -->
  593. <div id="message-modal" class="custom-modal">
  594. <div class="modal-overlay"></div>
  595. <div class="modal-content message-modal-content">
  596. <div class="modal-body">
  597. <div class="modal-icon message-icon">
  598. <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  599. <path d="M9 12l2 2 4-4M21 12a9 9 0 11-18 0 9 9 0 0118 0z" stroke="currentColor" stroke-width="2"
  600. stroke-linecap="round" stroke-linejoin="round" />
  601. </svg>
  602. </div>
  603. <p class="modal-message" id="message-text">操作成功</p>
  604. </div>
  605. <div class="modal-footer">
  606. <button class="btn btn-primary" onclick="closeModal('message-modal')">确定</button>
  607. </div>
  608. </div>
  609. </div>
  610. <script>
  611. // 弹框控制函数
  612. function showModal (modalId) {
  613. const modal = document.getElementById(modalId);
  614. if (modal) {
  615. modal.classList.add('show');
  616. document.body.style.overflow = 'hidden'; // 防止背景滚动
  617. }
  618. }
  619. function closeModal (modalId) {
  620. const modal = document.getElementById(modalId);
  621. if (modal) {
  622. modal.classList.remove('show');
  623. document.body.style.overflow = ''; // 恢复滚动
  624. }
  625. }
  626. function showMessage (message, type = 'success') {
  627. const messageText = document.getElementById('message-text');
  628. const messageIcon = document.querySelector('#message-modal .modal-icon');
  629. if (messageText) {
  630. messageText.textContent = message;
  631. }
  632. if (messageIcon) {
  633. // 根据类型设置图标颜色
  634. messageIcon.className = 'modal-icon message-icon';
  635. if (type === 'error') {
  636. messageIcon.style.color = '#ef4444';
  637. } else if (type === 'warning') {
  638. messageIcon.style.color = '#f59e0b';
  639. } else {
  640. messageIcon.style.color = '#10b981';
  641. }
  642. }
  643. showModal('message-modal');
  644. }
  645. // 点击遮罩层关闭弹框
  646. document.addEventListener('click', function (e) {
  647. if (e.target.classList.contains('modal-overlay')) {
  648. const modal = e.target.closest('.custom-modal');
  649. if (modal) {
  650. closeModal(modal.id);
  651. }
  652. }
  653. });
  654. // ESC键关闭弹框
  655. document.addEventListener('keydown', function (e) {
  656. if (e.key === 'Escape') {
  657. const openModal = document.querySelector('.custom-modal.show');
  658. if (openModal) {
  659. closeModal(openModal.id);
  660. }
  661. }
  662. });
  663. // 防重复重定向标志
  664. let isRedirecting = false;
  665. // 页面加载时检查认证状态
  666. document.addEventListener('DOMContentLoaded', function () {
  667. checkAuthStatus();
  668. });
  669. // 思考过程折叠/展开函数
  670. function toggleThought (button) {
  671. const container = button.closest('.thought-container');
  672. const content = container.querySelector('.thought-content');
  673. const icon = button.querySelector('svg path');
  674. if (container.dataset.collapsed === 'true') {
  675. // 展开
  676. container.dataset.collapsed = 'false';
  677. content.style.maxHeight = '500px';
  678. content.style.padding = '10px 0';
  679. icon.setAttribute('d', 'M6 9l6 6 6-6');
  680. } else {
  681. // 折叠
  682. container.dataset.collapsed = 'true';
  683. content.style.maxHeight = '0';
  684. content.style.padding = '0';
  685. icon.setAttribute('d', 'M18 15l-6-6-6 6');
  686. }
  687. }
  688. function checkAuthStatus () {
  689. // 检查URL参数中是否有登录成功信息
  690. const urlParams = new URLSearchParams(window.location.search);
  691. const loginSuccess = urlParams.get('login_success');
  692. const token = urlParams.get('token');
  693. const userInfoJson = urlParams.get('user_info');
  694. if (loginSuccess && token && userInfoJson) {
  695. // 登录成功,处理用户信息
  696. try {
  697. const userInfo = JSON.parse(decodeURIComponent(userInfoJson));
  698. // 保存到localStorage
  699. localStorage.setItem('auth_token', token);
  700. localStorage.setItem('user_info', JSON.stringify(userInfo));
  701. // 显示用户信息
  702. displayUserInfo(userInfo);
  703. showUserSection();
  704. addAuthHeader(token);
  705. // 清理URL参数
  706. window.history.replaceState({}, document.title, window.location.pathname);
  707. // 初始化历史记录侧边栏
  708. initializeHistorySidebar();
  709. // 启动对话状态更新器
  710. if (typeof startConversationStatusUpdater === 'function') {
  711. startConversationStatusUpdater();
  712. }
  713. } catch (e) {
  714. redirectToLogin();
  715. }
  716. } else {
  717. // 正常检查localStorage中的认证信息
  718. const storedToken = localStorage.getItem('auth_token');
  719. const storedUserInfo = localStorage.getItem('user_info');
  720. if (storedToken && storedUserInfo) {
  721. try {
  722. const user = JSON.parse(storedUserInfo);
  723. // 验证用户信息的基本字段
  724. if (!user.name && !user.nickname) {
  725. user.name = '钉钉用户';
  726. user.nickname = '钉钉用户';
  727. }
  728. displayUserInfo(user);
  729. showUserSection();
  730. addAuthHeader(storedToken);
  731. // 初始化历史记录侧边栏
  732. initializeHistorySidebar();
  733. // 启动对话状态更新器
  734. if (typeof startConversationStatusUpdater === 'function') {
  735. startConversationStatusUpdater();
  736. }
  737. } catch (e) {
  738. redirectToLogin();
  739. }
  740. } else {
  741. redirectToLogin();
  742. }
  743. }
  744. }
  745. function displayUserInfo (user) {
  746. // 显示用户头像
  747. const avatarImg = document.getElementById('avatar-img');
  748. const avatarFallback = document.getElementById('avatar-fallback');
  749. if (user.avatar && user.avatar.trim() !== '') {
  750. avatarImg.src = user.avatar;
  751. avatarImg.style.display = 'block';
  752. avatarFallback.style.display = 'none';
  753. } else {
  754. avatarImg.style.display = 'none';
  755. avatarFallback.style.display = 'block';
  756. // 获取用户名的首字母作为头像
  757. const displayName = user.nickname || user.name || 'U';
  758. avatarFallback.textContent = displayName.charAt(0).toUpperCase();
  759. }
  760. // 显示用户信息
  761. const userName = document.getElementById('user-name');
  762. if (userName) {
  763. const displayName = user.nickname || user.name || '钉钉用户';
  764. userName.textContent = displayName;
  765. }
  766. const userType = document.getElementById('user-type');
  767. if (userType) {
  768. // 根据登录类型显示不同的标签样式
  769. if (user.login_type === 'dingtalk') {
  770. userType.textContent = '钉钉';
  771. userType.style.background = 'rgba(24, 144, 255, 0.2)';
  772. userType.style.color = '#1890ff';
  773. userType.style.border = '1px solid rgba(24, 144, 255, 0.3)';
  774. } else {
  775. userType.textContent = user.login_type || '钉钉';
  776. userType.style.background = 'rgba(255, 255, 255, 0.3)';
  777. userType.style.color = '#666';
  778. userType.style.border = '1px solid rgba(255, 255, 255, 0.2)';
  779. }
  780. }
  781. const userTitle = document.getElementById('user-title');
  782. if (userTitle && user.title) {
  783. userTitle.textContent = user.title;
  784. userTitle.style.display = 'block';
  785. }
  786. // 显示其他用户信息
  787. if (user.email) {
  788. const emailItem = document.getElementById('user-email');
  789. if (emailItem) {
  790. emailItem.querySelector('.info-value').textContent = user.email;
  791. emailItem.style.display = 'block';
  792. }
  793. }
  794. if (user.mobile) {
  795. const mobileItem = document.getElementById('user-mobile');
  796. if (mobileItem) {
  797. mobileItem.querySelector('.info-value').textContent = user.mobile;
  798. mobileItem.style.display = 'block';
  799. }
  800. }
  801. if (user.job_number) {
  802. const jobItem = document.getElementById('user-job');
  803. if (jobItem) {
  804. jobItem.querySelector('.info-value').textContent = user.job_number;
  805. jobItem.style.display = 'block';
  806. }
  807. }
  808. if (user.dept_name) {
  809. const deptItem = document.getElementById('user-dept');
  810. if (deptItem) {
  811. deptItem.querySelector('.info-value').textContent = user.dept_name;
  812. deptItem.style.display = 'block';
  813. }
  814. }
  815. }
  816. function showUserSection () {
  817. const userInfo = document.getElementById('user-info');
  818. if (userInfo) userInfo.style.display = 'flex';
  819. }
  820. function addAuthHeader (token) {
  821. // 注意:addAuthHeader函数由chat.js提供,这里不需要重复定义
  822. // 如果需要设置认证头,直接调用chat.js中的函数
  823. if (typeof window.addAuthHeader === 'function') {
  824. window.addAuthHeader(token);
  825. }
  826. }
  827. function redirectToLogin () {
  828. if (isRedirecting) {
  829. return;
  830. }
  831. isRedirecting = true;
  832. localStorage.removeItem('auth_token');
  833. localStorage.removeItem('user_info');
  834. // 添加延迟,避免频繁重定向
  835. setTimeout(() => {
  836. window.location.href = '/login';
  837. }, 100);
  838. }
  839. // 退出登录
  840. document.getElementById('logout-btn').addEventListener('click', function () {
  841. fetch('/api/auth/logout', {
  842. method: 'POST',
  843. headers: {
  844. 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
  845. 'Content-Type': 'application/json'
  846. }
  847. }).then(() => {
  848. redirectToLogin();
  849. }).catch(() => {
  850. redirectToLogin();
  851. });
  852. });
  853. // 用户信息下拉菜单(修复:添加鼠标进入/离开事件,防止移向退出登录按钮时菜单消失)
  854. function initializeUserDropdown () {
  855. const userInfo = document.getElementById('user-info');
  856. const dropdown = document.getElementById('user-dropdown');
  857. if (!userInfo || !dropdown) {
  858. return;
  859. }
  860. // 初始化时确保下拉菜单是隐藏状态(覆盖CSS的:hover效果)
  861. dropdown.style.display = 'none';
  862. dropdown.style.opacity = '0';
  863. dropdown.style.visibility = 'hidden';
  864. dropdown.style.transform = 'translateY(-15px) scale(0.95)';
  865. let isHovering = false;
  866. let hideTimer = null;
  867. function showDropdown () {
  868. if (hideTimer) {
  869. clearTimeout(hideTimer);
  870. hideTimer = null;
  871. }
  872. dropdown.style.display = 'block';
  873. dropdown.style.opacity = '1';
  874. dropdown.style.visibility = 'visible';
  875. dropdown.style.transform = 'translateY(0) scale(1)';
  876. }
  877. function scheduleHide () {
  878. if (hideTimer) {
  879. clearTimeout(hideTimer);
  880. }
  881. hideTimer = setTimeout(() => {
  882. if (!isHovering) {
  883. dropdown.style.display = 'none';
  884. dropdown.style.opacity = '0';
  885. dropdown.style.visibility = 'hidden';
  886. dropdown.style.transform = 'translateY(-15px) scale(0.95)';
  887. }
  888. }, 150); // 150ms延迟,给用户足够时间移动到按钮
  889. }
  890. // 鼠标进入用户信息区域
  891. userInfo.addEventListener('mouseenter', function () {
  892. isHovering = true;
  893. showDropdown();
  894. });
  895. // 鼠标离开用户信息区域
  896. userInfo.addEventListener('mouseleave', function () {
  897. isHovering = false;
  898. scheduleHide();
  899. });
  900. // 鼠标进入下拉菜单区域(重要:防止鼠标移动到按钮时菜单消失)
  901. dropdown.addEventListener('mouseenter', function () {
  902. isHovering = true;
  903. showDropdown();
  904. });
  905. // 鼠标离开下拉菜单区域
  906. dropdown.addEventListener('mouseleave', function () {
  907. isHovering = false;
  908. scheduleHide();
  909. });
  910. // 保留点击事件用于移动端
  911. document.getElementById('user-avatar').addEventListener('click', function (e) {
  912. // 在桌面端,如果已经在悬停显示状态,点击时不处理(避免冲突)
  913. if (window.innerWidth > 768 && dropdown.style.display === 'block') {
  914. return;
  915. }
  916. // 移动端切换显示/隐藏
  917. if (dropdown.style.display === 'none' || dropdown.style.display === '') {
  918. showDropdown();
  919. } else {
  920. dropdown.style.display = 'none';
  921. dropdown.style.opacity = '0';
  922. dropdown.style.visibility = 'hidden';
  923. dropdown.style.transform = 'translateY(-15px) scale(0.95)';
  924. }
  925. });
  926. }
  927. // 初始化用户下拉菜单
  928. document.addEventListener('DOMContentLoaded', function () {
  929. setTimeout(() => {
  930. initializeUserDropdown();
  931. }, 100);
  932. });
  933. const AGENT_META = {
  934. 'planning': {
  935. name: '智能策划大师',
  936. icon: "{{ url_for('static', filename='img/planning.png') }}"
  937. },
  938. 'pathology': {
  939. name: '病理分析',
  940. icon: "{{ url_for('static', filename='img/videoaccount.svg') }}"
  941. },
  942. 'diagnosis': {
  943. name: '投放诊断',
  944. icon: "{{ url_for('static', filename='img/diagnosis.svg') }}"
  945. },
  946. };
  947. const AGENT_WELCOME_CONTENT = {
  948. 'planning': [
  949. `您好,我是聚德策划大师。请输入您需要的内容,例如:
  950. <ul>
  951. <li>请输入需要撰写的产品或疾病名称</li>
  952. <li>补充目标人群、投放场景、文案风格</li>
  953. </ul>`,
  954. '我将为您输出可直接使用的营销文案、脚本方向和优化建议。'
  955. ],
  956. 'pathology': [
  957. `您好,我是病理分析助手。为了更准确分析,请尽量提供:
  958. <ul>
  959. <li>疾病或产品名称</li>
  960. </ul>`,
  961. '我会给出病理逻辑拆解、用户关注点与内容表达建议。'
  962. ],
  963. 'diagnosis': [
  964. `您好,我是投放诊断助手。请发送您的投放数据,例如:
  965. <ul>
  966. <li>消耗、曝光、点击、转化、成本等核心指标</li>
  967. </ul>`,
  968. '如果是视频诊断,目前仅支持文案诊断,建议先转为文案(最好附时间戳字幕)。'
  969. ]
  970. };
  971. function getCurrentAgentType () {
  972. return localStorage.getItem('current_agent') || 'planning';
  973. }
  974. function getAgentWelcomeHtml (agentType) {
  975. const welcomeBlocks = AGENT_WELCOME_CONTENT[agentType] || AGENT_WELCOME_CONTENT['planning'];
  976. return `
  977. <div class="message bot">
  978. ${welcomeBlocks.map(content => `<div class="message-content">${content}</div>`).join('')}
  979. </div>
  980. `;
  981. }
  982. function renderAgentWelcomeMessage (agentType) {
  983. const chatMessages = document.getElementById('chat-messages');
  984. if (!chatMessages) return;
  985. chatMessages.innerHTML = getAgentWelcomeHtml(agentType || getCurrentAgentType());
  986. }
  987. function syncAgentWelcomeMessageForEmptyConversation () {
  988. const chatMessages = document.getElementById('chat-messages');
  989. if (!chatMessages) return;
  990. const hasUserMessages = chatMessages.querySelectorAll('.message.user').length > 0;
  991. if (hasUserMessages) return;
  992. const hasOnlyOneBotMessage = chatMessages.children.length === 1 &&
  993. chatMessages.querySelectorAll('.message.bot').length === 1;
  994. const hasNoMessages = chatMessages.children.length === 0;
  995. if (hasOnlyOneBotMessage || hasNoMessages) {
  996. renderAgentWelcomeMessage(getCurrentAgentType());
  997. }
  998. }
  999. // 智能体选择(悬停展开)
  1000. document.addEventListener('DOMContentLoaded', function () {
  1001. setTimeout(() => {
  1002. initializeAgentHoverDropdown();
  1003. syncAgentWelcomeMessageForEmptyConversation();
  1004. }, 100);
  1005. // 监听窗口大小变化,重新初始化智能体菜单
  1006. let resizeTimer;
  1007. window.addEventListener('resize', function () {
  1008. clearTimeout(resizeTimer);
  1009. resizeTimer = setTimeout(() => {
  1010. initializeAgentHoverDropdown();
  1011. }, 250);
  1012. });
  1013. });
  1014. function initializeAgentHoverDropdown () {
  1015. const dropdown = document.getElementById('agent-dropdown');
  1016. const menu = document.getElementById('agent-menu');
  1017. const triggerText = document.getElementById('agent-trigger-text');
  1018. const triggerIcon = document.getElementById('agent-trigger-icon');
  1019. if (!dropdown || !menu) return;
  1020. const agentMeta = AGENT_META;
  1021. // 兼容历史存储:如果之前存的是已删除的智能体,强制切回智能策划大师
  1022. const storedAgent = localStorage.getItem('current_agent');
  1023. let currentAgent = 'planning';
  1024. if (!storedAgent || !agentMeta[storedAgent]) {
  1025. // 没有存过,或存的是已不存在的智能体 -> 统一重置为智能策划大师
  1026. localStorage.setItem('current_agent', 'planning');
  1027. } else {
  1028. currentAgent = storedAgent;
  1029. }
  1030. // 初始化触发器显示
  1031. triggerText.textContent = agentMeta[currentAgent].name;
  1032. if (triggerIcon) {
  1033. triggerIcon.src = agentMeta[currentAgent].icon;
  1034. triggerIcon.style.display = 'block';
  1035. }
  1036. // 高亮选中项(仅影响下拉菜单项,不改全局样式)
  1037. function clearActiveStyles () {
  1038. menu.querySelectorAll('.agent-option').forEach(item => {
  1039. item.removeAttribute('data-active');
  1040. item.style.background = '';
  1041. item.style.border = '';
  1042. item.style.opacity = '';
  1043. item.style.pointerEvents = '';
  1044. });
  1045. }
  1046. function setActiveStyles (agentType) {
  1047. clearActiveStyles();
  1048. const activeEl = menu.querySelector(`.agent-option[data-agent="${agentType}"]`);
  1049. if (activeEl) {
  1050. activeEl.setAttribute('data-active', 'true');
  1051. activeEl.style.background = 'rgba(99, 102, 241, 0.12)';
  1052. activeEl.style.border = '1px solid rgba(99, 102, 241, 0.35)';
  1053. activeEl.style.opacity = '1';
  1054. // 禁止重复点击当前激活项
  1055. activeEl.style.pointerEvents = 'none';
  1056. }
  1057. }
  1058. setActiveStyles(currentAgent);
  1059. // 检测是否为移动设备
  1060. const isMobile = window.innerWidth <= 768;
  1061. if (isMobile) {
  1062. // 移动端:点击显示/隐藏菜单
  1063. let isMenuOpen = false;
  1064. function showMenu () {
  1065. menu.style.display = 'block';
  1066. isMenuOpen = true;
  1067. // 添加动画类
  1068. setTimeout(() => {
  1069. menu.classList.add('show');
  1070. }, 10);
  1071. }
  1072. function hideMenu () {
  1073. menu.classList.remove('show');
  1074. setTimeout(() => {
  1075. menu.style.display = 'none';
  1076. }, 300);
  1077. isMenuOpen = false;
  1078. }
  1079. // 点击触发器显示菜单
  1080. dropdown.addEventListener('click', function (e) {
  1081. e.preventDefault();
  1082. e.stopPropagation();
  1083. if (isMenuOpen) {
  1084. hideMenu();
  1085. } else {
  1086. showMenu();
  1087. }
  1088. });
  1089. // 移除遮罩层点击事件
  1090. // 点击菜单外部隐藏菜单
  1091. document.addEventListener('click', function (e) {
  1092. if (!dropdown.contains(e.target) && !menu.contains(e.target)) {
  1093. hideMenu();
  1094. }
  1095. });
  1096. } else {
  1097. // 桌面端:悬停显示/隐藏(避免从触发区移动到菜单区时闪烁隐藏)
  1098. let isHovering = false;
  1099. let hideTimer = null;
  1100. function showMenu () {
  1101. if (hideTimer) {
  1102. clearTimeout(hideTimer);
  1103. hideTimer = null;
  1104. }
  1105. menu.style.display = 'block';
  1106. }
  1107. function scheduleHide () {
  1108. if (hideTimer) {
  1109. clearTimeout(hideTimer);
  1110. }
  1111. hideTimer = setTimeout(() => {
  1112. if (!isHovering) {
  1113. menu.style.display = 'none';
  1114. }
  1115. }, 120);
  1116. }
  1117. dropdown.addEventListener('mouseenter', function () {
  1118. isHovering = true;
  1119. showMenu();
  1120. });
  1121. dropdown.addEventListener('mouseleave', function () {
  1122. isHovering = false;
  1123. scheduleHide();
  1124. });
  1125. menu.addEventListener('mouseenter', function () {
  1126. isHovering = true;
  1127. showMenu();
  1128. });
  1129. menu.addEventListener('mouseleave', function () {
  1130. isHovering = false;
  1131. scheduleHide();
  1132. });
  1133. }
  1134. menu.querySelectorAll('.agent-option').forEach((item, index) => {
  1135. item.addEventListener('click', function (e) {
  1136. e.preventDefault();
  1137. e.stopPropagation();
  1138. const agentType = this.getAttribute('data-agent');
  1139. const current = localStorage.getItem('current_agent') || 'planning';
  1140. // 已是当前激活则不处理
  1141. if (agentType === current) {
  1142. return;
  1143. }
  1144. // 检查是否已有对话(不是新对话)且有实际消息内容
  1145. const conversationId = window.currentConversationId;
  1146. const hasExistingConversation = conversationId &&
  1147. conversationId !== 'new' &&
  1148. conversationId !== null &&
  1149. conversationId !== undefined;
  1150. // 检查当前对话是否有实际的消息内容(不是空的新对话)
  1151. const hasActualMessages = checkConversationHasMessages(conversationId);
  1152. if (hasExistingConversation && hasActualMessages) {
  1153. // 先关闭菜单,避免遮挡对话框
  1154. if (isMobile) {
  1155. hideMenu();
  1156. } else {
  1157. isHovering = false;
  1158. scheduleHide();
  1159. }
  1160. // 延迟一下再弹出对话框,确保菜单已关闭
  1161. setTimeout(() => {
  1162. // 弹出确认对话框
  1163. showAgentSwitchConfirmDialog(agentType, current, function (confirmed) {
  1164. if (confirmed) {
  1165. // 用户确认,创建新对话并切换智能体
  1166. switchAgentWithNewConversation(agentType);
  1167. setActiveStyles(agentType);
  1168. // 更新触发器
  1169. triggerText.textContent = agentMeta[agentType].name;
  1170. if (triggerIcon) {
  1171. triggerIcon.src = agentMeta[agentType].icon;
  1172. triggerIcon.style.display = 'block';
  1173. }
  1174. } else {
  1175. // 用户取消,不切换智能体,保持当前智能体
  1176. // 不需要做任何操作
  1177. }
  1178. });
  1179. }, 100);
  1180. } else {
  1181. // 新对话或空对话(没有实际消息),直接切换智能体,无需确认
  1182. switchAgent(agentType);
  1183. setActiveStyles(agentType);
  1184. // 更新触发器
  1185. triggerText.textContent = agentMeta[agentType].name;
  1186. if (triggerIcon) {
  1187. triggerIcon.src = agentMeta[agentType].icon;
  1188. triggerIcon.style.display = 'block';
  1189. }
  1190. // 移动端点击后隐藏菜单
  1191. if (isMobile) {
  1192. hideMenu();
  1193. } else {
  1194. isHovering = false;
  1195. scheduleHide();
  1196. }
  1197. }
  1198. });
  1199. // 添加触摸事件支持(移动端)
  1200. item.addEventListener('touchend', function (e) {
  1201. e.preventDefault();
  1202. this.click(); // 触发点击事件
  1203. });
  1204. });
  1205. }
  1206. // 检查对话是否有实际的消息内容
  1207. function checkConversationHasMessages (conversationId) {
  1208. if (!conversationId || conversationId === 'new') {
  1209. return false;
  1210. }
  1211. // 方法1: 检查聊天消息区域中是否有用户消息
  1212. const chatMessages = document.getElementById('chat-messages');
  1213. if (chatMessages) {
  1214. const userMessages = chatMessages.querySelectorAll('.message.user');
  1215. // 如果有用户消息,说明对话有实际内容
  1216. if (userMessages.length > 0) {
  1217. return true;
  1218. }
  1219. }
  1220. // 方法2: 检查侧边栏中当前对话的消息数量
  1221. const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
  1222. if (conversationItem) {
  1223. const messageCountElement = conversationItem.querySelector('.message-count');
  1224. if (messageCountElement) {
  1225. const messageCount = parseInt(messageCountElement.textContent) || 0;
  1226. // 如果消息数量大于0,说明对话有实际内容
  1227. if (messageCount > 0) {
  1228. return true;
  1229. }
  1230. }
  1231. }
  1232. // 方法3: 检查是否有正在进行的流式响应(说明用户正在发送消息)
  1233. if (window.conversationStates && window.conversationStates.has(conversationId)) {
  1234. const state = window.conversationStates.get(conversationId);
  1235. if (state && (state.isStreaming || (state.userMessages && state.userMessages.length > 0))) {
  1236. return true;
  1237. }
  1238. }
  1239. // 如果以上都没有,说明是空的新对话
  1240. return false;
  1241. }
  1242. function switchAgent (agentType) {
  1243. const current = localStorage.getItem('current_agent') || 'planning';
  1244. if (current === agentType) {
  1245. return;
  1246. }
  1247. // 保存到本地存储
  1248. localStorage.setItem('current_agent', agentType);
  1249. // 更新状态提示(如有)
  1250. updateStatusIndicator(agentType);
  1251. // 空对话下切换智能体时,同步更新说明文案
  1252. syncAgentWelcomeMessageForEmptyConversation();
  1253. // 显示切换提示
  1254. showAgentSwitchNotification(agentType);
  1255. }
  1256. // 切换智能体并创建新对话
  1257. function switchAgentWithNewConversation (agentType) {
  1258. const current = localStorage.getItem('current_agent') || 'planning';
  1259. if (current === agentType) {
  1260. return;
  1261. }
  1262. // 保存到本地存储
  1263. localStorage.setItem('current_agent', agentType);
  1264. // 更新状态提示(如有)
  1265. updateStatusIndicator(agentType);
  1266. // 创建新对话
  1267. if (typeof createNewConversation === 'function') {
  1268. createNewConversation();
  1269. }
  1270. // 显示切换提示
  1271. showAgentSwitchNotification(agentType);
  1272. }
  1273. // 显示智能体切换确认对话框
  1274. function showAgentSwitchConfirmDialog (newAgentType, currentAgentType, callback) {
  1275. // 防止重复弹出对话框
  1276. if (document.querySelector('.agent-switch-dialog-overlay')) {
  1277. return;
  1278. }
  1279. const agentNames = {
  1280. 'planning': '智能策划大师',
  1281. 'pathology': '病理分析',
  1282. 'diagnosis': '投放诊断',
  1283. 'kuaishou': '快手',
  1284. 'toutiao': '头条'
  1285. };
  1286. const newAgentName = agentNames[newAgentType] || '新智能体';
  1287. const currentAgentName = agentNames[currentAgentType] || '当前智能体';
  1288. // 创建对话框遮罩层
  1289. const overlay = document.createElement('div');
  1290. overlay.className = 'agent-switch-dialog-overlay';
  1291. overlay.style.cssText = `
  1292. position: fixed;
  1293. top: 0;
  1294. left: 0;
  1295. width: 100%;
  1296. height: 100%;
  1297. background: rgba(0, 0, 0, 0.5);
  1298. display: flex;
  1299. justify-content: center;
  1300. align-items: center;
  1301. z-index: 10000;
  1302. animation: fadeIn 0.2s ease;
  1303. `;
  1304. // 创建对话框
  1305. const dialog = document.createElement('div');
  1306. dialog.className = 'agent-switch-dialog';
  1307. dialog.style.cssText = `
  1308. background: white;
  1309. border-radius: 12px;
  1310. padding: 24px;
  1311. max-width: 400px;
  1312. width: 90%;
  1313. box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  1314. animation: slideUp 0.3s ease;
  1315. `;
  1316. dialog.innerHTML = `
  1317. <div style="margin-bottom: 20px;">
  1318. <div style="font-size: 18px; font-weight: 600; color: #333; margin-bottom: 12px;">
  1319. 切换智能体
  1320. </div>
  1321. <div style="font-size: 14px; color: #666; line-height: 1.6;">
  1322. 切换将新建对话,是否继续?
  1323. </div>
  1324. </div>
  1325. <div style="display: flex; gap: 12px; justify-content: flex-end;">
  1326. <button class="dialog-btn-cancel" style="
  1327. padding: 10px 20px;
  1328. border: 1px solid #ddd;
  1329. border-radius: 6px;
  1330. background: white;
  1331. color: #666;
  1332. cursor: pointer;
  1333. font-size: 14px;
  1334. transition: all 0.2s;
  1335. ">否</button>
  1336. <button class="dialog-btn-confirm" style="
  1337. padding: 10px 20px;
  1338. border: none;
  1339. border-radius: 6px;
  1340. background: #007bff;
  1341. color: white;
  1342. cursor: pointer;
  1343. font-size: 14px;
  1344. transition: all 0.2s;
  1345. ">继续</button>
  1346. </div>
  1347. `;
  1348. // 添加动画样式
  1349. if (!document.getElementById('agent-switch-dialog-styles')) {
  1350. const style = document.createElement('style');
  1351. style.id = 'agent-switch-dialog-styles';
  1352. style.textContent = `
  1353. @keyframes fadeIn {
  1354. from { opacity: 0; }
  1355. to { opacity: 1; }
  1356. }
  1357. @keyframes fadeOut {
  1358. from { opacity: 1; }
  1359. to { opacity: 0; }
  1360. }
  1361. @keyframes slideUp {
  1362. from {
  1363. opacity: 0;
  1364. transform: translateY(20px);
  1365. }
  1366. to {
  1367. opacity: 1;
  1368. transform: translateY(0);
  1369. }
  1370. }
  1371. @keyframes slideDown {
  1372. from {
  1373. opacity: 1;
  1374. transform: translateY(0);
  1375. }
  1376. to {
  1377. opacity: 0;
  1378. transform: translateY(20px);
  1379. }
  1380. }
  1381. .agent-switch-dialog-overlay {
  1382. backdrop-filter: blur(2px);
  1383. }
  1384. .dialog-btn-cancel:hover {
  1385. background: #f5f5f5 !important;
  1386. border-color: #bbb !important;
  1387. }
  1388. .dialog-btn-confirm:hover {
  1389. background: #0056b3 !important;
  1390. }
  1391. .dialog-btn-cancel:active,
  1392. .dialog-btn-confirm:active {
  1393. transform: scale(0.98);
  1394. }
  1395. `;
  1396. document.head.appendChild(style);
  1397. }
  1398. overlay.appendChild(dialog);
  1399. document.body.appendChild(overlay);
  1400. // 绑定按钮事件
  1401. const cancelBtn = dialog.querySelector('.dialog-btn-cancel');
  1402. const confirmBtn = dialog.querySelector('.dialog-btn-confirm');
  1403. const closeDialog = (result) => {
  1404. overlay.style.animation = 'fadeOut 0.2s ease';
  1405. dialog.style.animation = 'slideDown 0.2s ease';
  1406. setTimeout(() => {
  1407. overlay.remove();
  1408. callback(result);
  1409. }, 200);
  1410. };
  1411. cancelBtn.addEventListener('click', () => closeDialog(false));
  1412. confirmBtn.addEventListener('click', () => closeDialog(true));
  1413. // 点击遮罩层关闭(取消)
  1414. overlay.addEventListener('click', (e) => {
  1415. if (e.target === overlay) {
  1416. closeDialog(false);
  1417. }
  1418. });
  1419. // ESC键关闭(取消)
  1420. const handleEsc = (e) => {
  1421. if (e.key === 'Escape') {
  1422. closeDialog(false);
  1423. document.removeEventListener('keydown', handleEsc);
  1424. }
  1425. };
  1426. document.addEventListener('keydown', handleEsc);
  1427. }
  1428. function updateStatusIndicator (agentType) {
  1429. const agentNames = {
  1430. 'planning': '智能策划大师',
  1431. 'pathology': '病理分析',
  1432. 'diagnosis': '投放诊断',
  1433. 'kuaishou': '快手',
  1434. 'toutiao': '头条'
  1435. };
  1436. const currentPlatformName = document.getElementById('current-platform-name');
  1437. if (currentPlatformName) {
  1438. currentPlatformName.textContent = agentNames[agentType] || '智能策划大师';
  1439. }
  1440. }
  1441. function showAgentSwitchNotification (agentType) {
  1442. const agentNames = {
  1443. 'planning': '智能策划大师',
  1444. 'pathology': '病理分析',
  1445. 'diagnosis': '投放诊断',
  1446. 'kuaishou': '快手',
  1447. 'toutiao': '头条'
  1448. };
  1449. const agentName = agentNames[agentType] || '智能策划大师';
  1450. // 创建通知元素
  1451. const notification = document.createElement('div');
  1452. notification.className = 'agent-switch-notification';
  1453. notification.setAttribute('data-platform', agentType);
  1454. notification.innerHTML = `
  1455. <div class="notification-content">
  1456. <span class="notification-icon">✨</span>
  1457. <span class="notification-text">已切换到 ${agentName}</span>
  1458. </div>
  1459. `;
  1460. // 添加到页面
  1461. document.body.appendChild(notification);
  1462. // 显示动画
  1463. setTimeout(() => {
  1464. notification.classList.add('show');
  1465. }, 100);
  1466. // 自动隐藏
  1467. setTimeout(() => {
  1468. notification.classList.remove('show');
  1469. setTimeout(() => {
  1470. if (notification.parentNode) {
  1471. notification.parentNode.removeChild(notification);
  1472. }
  1473. }, 300);
  1474. }, 2000);
  1475. }
  1476. // 获取当前平台类型(供其他功能使用)
  1477. function getCurrentAgent () {
  1478. return getCurrentAgentType();
  1479. }
  1480. // 动态调整聊天消息区域高度
  1481. function adjustChatMessagesHeight () {
  1482. const userInput = document.getElementById('user-input');
  1483. const chatMessages = document.getElementById('chat-messages');
  1484. if (userInput && chatMessages) {
  1485. // 获取输入框的实际高度
  1486. const inputHeight = userInput.scrollHeight;
  1487. const minHeight = 44; // 最小高度
  1488. const maxHeight = 200; // 最大高度
  1489. const actualHeight = Math.max(minHeight, Math.min(inputHeight, maxHeight));
  1490. // 计算聊天消息区域应该的高度
  1491. const containerHeight = document.querySelector('.chat-container').offsetHeight;
  1492. const headerHeight = document.querySelector('header').offsetHeight;
  1493. const inputContainerPadding = 40; // 输入框容器的padding
  1494. const availableHeight = containerHeight - headerHeight - actualHeight - inputContainerPadding;
  1495. // 设置最小高度为100px,确保有足够的显示空间
  1496. const finalHeight = Math.max(availableHeight, 100);
  1497. chatMessages.style.height = `${finalHeight}px`;
  1498. }
  1499. }
  1500. // 滚动到聊天消息区域底部
  1501. function scrollToBottom () {
  1502. const chatMessages = document.getElementById('chat-messages');
  1503. if (chatMessages) {
  1504. chatMessages.scrollTop = chatMessages.scrollHeight;
  1505. }
  1506. }
  1507. // 平滑滚动到聊天消息区域底部
  1508. function smoothScrollToBottom () {
  1509. const chatMessages = document.getElementById('chat-messages');
  1510. if (chatMessages) {
  1511. chatMessages.scrollTo({
  1512. top: chatMessages.scrollHeight,
  1513. behavior: 'smooth'
  1514. });
  1515. }
  1516. }
  1517. // 监听输入框内容变化
  1518. document.addEventListener('DOMContentLoaded', function () {
  1519. const userInput = document.getElementById('user-input');
  1520. if (userInput) {
  1521. // 监听输入事件
  1522. userInput.addEventListener('input', adjustChatMessagesHeight);
  1523. // 监听键盘事件(回车等)
  1524. userInput.addEventListener('keydown', function (e) {
  1525. if (e.key === 'Enter' && !e.shiftKey) {
  1526. // 如果是回车键且没有按Shift,延迟调整高度
  1527. setTimeout(adjustChatMessagesHeight, 100);
  1528. }
  1529. });
  1530. // 监听窗口大小变化
  1531. window.addEventListener('resize', adjustChatMessagesHeight);
  1532. // 初始化时调整一次高度
  1533. setTimeout(adjustChatMessagesHeight, 100);
  1534. }
  1535. // 监听聊天消息区域的内容变化,自动滚动到底部
  1536. const chatMessages = document.getElementById('chat-messages');
  1537. if (chatMessages) {
  1538. // 创建观察器监听内容变化
  1539. const observer = new MutationObserver(function (mutations) {
  1540. // 如果正在编辑消息,不自动滚动
  1541. if (window.isEditingMessage) {
  1542. return;
  1543. }
  1544. const distanceToBottom = chatMessages.scrollHeight - chatMessages.scrollTop - chatMessages.clientHeight;
  1545. const threshold = 50;
  1546. if (distanceToBottom > threshold) {
  1547. return;
  1548. }
  1549. // 延迟滚动,确保内容完全渲染
  1550. setTimeout(() => {
  1551. scrollToBottom();
  1552. }, 100);
  1553. });
  1554. // 监听子节点变化和属性变化
  1555. observer.observe(chatMessages, {
  1556. childList: true,
  1557. subtree: true,
  1558. attributes: false
  1559. });
  1560. // 初始化时滚动到底部
  1561. setTimeout(scrollToBottom, 100);
  1562. // 添加双击快速滚动到底部的功能
  1563. let clickCount = 0;
  1564. let clickTimer = null;
  1565. chatMessages.addEventListener('click', function () {
  1566. clickCount++;
  1567. if (clickCount === 1) {
  1568. clickTimer = setTimeout(() => {
  1569. clickCount = 0;
  1570. }, 300);
  1571. } else if (clickCount === 2) {
  1572. clearTimeout(clickTimer);
  1573. clickCount = 0;
  1574. smoothScrollToBottom();
  1575. }
  1576. });
  1577. }
  1578. });
  1579. // 添加键盘快捷键:Ctrl+End 或 Cmd+End 快速滚动到底部
  1580. document.addEventListener('keydown', function (e) {
  1581. if ((e.ctrlKey || e.metaKey) && e.key === 'End') {
  1582. e.preventDefault();
  1583. smoothScrollToBottom();
  1584. }
  1585. });
  1586. // 历史记录侧边栏功能 - 移除自动初始化,由认证成功后调用
  1587. function initializeHistorySidebar () {
  1588. const sidebar = document.getElementById('history-sidebar');
  1589. const sidebarToggle = document.getElementById('sidebar-toggle');
  1590. const sidebarOverlay = document.getElementById('sidebar-overlay');
  1591. const newChatBtn = document.getElementById('new-chat-btn');
  1592. const conversationItems = document.querySelectorAll('.conversation-item');
  1593. const conversationMenus = document.querySelectorAll('.conversation-menu');
  1594. // 检测是否为移动设备
  1595. const isMobile = window.innerWidth <= 768;
  1596. if (isMobile) {
  1597. // 移动端显示切换按钮
  1598. if (sidebarToggle) {
  1599. sidebarToggle.style.display = 'flex';
  1600. }
  1601. // 移动端侧边栏切换功能
  1602. if (sidebarToggle && sidebar && sidebarOverlay) {
  1603. sidebarToggle.addEventListener('click', function () {
  1604. sidebar.classList.add('show');
  1605. sidebarOverlay.classList.add('show');
  1606. document.body.style.overflow = 'hidden';
  1607. });
  1608. sidebarOverlay.addEventListener('click', function () {
  1609. sidebar.classList.remove('show');
  1610. sidebarOverlay.classList.remove('show');
  1611. document.body.style.overflow = '';
  1612. });
  1613. }
  1614. } else {
  1615. // 桌面端隐藏切换按钮
  1616. if (sidebarToggle) {
  1617. sidebarToggle.style.display = 'none';
  1618. }
  1619. }
  1620. // 监听窗口大小变化
  1621. window.addEventListener('resize', function () {
  1622. const isMobileNow = window.innerWidth <= 768;
  1623. if (isMobileNow && !isMobile) {
  1624. // 切换到移动端
  1625. if (sidebarToggle) {
  1626. sidebarToggle.style.display = 'flex';
  1627. }
  1628. if (sidebar && sidebarOverlay) {
  1629. sidebar.classList.remove('show');
  1630. sidebarOverlay.classList.remove('show');
  1631. document.body.style.overflow = '';
  1632. }
  1633. } else if (!isMobileNow && isMobile) {
  1634. // 切换到桌面端
  1635. if (sidebarToggle) {
  1636. sidebarToggle.style.display = 'none';
  1637. }
  1638. if (sidebar && sidebarOverlay) {
  1639. sidebar.classList.remove('show');
  1640. sidebarOverlay.classList.remove('show');
  1641. document.body.style.overflow = '';
  1642. }
  1643. }
  1644. });
  1645. // 新对话按钮功能
  1646. if (newChatBtn) {
  1647. newChatBtn.addEventListener('click', function () {
  1648. // 立即创建新对话
  1649. createNewConversation();
  1650. });
  1651. }
  1652. // 对话项点击功能
  1653. conversationItems.forEach(item => {
  1654. item.addEventListener('click', function (e) {
  1655. // 如果点击的是菜单按钮,不处理
  1656. if (e.target.closest('.conversation-menu')) {
  1657. return;
  1658. }
  1659. const conversationId = this.getAttribute('data-conversation-id');
  1660. // 设置激活的对话
  1661. if (typeof setActiveConversation === 'function') {
  1662. setActiveConversation(conversationId);
  1663. }
  1664. loadConversation(conversationId);
  1665. updateConversationSelection(conversationId);
  1666. // 移动端关闭侧边栏
  1667. if (isMobile && sidebar && sidebarOverlay) {
  1668. sidebar.classList.remove('show');
  1669. sidebarOverlay.classList.remove('show');
  1670. document.body.style.overflow = '';
  1671. }
  1672. });
  1673. });
  1674. // 对话菜单功能
  1675. conversationMenus.forEach(menu => {
  1676. menu.addEventListener('click', function (e) {
  1677. e.stopPropagation();
  1678. const conversationId = this.getAttribute('data-conversation-id');
  1679. showConversationMenu(conversationId, this);
  1680. });
  1681. });
  1682. // 同步侧边栏用户信息
  1683. syncSidebarUserInfo();
  1684. // 加载历史记录
  1685. loadConversationHistory();
  1686. }
  1687. // 查找现有的空"新对话"
  1688. function findExistingEmptyConversation () {
  1689. const conversationItems = document.querySelectorAll('.conversation-item');
  1690. for (let item of conversationItems) {
  1691. const messageCountElement = item.querySelector('.message-count');
  1692. if (messageCountElement) {
  1693. const messageCount = parseInt(messageCountElement.textContent);
  1694. if (messageCount === 0) {
  1695. return {
  1696. conversationId: item.getAttribute('data-conversation-id'),
  1697. sessionId: item.getAttribute('data-session-id'),
  1698. element: item
  1699. };
  1700. }
  1701. }
  1702. }
  1703. return null;
  1704. }
  1705. // 切换到现有的空"新对话"
  1706. function switchToExistingEmptyConversation (conversation) {
  1707. // 更新当前对话ID和session_id
  1708. window.currentConversationId = conversation.conversationId;
  1709. window.currentSessionId = conversation.sessionId;
  1710. // 清除聊天区域并显示提示语
  1711. clearCurrentConversation();
  1712. // 更新侧边栏选中状态
  1713. updateConversationSelection(conversation.conversationId);
  1714. // 移动端关闭侧边栏
  1715. const isMobile = window.innerWidth <= 768;
  1716. if (isMobile) {
  1717. const sidebar = document.getElementById('history-sidebar');
  1718. const sidebarOverlay = document.getElementById('sidebar-overlay');
  1719. if (sidebar && sidebarOverlay) {
  1720. sidebar.classList.remove('show');
  1721. sidebarOverlay.classList.remove('show');
  1722. document.body.style.overflow = '';
  1723. }
  1724. }
  1725. // 确保输入框状态正确
  1726. const userInput = document.getElementById('user-input');
  1727. const sendButton = document.getElementById('send-btn');
  1728. if (userInput && sendButton) {
  1729. userInput.disabled = false;
  1730. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  1731. userInput.classList.remove('input-loading');
  1732. sendButton.disabled = false;
  1733. sendButton.classList.remove('stopping');
  1734. }
  1735. }
  1736. function createNewConversation () {
  1737. // 检查认证状态
  1738. const token = localStorage.getItem('auth_token');
  1739. if (!token) {
  1740. redirectToLogin();
  1741. return;
  1742. }
  1743. // 先检查是否已经存在一个空的"新对话"
  1744. const existingEmptyConversation = findExistingEmptyConversation();
  1745. if (existingEmptyConversation) {
  1746. // 如果存在空的"新对话",直接切换到该对话
  1747. switchToExistingEmptyConversation(existingEmptyConversation);
  1748. return;
  1749. }
  1750. // 显示加载状态
  1751. const newChatBtn = document.getElementById('new-chat-btn');
  1752. if (newChatBtn) {
  1753. const originalText = newChatBtn.innerHTML;
  1754. newChatBtn.innerHTML = `
  1755. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="animation: spin 1s linear infinite;">
  1756. <path d="M21 12a9 9 0 11-6.219-8.56" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
  1757. </svg>
  1758. 创建中...
  1759. `;
  1760. newChatBtn.disabled = true;
  1761. }
  1762. // 调用后端API创建新对话
  1763. fetch('/api/conversations/new', {
  1764. method: 'POST',
  1765. headers: {
  1766. 'Authorization': `Bearer ${token}`,
  1767. 'Content-Type': 'application/json'
  1768. },
  1769. body: JSON.stringify({
  1770. title: '新对话'
  1771. })
  1772. })
  1773. .then(response => {
  1774. if (response.status === 401) {
  1775. redirectToLogin();
  1776. return;
  1777. }
  1778. return response.json();
  1779. })
  1780. .then(data => {
  1781. if (data && data.success) {
  1782. // 更新当前对话ID和session_id
  1783. window.currentConversationId = data.conversation.conversation_id;
  1784. window.currentSessionId = data.conversation.session_id;
  1785. // 清除聊天区域并显示提示语
  1786. clearCurrentConversation();
  1787. // 更新侧边栏选中状态
  1788. updateConversationSelection(data.conversation.conversation_id);
  1789. // 重新加载历史记录以显示新对话,但不自动加载对话内容
  1790. loadConversationHistory(false);
  1791. // 确保输入框状态正确
  1792. const userInput = document.getElementById('user-input');
  1793. const sendButton = document.getElementById('send-btn');
  1794. if (userInput && sendButton) {
  1795. userInput.disabled = false;
  1796. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  1797. userInput.classList.remove('input-loading');
  1798. sendButton.disabled = false;
  1799. sendButton.classList.remove('stopping');
  1800. }
  1801. // 移动端关闭侧边栏
  1802. const isMobile = window.innerWidth <= 768;
  1803. if (isMobile) {
  1804. const sidebar = document.getElementById('history-sidebar');
  1805. const sidebarOverlay = document.getElementById('sidebar-overlay');
  1806. if (sidebar && sidebarOverlay) {
  1807. sidebar.classList.remove('show');
  1808. sidebarOverlay.classList.remove('show');
  1809. document.body.style.overflow = '';
  1810. }
  1811. }
  1812. } else {
  1813. showMessage('创建新对话失败: ' + (data ? data.error : '未知错误'), 'error');
  1814. }
  1815. })
  1816. .catch(error => {
  1817. showMessage('创建新对话时发生错误: ' + error.message, 'error');
  1818. })
  1819. .finally(() => {
  1820. // 恢复按钮状态
  1821. if (newChatBtn) {
  1822. newChatBtn.innerHTML = `
  1823. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  1824. <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
  1825. </svg>
  1826. 开启新对话
  1827. `;
  1828. newChatBtn.disabled = false;
  1829. }
  1830. });
  1831. }
  1832. function clearCurrentConversation () {
  1833. const chatMessages = document.getElementById('chat-messages');
  1834. if (chatMessages) {
  1835. renderAgentWelcomeMessage(getCurrentAgentType());
  1836. }
  1837. // 清除全局状态管理中的当前激活对话
  1838. if (typeof currentActiveConversationId !== 'undefined') {
  1839. currentActiveConversationId = null;
  1840. }
  1841. // 清除强制创建新对话的标志(因为已经创建了新对话)
  1842. window.forceNewConversation = false;
  1843. }
  1844. function loadConversation (conversationId) {
  1845. // 检查认证状态
  1846. const token = localStorage.getItem('auth_token');
  1847. if (!token) {
  1848. redirectToLogin();
  1849. return;
  1850. }
  1851. // 设置激活的对话
  1852. if (typeof setActiveConversation === 'function') {
  1853. setActiveConversation(conversationId);
  1854. }
  1855. // 先切换到指定对话,然后加载内容
  1856. switchToConversationAndLoad(conversationId, token);
  1857. }
  1858. function switchToConversationAndLoad (conversationId, token) {
  1859. // 调用后端API切换到指定对话
  1860. fetch(`/api/conversations/${conversationId}/switch`, {
  1861. method: 'POST',
  1862. headers: {
  1863. 'Authorization': `Bearer ${token}`,
  1864. 'Content-Type': 'application/json'
  1865. }
  1866. }).then(response => {
  1867. if (response.status === 401) {
  1868. redirectToLogin();
  1869. return;
  1870. }
  1871. return response.json();
  1872. }).then(data => {
  1873. if (data && data.success) {
  1874. // 更新当前对话ID和session_id
  1875. window.currentConversationId = data.conversation.conversation_id;
  1876. window.currentSessionId = data.conversation.session_id;
  1877. // 加载对话内容
  1878. loadConversationSimple(conversationId, token);
  1879. } else {
  1880. showMessage('切换对话失败: ' + (data ? data.error : '未知错误'), 'error');
  1881. }
  1882. }).catch(error => {
  1883. showMessage('切换对话时发生错误: ' + error.message, 'error');
  1884. });
  1885. }
  1886. function loadConversationSimple (conversationId, token) {
  1887. // 检查是否有正在进行的流式响应
  1888. const hasActiveStream = window.conversationStates && window.conversationStates.has(conversationId);
  1889. const streamState = hasActiveStream ? window.conversationStates.get(conversationId) : null;
  1890. // 检查是否真正在流式响应(只要 isStreaming 为 true,无论是否有 messageElement)
  1891. const isActuallyStreaming = streamState && streamState.isStreaming;
  1892. // 检查是否有可用的消息元素(用于判断是否可以通过 updateExistingMessages 处理)
  1893. const hasMessageElement = streamState && streamState.messageElement && streamState.messageElement.parentNode;
  1894. // 返回 Promise
  1895. return fetch(`/api/conversations/${conversationId}`, {
  1896. method: 'GET',
  1897. headers: {
  1898. 'Authorization': `Bearer ${token}`,
  1899. 'Content-Type': 'application/json'
  1900. }
  1901. })
  1902. .then(response => {
  1903. if (response.status === 401) {
  1904. redirectToLogin();
  1905. return;
  1906. }
  1907. return response.json();
  1908. })
  1909. .then(data => {
  1910. if (data && data.success) {
  1911. const chatMessages = document.getElementById('chat-messages');
  1912. // 如果有正在进行的流式响应且有可用的消息元素,保留流式响应元素
  1913. if (isActuallyStreaming && hasMessageElement) {
  1914. // 保留流式响应的消息元素,只更新历史消息
  1915. updateExistingMessages(data.messages, streamState.messageElement);
  1916. } else {
  1917. // 清空聊天区域并重新渲染所有消息
  1918. chatMessages.innerHTML = '';
  1919. // 如果没有消息,显示提示语
  1920. if (!data.messages || data.messages.length === 0) {
  1921. renderAgentWelcomeMessage(getCurrentAgentType());
  1922. } else {
  1923. renderAllMessages(data.messages, chatMessages);
  1924. }
  1925. // 确保用户消息在切换对话后仍然可见
  1926. // 检查是否有未保存的用户消息
  1927. if (streamState && streamState.userMessages) {
  1928. streamState.userMessages.forEach(userMsg => {
  1929. // 检查用户消息是否已经在DOM中
  1930. const existingUserMsg = Array.from(chatMessages.children).find(msg =>
  1931. msg.classList.contains('user') &&
  1932. msg.querySelector('.message-content')?.textContent === userMsg.content
  1933. );
  1934. if (!existingUserMsg) {
  1935. // 如果用户消息不在DOM中,重新添加
  1936. chatMessages.appendChild(userMsg.element);
  1937. }
  1938. });
  1939. }
  1940. // ===== 恢复流式响应内容(无论是正在进行还是已完成但未保存到数据库) =====
  1941. // 检查数据库中是否已经包含了流式响应的内容
  1942. let shouldRestoreStreamContent = false;
  1943. // 如果流式响应正在进行,必须恢复显示
  1944. if (streamState && isActuallyStreaming) {
  1945. shouldRestoreStreamContent = true;
  1946. }
  1947. // 如果流式响应已完成,检查是否需要恢复(内容未保存到数据库)
  1948. else if (streamState && !isActuallyStreaming && (streamState.currentMessage || (streamState.currentThoughts && streamState.currentThoughts.length > 0))) {
  1949. // 检查数据库返回的最后一条 assistant 消息是否与流式响应的内容匹配
  1950. const dbMessages = data.messages || [];
  1951. const lastAssistantMsg = dbMessages.filter(msg => msg.role === 'assistant').pop();
  1952. if (lastAssistantMsg) {
  1953. // 如果最后一条 assistant 消息的内容与流式响应的内容匹配,说明内容已经保存到数据库
  1954. // 使用更精确的匹配:检查消息内容是否相同或包含流式响应的主要内容
  1955. let contentMatches = false;
  1956. if (streamState.currentMessage) {
  1957. const streamContent = streamState.currentMessage.trim();
  1958. const dbContent = lastAssistantMsg.content.trim();
  1959. // 精确匹配或检查前100个字符是否匹配(处理可能的截断)
  1960. contentMatches = (dbContent === streamContent) ||
  1961. (dbContent.length > 50 && streamContent.length > 50 &&
  1962. dbContent.substring(0, 100) === streamContent.substring(0, 100));
  1963. } else {
  1964. // 如果没有流式响应内容,认为匹配
  1965. contentMatches = true;
  1966. }
  1967. let thoughtsMatch = false;
  1968. if (streamState.currentThoughts && streamState.currentThoughts.length > 0) {
  1969. const streamThoughts = streamState.currentThoughts.join('').trim();
  1970. const dbThoughts = (lastAssistantMsg.thinking_content || '').trim();
  1971. thoughtsMatch = (dbThoughts === streamThoughts) ||
  1972. (dbThoughts.length > 50 && streamThoughts.length > 50 &&
  1973. dbThoughts.substring(0, 100) === streamThoughts.substring(0, 100));
  1974. } else {
  1975. // 如果流式响应没有思考过程,检查数据库是否有思考过程
  1976. thoughtsMatch = !lastAssistantMsg.thinking_content || lastAssistantMsg.thinking_content.trim() === '';
  1977. }
  1978. // 只有当内容不匹配时,才需要恢复流式响应的内容
  1979. shouldRestoreStreamContent = !contentMatches || !thoughtsMatch;
  1980. } else {
  1981. // 如果数据库中没有 assistant 消息,说明确实需要恢复流式响应的内容
  1982. shouldRestoreStreamContent = true;
  1983. }
  1984. // 如果内容已保存在数据库中,清除流式响应状态以避免下次重复检查
  1985. if (!shouldRestoreStreamContent) {
  1986. streamState.currentMessage = '';
  1987. streamState.currentThoughts = [];
  1988. }
  1989. }
  1990. if (shouldRestoreStreamContent && streamState) {
  1991. // 如果流式响应正在进行或已完成,但消息元素不在DOM中,需要重新创建或恢复
  1992. let restoredMessageElement = streamState.messageElement;
  1993. // 如果流式响应正在进行,确保消息元素存在
  1994. const isStreamingNow = streamState.isStreaming;
  1995. // 如果消息元素不存在或不在DOM中
  1996. if (!restoredMessageElement) {
  1997. // 消息元素不存在,需要创建
  1998. restoredMessageElement = document.createElement('div');
  1999. restoredMessageElement.className = 'message bot';
  2000. // 创建思考过程容器(如果有)
  2001. if (streamState.currentThoughts && streamState.currentThoughts.length > 0) {
  2002. const thoughtContainer = document.createElement('div');
  2003. thoughtContainer.className = 'thought-container';
  2004. const thoughtToggleBtn = document.createElement('button');
  2005. thoughtToggleBtn.className = 'thought-toggle-btn';
  2006. thoughtToggleBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  2007. thoughtToggleBtn.title = '收起/展开思考过程';
  2008. thoughtToggleBtn.onclick = function (e) {
  2009. e.stopPropagation();
  2010. thoughtContainer.classList.toggle('collapsed');
  2011. };
  2012. const thoughtContent = document.createElement('div');
  2013. thoughtContent.className = 'thought-content';
  2014. if (typeof window.renderThoughts === 'function') {
  2015. thoughtContent.innerHTML = window.renderThoughts(streamState.currentThoughts.join(''));
  2016. } else {
  2017. thoughtContent.textContent = streamState.currentThoughts.join('');
  2018. }
  2019. thoughtContainer.appendChild(thoughtToggleBtn);
  2020. thoughtContainer.appendChild(thoughtContent);
  2021. restoredMessageElement.appendChild(thoughtContainer);
  2022. // 更新状态中的引用
  2023. streamState.thoughtContainer = thoughtContainer;
  2024. }
  2025. // 创建消息内容容器
  2026. const contentContainer = document.createElement('div');
  2027. // 如果流式响应正在进行,添加 typing 类名
  2028. contentContainer.className = isStreamingNow ? 'message-content typing' : 'message-content';
  2029. if (streamState.currentMessage) {
  2030. if (typeof window.renderMarkdown === 'function') {
  2031. contentContainer.innerHTML = window.renderMarkdown(streamState.currentMessage);
  2032. if (typeof window.applyCodeHighlighting === 'function') {
  2033. window.applyCodeHighlighting(contentContainer);
  2034. }
  2035. } else {
  2036. contentContainer.textContent = streamState.currentMessage;
  2037. }
  2038. }
  2039. restoredMessageElement.appendChild(contentContainer);
  2040. // 保存 contentContainer 引用到状态中,以便流式响应继续更新
  2041. if (isStreamingNow && contentContainer) {
  2042. // 确保状态中的消息元素引用正确
  2043. streamState.messageElement = restoredMessageElement;
  2044. }
  2045. // 添加到聊天区域
  2046. chatMessages.appendChild(restoredMessageElement);
  2047. // 添加对话ID标识,便于后续管理
  2048. restoredMessageElement.setAttribute('data-conversation-id', conversationId);
  2049. // 更新状态中的引用(确保流式响应能够继续更新)
  2050. streamState.messageElement = restoredMessageElement;
  2051. // 如果流式响应正在进行,确保恢复后能够继续更新
  2052. if (isStreamingNow) {
  2053. // 确保消息元素可见
  2054. restoredMessageElement.style.opacity = '1';
  2055. restoredMessageElement.style.transform = 'translateY(0)';
  2056. // 滚动到底部以看到实时更新
  2057. setTimeout(() => {
  2058. chatMessages.scrollTop = chatMessages.scrollHeight;
  2059. }, 100);
  2060. }
  2061. } else if (!restoredMessageElement.parentNode) {
  2062. // 消息元素存在但不在DOM中,需要重新添加到DOM
  2063. chatMessages.appendChild(restoredMessageElement);
  2064. // 确保消息元素可见
  2065. restoredMessageElement.style.opacity = '1';
  2066. restoredMessageElement.style.transform = 'translateY(0)';
  2067. // 如果流式响应正在进行,滚动到底部
  2068. if (isStreamingNow) {
  2069. setTimeout(() => {
  2070. chatMessages.scrollTop = chatMessages.scrollHeight;
  2071. }, 100);
  2072. }
  2073. } else {
  2074. // 如果消息元素还在DOM中,只需要确保内容是最新的
  2075. const contentContainer = restoredMessageElement.querySelector('.message-content');
  2076. if (contentContainer) {
  2077. // 如果流式响应正在进行,确保有 typing 类名
  2078. if (isStreamingNow && !contentContainer.classList.contains('typing')) {
  2079. contentContainer.classList.add('typing');
  2080. } else if (!isStreamingNow && contentContainer.classList.contains('typing')) {
  2081. contentContainer.classList.remove('typing');
  2082. }
  2083. // 更新内容
  2084. if (streamState.currentMessage) {
  2085. if (typeof window.renderMarkdown === 'function') {
  2086. contentContainer.innerHTML = window.renderMarkdown(streamState.currentMessage);
  2087. if (typeof window.applyCodeHighlighting === 'function') {
  2088. window.applyCodeHighlighting(contentContainer);
  2089. }
  2090. } else {
  2091. contentContainer.textContent = streamState.currentMessage;
  2092. }
  2093. }
  2094. }
  2095. // 恢复思考过程
  2096. if (streamState.thoughtContainer && streamState.currentThoughts && streamState.currentThoughts.length > 0) {
  2097. const thoughtContent = streamState.thoughtContainer.querySelector('.thought-content');
  2098. if (thoughtContent) {
  2099. if (typeof window.renderThoughts === 'function') {
  2100. thoughtContent.innerHTML = window.renderThoughts(streamState.currentThoughts.join(''));
  2101. } else {
  2102. thoughtContent.textContent = streamState.currentThoughts.join('');
  2103. }
  2104. }
  2105. }
  2106. }
  2107. // 确保消息元素可见
  2108. restoredMessageElement.style.opacity = '1';
  2109. restoredMessageElement.style.transform = 'translateY(0)';
  2110. // 为新恢复的消息添加复制按钮
  2111. if (typeof window.setupCopyButtons === 'function') {
  2112. window.setupCopyButtons();
  2113. }
  2114. }
  2115. }
  2116. // 更新当前对话ID和session_id
  2117. window.currentConversationId = conversationId;
  2118. if (data.conversation && data.conversation.session_id) {
  2119. window.currentSessionId = data.conversation.session_id;
  2120. }
  2121. // 更新输入框状态 - 确保切换对话时输入框状态正确
  2122. if (typeof updateInputUIForConversation === 'function') {
  2123. updateInputUIForConversation(conversationId);
  2124. } else if (typeof resetUIState === 'function') {
  2125. resetUIState();
  2126. }
  2127. // 滚动到底部
  2128. setTimeout(() => {
  2129. chatMessages.scrollTop = chatMessages.scrollHeight;
  2130. }, 100);
  2131. } else {
  2132. showMessage('加载对话失败: ' + (data ? data.error : '未知错误'), 'error');
  2133. }
  2134. })
  2135. .catch(error => {
  2136. showMessage('加载对话时发生错误: ' + error.message, 'error');
  2137. });
  2138. }
  2139. function updateExistingMessages (messages, streamElement) {
  2140. const chatMessages = document.getElementById('chat-messages');
  2141. const existingMessages = Array.from(chatMessages.children);
  2142. // 找到流式响应元素的位置
  2143. const streamIndex = existingMessages.indexOf(streamElement);
  2144. // 移除流式响应元素之前的所有消息(这些是历史消息)
  2145. for (let i = 0; i < streamIndex; i++) {
  2146. if (existingMessages[i] && existingMessages[i].parentNode) {
  2147. existingMessages[i].remove();
  2148. }
  2149. }
  2150. // 在流式响应元素之前插入所有历史消息
  2151. messages.forEach((msg, index) => {
  2152. // 显示所有历史消息,包括用户消息和AI回复
  2153. const messageDiv = createMessageElement(msg);
  2154. chatMessages.insertBefore(messageDiv, streamElement);
  2155. });
  2156. }
  2157. function renderAllMessages (messages, chatMessages) {
  2158. messages.forEach((msg, index) => {
  2159. const messageDiv = createMessageElement(msg);
  2160. chatMessages.appendChild(messageDiv);
  2161. });
  2162. }
  2163. function createMessageElement (msg) {
  2164. const messageDiv = document.createElement('div');
  2165. messageDiv.className = `message ${msg.role}`;
  2166. let content = msg.content;
  2167. // 如果是AI消息且有思考过程,添加思考容器
  2168. if (msg.role === 'assistant' && msg.thinking_content) {
  2169. // 使用思考过程专用的渲染函数
  2170. let thoughtHtml = '';
  2171. if (typeof window.renderThoughts === 'function') {
  2172. thoughtHtml = window.renderThoughts(msg.thinking_content);
  2173. } else if (typeof window.renderMarkdown === 'function') {
  2174. thoughtHtml = window.renderMarkdown(msg.thinking_content);
  2175. } else if (typeof showdown !== 'undefined') {
  2176. const converter = new showdown.Converter({
  2177. strikethrough: true,
  2178. tables: true,
  2179. tasklists: true,
  2180. ghCodeBlocks: true,
  2181. openLinksInNewWindow: true
  2182. });
  2183. thoughtHtml = converter.makeHtml(msg.thinking_content);
  2184. } else {
  2185. thoughtHtml = msg.thinking_content;
  2186. }
  2187. const thoughtContainerHtml = `
  2188. <div class="thought-container" data-collapsed="false">
  2189. <button class="thought-toggle-btn" onclick="toggleThought(this)">
  2190. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  2191. <path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2192. </svg>
  2193. </button>
  2194. <div class="thought-content">
  2195. ${thoughtHtml}
  2196. </div>
  2197. </div>
  2198. `;
  2199. content = thoughtContainerHtml + content;
  2200. }
  2201. // 使用统一的Markdown渲染函数渲染消息内容
  2202. let renderedContent = content;
  2203. if (msg.role === 'assistant') {
  2204. if (typeof window.renderMarkdown === 'function') {
  2205. // 只渲染消息内容部分,思考过程已经渲染过了
  2206. const messageContentOnly = msg.content;
  2207. renderedContent = msg.thinking_content ?
  2208. content.replace(msg.content, window.renderMarkdown(messageContentOnly)) :
  2209. window.renderMarkdown(messageContentOnly);
  2210. } else if (typeof showdown !== 'undefined') {
  2211. const converter = new showdown.Converter({
  2212. strikethrough: true,
  2213. tables: true,
  2214. tasklists: true,
  2215. ghCodeBlocks: true,
  2216. openLinksInNewWindow: true
  2217. });
  2218. // 只渲染消息内容部分,思考过程已经渲染过了
  2219. const messageContentOnly = msg.content;
  2220. renderedContent = msg.thinking_content ?
  2221. content.replace(msg.content, converter.makeHtml(messageContentOnly)) :
  2222. converter.makeHtml(messageContentOnly);
  2223. }
  2224. }
  2225. // 为用户消息添加编辑按钮
  2226. let messageContentHtml = `<div class="message-content">${renderedContent}</div>`;
  2227. if (msg.role === 'user' && msg.message_id) {
  2228. // 转义特殊字符,防止XSS攻击
  2229. const escapedContent = msg.content.replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  2230. messageContentHtml = `
  2231. <div class="message-content">${renderedContent}</div>
  2232. <button class="edit-button" onclick="editMessage(${msg.message_id}, '${escapedContent}')" title="编辑消息">
  2233. <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  2234. <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2235. <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2236. </svg>
  2237. </button>
  2238. `;
  2239. }
  2240. messageDiv.innerHTML = messageContentHtml;
  2241. // 为用户消息添加data-message-id属性
  2242. if (msg.role === 'user' && msg.message_id) {
  2243. messageDiv.setAttribute('data-message-id', msg.message_id);
  2244. }
  2245. // 确保消息立即可见
  2246. messageDiv.style.opacity = '1';
  2247. messageDiv.style.transform = 'translateY(0)';
  2248. // 应用代码高亮和表格处理
  2249. if (typeof applyCodeHighlighting === 'function') {
  2250. applyCodeHighlighting(messageDiv);
  2251. }
  2252. if (typeof processAuditResultTables === 'function') {
  2253. processAuditResultTables();
  2254. }
  2255. // 为历史消息添加复制按钮
  2256. if (typeof window.setupCopyButtons === 'function') {
  2257. window.setupCopyButtons();
  2258. }
  2259. return messageDiv;
  2260. }
  2261. function updateConversationSelection (conversationId) {
  2262. const conversationItems = document.querySelectorAll('.conversation-item');
  2263. conversationItems.forEach(item => {
  2264. const itemId = item.getAttribute('data-conversation-id');
  2265. if (itemId === conversationId) {
  2266. item.classList.add('active');
  2267. // 确保状态点显示
  2268. const statusDot = item.querySelector('.conversation-status-dot');
  2269. if (statusDot) {
  2270. statusDot.style.opacity = '1';
  2271. }
  2272. } else {
  2273. item.classList.remove('active');
  2274. // 移除非活跃对话的状态类
  2275. item.classList.remove('streaming', 'paused');
  2276. const statusDot = item.querySelector('.conversation-status-dot');
  2277. if (statusDot) {
  2278. statusDot.style.opacity = '0';
  2279. }
  2280. }
  2281. });
  2282. }
  2283. function updateConversationStatus (conversationId, status) {
  2284. const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
  2285. if (conversationItem) {
  2286. const statusDot = conversationItem.querySelector('.conversation-status-dot');
  2287. // 移除所有状态类
  2288. conversationItem.classList.remove('streaming', 'paused');
  2289. // 添加新的状态类
  2290. if (status === 'streaming') {
  2291. conversationItem.classList.add('streaming');
  2292. if (statusDot) {
  2293. statusDot.style.opacity = '1';
  2294. statusDot.style.background = '#10b981';
  2295. }
  2296. } else if (status === 'paused') {
  2297. conversationItem.classList.add('paused');
  2298. if (statusDot) {
  2299. statusDot.style.opacity = '1';
  2300. statusDot.style.background = '#f59e0b';
  2301. }
  2302. } else if (status === 'stopped') {
  2303. if (statusDot) {
  2304. statusDot.style.opacity = '0';
  2305. }
  2306. }
  2307. }
  2308. }
  2309. function showConversationMenu (conversationId, button) {
  2310. // 创建菜单
  2311. const menu = document.createElement('div');
  2312. menu.className = 'conversation-context-menu';
  2313. menu.innerHTML = `
  2314. <div class="menu-item" data-action="rename">
  2315. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  2316. <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2317. <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2318. </svg>
  2319. 重命名
  2320. </div>
  2321. <div class="menu-item" data-action="delete">
  2322. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  2323. <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2324. </svg>
  2325. 删除
  2326. </div>
  2327. `;
  2328. // 添加样式
  2329. menu.style.cssText = `
  2330. position: absolute;
  2331. background: rgba(255, 255, 255, 0.95);
  2332. backdrop-filter: blur(20px);
  2333. border: 1px solid rgba(255, 255, 255, 0.3);
  2334. border-radius: 8px;
  2335. box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  2336. padding: 8px 0;
  2337. min-width: 120px;
  2338. z-index: 1000;
  2339. opacity: 0;
  2340. transform: scale(0.9);
  2341. transition: all 0.2s ease;
  2342. `;
  2343. // 定位菜单
  2344. const rect = button.getBoundingClientRect();
  2345. menu.style.left = (rect.left - 100) + 'px';
  2346. menu.style.top = (rect.bottom + 5) + 'px';
  2347. // 添加到页面
  2348. document.body.appendChild(menu);
  2349. // 显示动画
  2350. setTimeout(() => {
  2351. menu.style.opacity = '1';
  2352. menu.style.transform = 'scale(1)';
  2353. }, 10);
  2354. // 菜单项点击事件
  2355. menu.querySelectorAll('.menu-item').forEach(item => {
  2356. item.addEventListener('click', function () {
  2357. const action = this.getAttribute('data-action');
  2358. handleConversationAction(action, conversationId);
  2359. closeMenu();
  2360. });
  2361. });
  2362. // 点击外部关闭菜单
  2363. function closeMenu () {
  2364. menu.style.opacity = '0';
  2365. menu.style.transform = 'scale(0.9)';
  2366. setTimeout(() => {
  2367. if (menu.parentNode) {
  2368. menu.parentNode.removeChild(menu);
  2369. }
  2370. }, 200);
  2371. }
  2372. // 点击外部关闭
  2373. document.addEventListener('click', function closeOnOutsideClick (e) {
  2374. if (!menu.contains(e.target) && e.target !== button) {
  2375. closeMenu();
  2376. document.removeEventListener('click', closeOnOutsideClick);
  2377. }
  2378. });
  2379. }
  2380. function handleConversationAction (action, conversationId) {
  2381. switch (action) {
  2382. case 'rename':
  2383. renameConversation(conversationId);
  2384. break;
  2385. case 'delete':
  2386. deleteConversation(conversationId);
  2387. break;
  2388. }
  2389. }
  2390. function renameConversation (conversationId) {
  2391. // 检查认证状态
  2392. const token = localStorage.getItem('auth_token');
  2393. if (!token) {
  2394. redirectToLogin();
  2395. return;
  2396. }
  2397. // 获取当前对话标题
  2398. const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
  2399. const currentTitle = conversationItem ? conversationItem.querySelector('.conversation-title').textContent : '';
  2400. // 设置输入框的值
  2401. const renameInput = document.getElementById('rename-input');
  2402. if (renameInput) {
  2403. renameInput.value = currentTitle;
  2404. renameInput.focus();
  2405. renameInput.select();
  2406. }
  2407. // 显示重命名弹框
  2408. showModal('rename-modal');
  2409. // 绑定确认按钮事件
  2410. const confirmBtn = document.getElementById('confirm-rename-btn');
  2411. if (confirmBtn) {
  2412. confirmBtn.onclick = function () {
  2413. const newTitle = renameInput.value.trim();
  2414. if (newTitle && newTitle !== currentTitle) {
  2415. performRename(conversationId, newTitle, token);
  2416. } else if (!newTitle) {
  2417. showMessage('请输入新的对话标题', 'warning');
  2418. } else {
  2419. closeModal('rename-modal');
  2420. }
  2421. };
  2422. }
  2423. // 绑定回车键事件
  2424. if (renameInput) {
  2425. renameInput.onkeydown = function (e) {
  2426. if (e.key === 'Enter') {
  2427. confirmBtn.click();
  2428. } else if (e.key === 'Escape') {
  2429. closeModal('rename-modal');
  2430. }
  2431. };
  2432. }
  2433. }
  2434. function performRename (conversationId, newTitle, token) {
  2435. fetch(`/api/conversations/${conversationId}/rename`, {
  2436. method: 'POST',
  2437. headers: {
  2438. 'Authorization': `Bearer ${token}`,
  2439. 'Content-Type': 'application/json'
  2440. },
  2441. body: JSON.stringify({
  2442. title: newTitle
  2443. })
  2444. })
  2445. .then(response => {
  2446. if (response.status === 401) {
  2447. redirectToLogin();
  2448. return;
  2449. }
  2450. return response.json();
  2451. })
  2452. .then(data => {
  2453. if (data && data.success) {
  2454. const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
  2455. if (conversationItem) {
  2456. const titleElement = conversationItem.querySelector('.conversation-title');
  2457. if (titleElement) {
  2458. titleElement.textContent = newTitle;
  2459. }
  2460. }
  2461. closeModal('rename-modal');
  2462. showMessage('对话标题已更新');
  2463. } else {
  2464. showMessage('重命名失败: ' + (data ? data.error : '未知错误'), 'error');
  2465. }
  2466. })
  2467. .catch(error => {
  2468. showMessage('重命名对话时发生错误: ' + error.message, 'error');
  2469. });
  2470. }
  2471. function deleteConversation (conversationId) {
  2472. // 检查认证状态
  2473. const token = localStorage.getItem('auth_token');
  2474. if (!token) {
  2475. redirectToLogin();
  2476. return;
  2477. }
  2478. // 显示删除确认弹框
  2479. showModal('delete-modal');
  2480. // 绑定确认删除按钮事件
  2481. const confirmBtn = document.getElementById('confirm-delete-btn');
  2482. if (confirmBtn) {
  2483. confirmBtn.onclick = function () {
  2484. performDelete(conversationId, token);
  2485. };
  2486. }
  2487. }
  2488. function performDelete (conversationId, token) {
  2489. fetch(`/api/conversations/${conversationId}`, {
  2490. method: 'DELETE',
  2491. headers: {
  2492. 'Authorization': `Bearer ${token}`,
  2493. 'Content-Type': 'application/json'
  2494. }
  2495. })
  2496. .then(response => {
  2497. if (response.status === 401) {
  2498. redirectToLogin();
  2499. return;
  2500. }
  2501. return response.json();
  2502. })
  2503. .then(data => {
  2504. if (data && data.success) {
  2505. const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
  2506. if (conversationItem) {
  2507. conversationItem.remove();
  2508. }
  2509. closeModal('delete-modal');
  2510. showMessage('对话已删除');
  2511. // 如果删除的是当前对话,清除当前对话ID
  2512. if (window.currentConversationId === conversationId) {
  2513. window.currentConversationId = null;
  2514. // 清空聊天区域
  2515. const chatMessages = document.getElementById('chat-messages');
  2516. if (chatMessages) {
  2517. chatMessages.innerHTML = '';
  2518. }
  2519. }
  2520. } else {
  2521. showMessage('删除失败: ' + (data ? data.error : '未知错误'), 'error');
  2522. }
  2523. })
  2524. .catch(error => {
  2525. showMessage('删除对话时发生错误: ' + error.message, 'error');
  2526. });
  2527. }
  2528. function loadConversationHistory (autoSelectLatest = false) {
  2529. // 检查认证状态
  2530. const token = localStorage.getItem('auth_token');
  2531. if (!token) {
  2532. redirectToLogin();
  2533. return;
  2534. }
  2535. // 从服务器加载历史记录
  2536. fetch('/api/conversations', {
  2537. method: 'GET',
  2538. headers: {
  2539. 'Authorization': `Bearer ${token}`,
  2540. 'Content-Type': 'application/json'
  2541. }
  2542. })
  2543. .then(response => {
  2544. if (response.status === 401) {
  2545. // 认证失败,清除本地存储并重定向到登录页面
  2546. redirectToLogin();
  2547. return;
  2548. }
  2549. return response.json();
  2550. })
  2551. .then(data => {
  2552. if (data && data.success) {
  2553. updateHistorySidebar(data.conversations, autoSelectLatest);
  2554. } else {
  2555. // 显示空状态
  2556. const historyLoading = document.getElementById('history-loading');
  2557. const historyEmpty = document.getElementById('history-empty');
  2558. if (historyLoading) historyLoading.style.display = 'none';
  2559. if (historyEmpty) historyEmpty.style.display = 'block';
  2560. }
  2561. })
  2562. .catch(error => {
  2563. // 显示空状态
  2564. const historyLoading = document.getElementById('history-loading');
  2565. const historyEmpty = document.getElementById('history-empty');
  2566. if (historyLoading) historyLoading.style.display = 'none';
  2567. if (historyEmpty) historyEmpty.style.display = 'block';
  2568. });
  2569. }
  2570. // 将loadConversationHistory函数暴露到全局作用域,供chat.js调用
  2571. window.loadConversationHistory = loadConversationHistory;
  2572. function updateHistorySidebar (conversations, autoSelectLatest = false) {
  2573. // 更新侧边栏的历史记录
  2574. const historyContent = document.querySelector('.history-content');
  2575. const historyLoading = document.getElementById('history-loading');
  2576. const historyEmpty = document.getElementById('history-empty');
  2577. if (!historyContent) {
  2578. return;
  2579. }
  2580. // 隐藏加载状态
  2581. if (historyLoading) {
  2582. historyLoading.style.display = 'none';
  2583. }
  2584. // 清空现有内容
  2585. historyContent.innerHTML = '';
  2586. // 检查是否有任何对话
  2587. const hasAnyConversations = Object.values(conversations).some(group => group && group.length > 0);
  2588. if (!hasAnyConversations) {
  2589. // 显示空状态
  2590. if (historyEmpty) {
  2591. historyEmpty.style.display = 'block';
  2592. }
  2593. return;
  2594. }
  2595. // 隐藏空状态
  2596. if (historyEmpty) {
  2597. historyEmpty.style.display = 'none';
  2598. }
  2599. // 按时间分组渲染
  2600. const timeGroups = [
  2601. { key: 'today', label: '今天' },
  2602. { key: 'yesterday', label: '昨天' },
  2603. { key: 'week', label: '7天内' },
  2604. { key: 'month', label: '30天内' }
  2605. ];
  2606. timeGroups.forEach(group => {
  2607. const groupConversations = conversations[group.key] || [];
  2608. if (groupConversations.length === 0) return;
  2609. // 创建分组容器
  2610. const groupDiv = document.createElement('div');
  2611. groupDiv.className = 'history-group';
  2612. // 分组标题
  2613. const headerDiv = document.createElement('div');
  2614. headerDiv.className = 'group-header';
  2615. headerDiv.textContent = group.label;
  2616. // 对话列表
  2617. const listDiv = document.createElement('div');
  2618. listDiv.className = 'conversation-list';
  2619. groupConversations.forEach(conv => {
  2620. const itemDiv = document.createElement('div');
  2621. itemDiv.className = 'conversation-item';
  2622. itemDiv.setAttribute('data-conversation-id', conv.conversation_id);
  2623. itemDiv.setAttribute('data-session-id', conv.session_id || '');
  2624. // 格式化时间显示
  2625. const lastMessageTime = conv.last_message_at ? new Date(conv.last_message_at).toLocaleTimeString('zh-CN', {
  2626. hour: '2-digit',
  2627. minute: '2-digit'
  2628. }) : '';
  2629. itemDiv.innerHTML = `
  2630. <div class="conversation-content">
  2631. <div class="conversation-title">${conv.title}</div>
  2632. <div class="conversation-meta">
  2633. <span class="message-count">${conv.message_count}条消息</span>
  2634. ${lastMessageTime ? `<span class="last-time">${lastMessageTime}</span>` : ''}
  2635. </div>
  2636. </div>
  2637. <div class="conversation-status-dot"></div>
  2638. <button class="conversation-menu" data-conversation-id="${conv.conversation_id}">
  2639. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  2640. <circle cx="12" cy="12" r="1" fill="currentColor"/>
  2641. <circle cx="19" cy="12" r="1" fill="currentColor"/>
  2642. <circle cx="5" cy="12" r="1" fill="currentColor"/>
  2643. </svg>
  2644. </button>
  2645. `;
  2646. listDiv.appendChild(itemDiv);
  2647. });
  2648. groupDiv.appendChild(headerDiv);
  2649. groupDiv.appendChild(listDiv);
  2650. historyContent.appendChild(groupDiv);
  2651. });
  2652. // 重新绑定事件
  2653. bindConversationEvents();
  2654. // 自动选中对话
  2655. const firstConversationItem = document.querySelector('.conversation-item');
  2656. if (firstConversationItem) {
  2657. const conversationId = firstConversationItem.getAttribute('data-conversation-id');
  2658. if (autoSelectLatest) {
  2659. // 新对话完成后,选中最新的对话,但不加载内容(保持提示语显示)
  2660. updateConversationSelection(conversationId);
  2661. // 不调用 loadConversation,保持提示语显示
  2662. } else if (!window.currentConversationId) {
  2663. // 页面初始加载时,选中第一个对话
  2664. updateConversationSelection(conversationId);
  2665. loadConversation(conversationId);
  2666. }
  2667. }
  2668. }
  2669. function bindConversationEvents () {
  2670. // 重新绑定对话项点击事件
  2671. const conversationItems = document.querySelectorAll('.conversation-item');
  2672. conversationItems.forEach(item => {
  2673. item.addEventListener('click', function (e) {
  2674. if (e.target.closest('.conversation-menu')) {
  2675. return;
  2676. }
  2677. const conversationId = this.getAttribute('data-conversation-id');
  2678. const sessionId = this.getAttribute('data-session-id');
  2679. // 设置当前对话的session_id
  2680. if (sessionId) {
  2681. window.currentSessionId = sessionId;
  2682. }
  2683. // 设置激活的对话
  2684. if (typeof setActiveConversation === 'function') {
  2685. setActiveConversation(conversationId);
  2686. }
  2687. loadConversation(conversationId);
  2688. updateConversationSelection(conversationId);
  2689. // 移动端关闭侧边栏
  2690. const isMobile = window.innerWidth <= 768;
  2691. if (isMobile) {
  2692. const sidebar = document.getElementById('history-sidebar');
  2693. const sidebarOverlay = document.getElementById('sidebar-overlay');
  2694. if (sidebar && sidebarOverlay) {
  2695. sidebar.classList.remove('show');
  2696. sidebarOverlay.classList.remove('show');
  2697. document.body.style.overflow = '';
  2698. }
  2699. }
  2700. });
  2701. });
  2702. // 重新绑定对话菜单事件
  2703. const conversationMenus = document.querySelectorAll('.conversation-menu');
  2704. conversationMenus.forEach(menu => {
  2705. menu.addEventListener('click', function (e) {
  2706. e.stopPropagation();
  2707. const conversationId = this.getAttribute('data-conversation-id');
  2708. showConversationMenu(conversationId, this);
  2709. });
  2710. });
  2711. }
  2712. function syncSidebarUserInfo () {
  2713. const userInfo = localStorage.getItem('user_info');
  2714. if (userInfo) {
  2715. try {
  2716. const user = JSON.parse(userInfo);
  2717. const sidebarUserName = document.getElementById('sidebar-user-name');
  2718. const sidebarAvatarImg = document.getElementById('sidebar-avatar-img');
  2719. const sidebarAvatarFallback = document.getElementById('sidebar-avatar-fallback');
  2720. if (sidebarUserName) {
  2721. const displayName = user.nickname || user.name || '用户';
  2722. sidebarUserName.textContent = displayName;
  2723. }
  2724. if (sidebarAvatarImg && user.avatar && user.avatar.trim() !== '') {
  2725. sidebarAvatarImg.src = user.avatar;
  2726. sidebarAvatarImg.style.display = 'block';
  2727. sidebarAvatarFallback.style.display = 'none';
  2728. } else if (sidebarAvatarFallback) {
  2729. sidebarAvatarImg.style.display = 'none';
  2730. sidebarAvatarFallback.style.display = 'flex';
  2731. const displayName = user.nickname || user.name || 'U';
  2732. sidebarAvatarFallback.textContent = displayName.charAt(0).toUpperCase();
  2733. }
  2734. } catch (e) {
  2735. }
  2736. }
  2737. }
  2738. // 编辑消息功能
  2739. let currentEditMessageId = null;
  2740. let currentEditMessageElement = null;
  2741. window.isEditingMessage = false; // 设置为全局变量
  2742. window.editMessage = function (messageId, originalContent) {
  2743. // 如果已经在编辑其他消息,先取消
  2744. if (currentEditMessageElement) {
  2745. cancelEdit();
  2746. }
  2747. currentEditMessageId = messageId;
  2748. // 找到对应的消息元素
  2749. const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
  2750. if (!messageElement) {
  2751. console.error('找不到消息元素');
  2752. return;
  2753. }
  2754. currentEditMessageElement = messageElement;
  2755. window.isEditingMessage = true; // 设置编辑状态
  2756. // 保存当前滚动位置
  2757. const chatMessages = document.getElementById('chat-messages');
  2758. const currentScrollTop = chatMessages.scrollTop;
  2759. // 解码HTML实体
  2760. const decodedContent = originalContent
  2761. .replace(/&quot;/g, '"')
  2762. .replace(/&#39;/g, "'")
  2763. .replace(/&lt;/g, '<')
  2764. .replace(/&gt;/g, '>')
  2765. .replace(/&amp;/g, '&');
  2766. // 创建编辑表单
  2767. const editForm = document.createElement('div');
  2768. editForm.className = 'edit-form';
  2769. editForm.innerHTML = `
  2770. <textarea class="edit-textarea" placeholder="请输入消息内容...">${decodedContent}</textarea>
  2771. <div class="edit-actions">
  2772. <button class="edit-cancel-btn" onclick="cancelEdit()">取消</button>
  2773. <button class="edit-send-btn" onclick="confirmEdit()">发送</button>
  2774. </div>
  2775. `;
  2776. // 隐藏原始消息内容,显示编辑表单
  2777. const messageContent = messageElement.querySelector('.message-content');
  2778. if (messageContent) {
  2779. messageContent.style.display = 'none';
  2780. }
  2781. // 隐藏编辑按钮
  2782. const editButton = messageElement.querySelector('.edit-button');
  2783. if (editButton) {
  2784. editButton.style.display = 'none';
  2785. }
  2786. // 添加编辑表单到消息元素
  2787. messageElement.appendChild(editForm);
  2788. messageElement.classList.add('message-editing');
  2789. // 恢复滚动位置
  2790. chatMessages.scrollTop = currentScrollTop;
  2791. // 聚焦到文本域
  2792. const textarea = editForm.querySelector('.edit-textarea');
  2793. if (textarea) {
  2794. textarea.focus();
  2795. textarea.select();
  2796. // 绑定键盘事件:Enter 发送(Shift+Enter 换行),Esc 取消
  2797. textarea.onkeydown = function (e) {
  2798. if (e.key === 'Enter') {
  2799. if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey || e.isComposing) {
  2800. return; // 保留换行/组合键
  2801. }
  2802. e.preventDefault();
  2803. confirmEdit();
  2804. } else if (e.key === 'Escape') {
  2805. cancelEdit();
  2806. }
  2807. };
  2808. }
  2809. }
  2810. function cancelEdit () {
  2811. if (currentEditMessageElement) {
  2812. // 保存当前滚动位置
  2813. const chatMessages = document.getElementById('chat-messages');
  2814. const currentScrollTop = chatMessages.scrollTop;
  2815. // 恢复原始消息内容
  2816. const messageContent = currentEditMessageElement.querySelector('.message-content');
  2817. if (messageContent) {
  2818. messageContent.style.display = 'block';
  2819. }
  2820. // 显示编辑按钮
  2821. const editButton = currentEditMessageElement.querySelector('.edit-button');
  2822. if (editButton) {
  2823. editButton.style.display = 'flex';
  2824. }
  2825. // 移除编辑表单
  2826. const editForm = currentEditMessageElement.querySelector('.edit-form');
  2827. if (editForm) {
  2828. editForm.remove();
  2829. }
  2830. currentEditMessageElement.classList.remove('message-editing');
  2831. // 先恢复滚动位置,再清除编辑状态
  2832. chatMessages.scrollTop = currentScrollTop;
  2833. // 延迟清除编辑状态,确保DOM变化不会触发滚动
  2834. setTimeout(() => {
  2835. currentEditMessageElement = null;
  2836. currentEditMessageId = null;
  2837. window.isEditingMessage = false;
  2838. }, 150);
  2839. }
  2840. }
  2841. function confirmEdit () {
  2842. if (!currentEditMessageElement || !currentEditMessageId) {
  2843. return;
  2844. }
  2845. const editForm = currentEditMessageElement.querySelector('.edit-form');
  2846. const textarea = editForm.querySelector('.edit-textarea');
  2847. const sendBtn = editForm.querySelector('.edit-send-btn');
  2848. if (!textarea || !sendBtn) {
  2849. return;
  2850. }
  2851. const newContent = textarea.value.trim();
  2852. if (!newContent) {
  2853. showMessage('消息内容不能为空', 'warning');
  2854. return;
  2855. }
  2856. // 显示加载状态
  2857. const originalText = sendBtn.textContent;
  2858. sendBtn.textContent = '发送中...';
  2859. sendBtn.disabled = true;
  2860. // 调用后端API编辑消息
  2861. performEditMessage(currentEditMessageId, newContent);
  2862. }
  2863. function performEditMessage (messageId, newContent) {
  2864. // 检查认证状态
  2865. const token = localStorage.getItem('auth_token');
  2866. if (!token) {
  2867. redirectToLogin();
  2868. return;
  2869. }
  2870. // 设置输入框为加载状态
  2871. const userInput = document.getElementById('user-input');
  2872. const sendButton = document.getElementById('send-btn');
  2873. if (userInput && sendButton) {
  2874. userInput.classList.add('input-loading');
  2875. userInput.placeholder = '正在重新生成回复...';
  2876. userInput.disabled = true;
  2877. sendButton.innerHTML = `
  2878. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  2879. <rect x="6" y="6" width="12" height="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  2880. </svg>`;
  2881. sendButton.classList.add('stopping');
  2882. }
  2883. // 隐藏编辑表单
  2884. if (currentEditMessageElement) {
  2885. const editForm = currentEditMessageElement.querySelector('.edit-form');
  2886. if (editForm) {
  2887. editForm.style.display = 'none';
  2888. }
  2889. }
  2890. // ===== 立即隐藏将被删除的消息(编辑的消息及其之后的所有消息) =====
  2891. const editMessageElement = currentEditMessageElement;
  2892. const chatMessages = document.getElementById('chat-messages');
  2893. let messagesToHide = [];
  2894. if (editMessageElement && chatMessages) {
  2895. let foundEditMessage = false;
  2896. const allMessages = Array.from(chatMessages.querySelectorAll('.message'));
  2897. allMessages.forEach(msg => {
  2898. if (msg === editMessageElement) {
  2899. foundEditMessage = true;
  2900. messagesToHide.push(msg);
  2901. // 立即隐藏消息(但保留DOM元素,后续再删除)
  2902. msg.style.display = 'none';
  2903. } else if (foundEditMessage) {
  2904. messagesToHide.push(msg);
  2905. // 立即隐藏消息
  2906. msg.style.display = 'none';
  2907. }
  2908. });
  2909. }
  2910. // 创建新的用户消息显示(立即显示编辑后的内容)
  2911. function createNewUserMessageImmediately () {
  2912. const chatMessages = document.getElementById('chat-messages');
  2913. if (!chatMessages) return null;
  2914. const newUserMessageElement = document.createElement('div');
  2915. newUserMessageElement.className = 'message user';
  2916. const contentElement = document.createElement('div');
  2917. contentElement.className = 'message-content';
  2918. contentElement.textContent = newContent;
  2919. newUserMessageElement.appendChild(contentElement);
  2920. // 重新对话添加编辑按钮
  2921. if (typeof messageId !== 'undefined' && messageId !== null) {
  2922. const editButton = document.createElement('button');
  2923. editButton.className = 'edit-button';
  2924. editButton.setAttribute('title', '编辑消息');
  2925. editButton.innerHTML = `<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
  2926. editButton.onclick = function () {
  2927. if (typeof window.editMessage === 'function') window.editMessage(messageId, newContent);
  2928. };
  2929. newUserMessageElement.appendChild(editButton);
  2930. newUserMessageElement.setAttribute('data-message-id', messageId);
  2931. }
  2932. chatMessages.appendChild(newUserMessageElement);
  2933. // 确保消息立即可见
  2934. newUserMessageElement.style.opacity = '1';
  2935. newUserMessageElement.style.transform = 'translateY(0)';
  2936. return newUserMessageElement;
  2937. }
  2938. // 立即创建并显示新的用户消息
  2939. const newUserMessageElement = createNewUserMessageImmediately();
  2940. // ===== 初始化对话状态(参考正常发送消息的逻辑) =====
  2941. const conversationId = window.currentConversationId || 'new';
  2942. // 初始化对话状态(如果不存在)
  2943. if (typeof window.initializeConversationState === 'function') {
  2944. window.initializeConversationState(conversationId);
  2945. }
  2946. // 获取或创建对话状态
  2947. const conversationStates = window.conversationStates || new Map();
  2948. const state = conversationStates.get(conversationId) || {
  2949. isStreaming: false,
  2950. isPaused: false,
  2951. currentMessage: '',
  2952. currentThoughts: [],
  2953. messageElement: null,
  2954. thoughtContainer: null,
  2955. abortController: null,
  2956. lastUpdateTime: Date.now(),
  2957. isVisible: false,
  2958. userMessages: []
  2959. };
  2960. // 重置流式响应状态
  2961. state.isStreaming = true;
  2962. state.isPaused = false;
  2963. state.currentMessage = '';
  2964. state.currentThoughts = [];
  2965. state.lastUpdateTime = Date.now();
  2966. state.isVisible = true;
  2967. // 保存用户消息到状态
  2968. if (!state.userMessages) {
  2969. state.userMessages = [];
  2970. }
  2971. state.userMessages.push({
  2972. content: newContent,
  2973. timestamp: new Date(),
  2974. element: newUserMessageElement,
  2975. messageId: messageId
  2976. });
  2977. // 更新状态映射
  2978. conversationStates.set(conversationId, state);
  2979. window.conversationStates = conversationStates;
  2980. // 更新侧边栏状态
  2981. if (typeof window.updateConversationItemStatus === 'function') {
  2982. window.updateConversationItemStatus(conversationId, 'streaming');
  2983. }
  2984. // ===== 创建AbortController用于取消请求(必须在fetch之前) =====
  2985. state.abortController = new AbortController();
  2986. conversationStates.set(conversationId, state);
  2987. // 调用后端API编辑消息(流式响应)
  2988. fetch(`/api/messages/${messageId}/edit`, {
  2989. method: 'POST',
  2990. headers: {
  2991. 'Authorization': `Bearer ${token}`,
  2992. 'Content-Type': 'application/json'
  2993. },
  2994. body: JSON.stringify({
  2995. content: newContent,
  2996. conversation_id: window.currentConversationId,
  2997. agent: localStorage.getItem('current_agent') || 'planning'
  2998. }),
  2999. signal: state.abortController.signal
  3000. })
  3001. .then(response => {
  3002. if (response.status === 401) {
  3003. // 恢复UI状态
  3004. if (userInput && sendButton) {
  3005. userInput.classList.remove('input-loading');
  3006. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  3007. userInput.disabled = false;
  3008. sendButton.innerHTML = `
  3009. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  3010. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  3011. </svg>`;
  3012. sendButton.classList.remove('stopping');
  3013. }
  3014. currentEditMessageElement = null;
  3015. currentEditMessageId = null;
  3016. window.isEditingMessage = false;
  3017. redirectToLogin();
  3018. return;
  3019. }
  3020. if (!response.ok) {
  3021. throw new Error(`HTTP error! Status: ${response.status}`);
  3022. }
  3023. // 使用流式读取器处理SSE响应
  3024. const reader = response.body.getReader();
  3025. const decoder = new TextDecoder();
  3026. let buffer = '';
  3027. // 用于实时渲染的变量(保存到state中,便于切换对话时恢复)
  3028. let fullMessage = '';
  3029. let allThoughts = [];
  3030. let thoughtContainer = null;
  3031. let thoughtContent = null;
  3032. let contentContainer = null;
  3033. let messageDiv = null;
  3034. // newUserMessageElement 已经在前面创建了
  3035. let lastRenderTime = 0;
  3036. const RENDER_INTERVAL = 16;
  3037. // 创建AI回复消息容器
  3038. function createBotMessageContainer () {
  3039. if (messageDiv) return messageDiv;
  3040. messageDiv = document.createElement('div');
  3041. messageDiv.className = 'message bot';
  3042. // 添加对话ID标识,便于后续管理
  3043. messageDiv.setAttribute('data-conversation-id', conversationId);
  3044. // 创建思考过程容器
  3045. thoughtContainer = document.createElement('div');
  3046. thoughtContainer.className = 'thought-container';
  3047. const thoughtToggleBtn = document.createElement('button');
  3048. thoughtToggleBtn.className = 'thought-toggle-btn';
  3049. thoughtToggleBtn.innerHTML = '<span class="toggle-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 15L12 9L6 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>';
  3050. thoughtToggleBtn.title = '收起/展开思考过程';
  3051. thoughtToggleBtn.onclick = function (e) {
  3052. e.stopPropagation();
  3053. thoughtContainer.classList.toggle('collapsed');
  3054. const icon = thoughtToggleBtn.querySelector('.toggle-icon');
  3055. if (thoughtContainer.classList.contains('collapsed')) {
  3056. icon.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  3057. } else {
  3058. icon.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 15L12 9L6 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
  3059. }
  3060. };
  3061. thoughtContainer.appendChild(thoughtToggleBtn);
  3062. thoughtContent = document.createElement('div');
  3063. thoughtContent.className = 'thought-content';
  3064. thoughtContainer.appendChild(thoughtContent);
  3065. messageDiv.appendChild(thoughtContainer);
  3066. const chatMessages = document.getElementById('chat-messages');
  3067. if (chatMessages) {
  3068. chatMessages.appendChild(messageDiv);
  3069. }
  3070. // ===== 保存到对话状态(关键!) =====
  3071. state.messageElement = messageDiv;
  3072. state.thoughtContainer = thoughtContainer;
  3073. conversationStates.set(conversationId, state);
  3074. // 确保消息元素可见
  3075. messageDiv.style.opacity = '1';
  3076. messageDiv.style.transform = 'translateY(0)';
  3077. return messageDiv;
  3078. }
  3079. function readStream () {
  3080. reader.read().then(({ done, value }) => {
  3081. if (done) {
  3082. // 流式响应完成
  3083. state.isStreaming = false;
  3084. if (typeof window.updateConversationItemStatus === 'function') {
  3085. window.updateConversationItemStatus(conversationId, 'stopped');
  3086. }
  3087. conversationStates.set(conversationId, state);
  3088. updateUIOnComplete();
  3089. return;
  3090. }
  3091. const chunk = decoder.decode(value, { stream: true });
  3092. buffer += chunk;
  3093. const lines = buffer.split('\n\n');
  3094. buffer = lines.pop() || '';
  3095. lines.forEach(line => {
  3096. if (line.startsWith('data: ')) {
  3097. try {
  3098. const eventData = JSON.parse(line.substring(6));
  3099. handleEditEventData(eventData);
  3100. } catch (error) {
  3101. console.error('解析SSE数据失败:', error);
  3102. }
  3103. }
  3104. });
  3105. // 无论是否暂停,都继续读取流数据
  3106. readStream();
  3107. }).catch(error => {
  3108. if (!state.isPaused) {
  3109. console.error('读取流数据失败:', error);
  3110. showMessage('编辑消息时发生错误: ' + error.message, 'error');
  3111. }
  3112. state.isStreaming = false;
  3113. if (typeof window.updateConversationItemStatus === 'function') {
  3114. window.updateConversationItemStatus(conversationId, 'stopped');
  3115. }
  3116. conversationStates.set(conversationId, state);
  3117. updateUIOnError();
  3118. });
  3119. }
  3120. function handleEditEventData (data) {
  3121. // 更新最后更新时间
  3122. state.lastUpdateTime = Date.now();
  3123. if (!data.success) {
  3124. showMessage('编辑消息失败: ' + (data.error || '未知错误'), 'error');
  3125. state.isStreaming = false;
  3126. if (typeof window.updateConversationItemStatus === 'function') {
  3127. window.updateConversationItemStatus(conversationId, 'stopped');
  3128. }
  3129. updateUIOnError();
  3130. return;
  3131. }
  3132. if (data.thought) {
  3133. // AI回复容器已存在或需要创建
  3134. allThoughts.push(data.thought);
  3135. // ===== 保存思考过程到状态 =====
  3136. state.currentThoughts = allThoughts;
  3137. createBotMessageContainer();
  3138. if (thoughtContent) {
  3139. const combinedThoughts = allThoughts.join('');
  3140. if (typeof window.renderThoughts === 'function') {
  3141. thoughtContent.innerHTML = window.renderThoughts(combinedThoughts);
  3142. } else {
  3143. thoughtContent.textContent = combinedThoughts;
  3144. }
  3145. // 更新状态
  3146. conversationStates.set(conversationId, state);
  3147. forceScrollToBottom();
  3148. }
  3149. return;
  3150. }
  3151. if (data.chunk) {
  3152. // AI回复容器已存在或需要创建
  3153. fullMessage += data.chunk;
  3154. // ===== 保存消息内容到状态 =====
  3155. state.currentMessage = fullMessage;
  3156. createBotMessageContainer();
  3157. if (!contentContainer) {
  3158. contentContainer = document.createElement('div');
  3159. contentContainer.className = 'message-content typing';
  3160. messageDiv.appendChild(contentContainer);
  3161. }
  3162. const now = performance.now();
  3163. if (now - lastRenderTime >= RENDER_INTERVAL) {
  3164. requestAnimationFrame(() => {
  3165. if (contentContainer) {
  3166. if (typeof window.renderMarkdown === 'function') {
  3167. contentContainer.innerHTML = window.renderMarkdown(fullMessage);
  3168. if (typeof window.applyCodeHighlighting === 'function') {
  3169. window.applyCodeHighlighting(contentContainer);
  3170. }
  3171. } else {
  3172. contentContainer.textContent = fullMessage;
  3173. }
  3174. // 更新状态
  3175. conversationStates.set(conversationId, state);
  3176. if (isUserNearBottom()) {
  3177. forceScrollToBottom();
  3178. }
  3179. }
  3180. });
  3181. lastRenderTime = now;
  3182. }
  3183. }
  3184. if (data.session_id) {
  3185. window.currentSessionId = data.session_id;
  3186. }
  3187. if (data.done) {
  3188. if (contentContainer) {
  3189. contentContainer.classList.remove('typing');
  3190. if (typeof window.renderMarkdown === 'function') {
  3191. contentContainer.innerHTML = window.renderMarkdown(fullMessage);
  3192. if (typeof window.applyCodeHighlighting === 'function') {
  3193. window.applyCodeHighlighting(contentContainer);
  3194. }
  3195. } else {
  3196. contentContainer.textContent = fullMessage;
  3197. }
  3198. }
  3199. // ===== 标记流式响应完成,但保留状态 =====
  3200. state.isStreaming = false;
  3201. state.currentMessage = fullMessage;
  3202. state.currentThoughts = allThoughts;
  3203. conversationStates.set(conversationId, state);
  3204. if (typeof window.updateConversationItemStatus === 'function') {
  3205. window.updateConversationItemStatus(conversationId, 'stopped');
  3206. }
  3207. updateUIOnComplete();
  3208. }
  3209. }
  3210. function updateUIOnComplete () {
  3211. // 删除旧的消息元素(被编辑的消息及其后的所有消息)
  3212. // 使用chat-messages容器来查找并删除所有相关消息
  3213. const chatMessages = document.getElementById('chat-messages');
  3214. if (chatMessages && editMessageElement) {
  3215. // 获取所有消息元素
  3216. const allMessages = Array.from(chatMessages.querySelectorAll('.message'));
  3217. let foundEditMessage = false;
  3218. allMessages.forEach(msg => {
  3219. // 找到被编辑的消息
  3220. if (msg === editMessageElement) {
  3221. foundEditMessage = true;
  3222. // 删除编辑表单
  3223. const editForm = msg.querySelector('.edit-form');
  3224. if (editForm) {
  3225. editForm.remove();
  3226. }
  3227. msg.classList.remove('message-editing');
  3228. // 删除整个消息元素(除了新创建的用户消息和AI回复)
  3229. if (msg && msg.parentNode && msg !== messageDiv && msg !== newUserMessageElement) {
  3230. msg.remove();
  3231. }
  3232. } else if (foundEditMessage) {
  3233. // 删除被编辑消息之后的所有消息(除了新创建的用户消息和AI回复)
  3234. if (msg && msg.parentNode && msg !== messageDiv && msg !== newUserMessageElement) {
  3235. msg.remove();
  3236. }
  3237. }
  3238. });
  3239. }
  3240. // 如果editMessageElement还存在但没有被删除,手动删除它
  3241. if (editMessageElement && editMessageElement.parentNode) {
  3242. editMessageElement.remove();
  3243. }
  3244. currentEditMessageElement = null;
  3245. currentEditMessageId = null;
  3246. window.isEditingMessage = false;
  3247. if (userInput && sendButton) {
  3248. userInput.classList.remove('input-loading');
  3249. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  3250. userInput.disabled = false;
  3251. sendButton.innerHTML = `
  3252. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  3253. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  3254. </svg>`;
  3255. sendButton.classList.remove('stopping');
  3256. }
  3257. // 只刷新侧边栏的对话列表,不重新加载消息(避免旧消息重新出现)
  3258. if (window.currentConversationId && typeof loadConversationHistory === 'function') {
  3259. setTimeout(() => {
  3260. loadConversationHistory(false); // 只更新侧边栏,不重新加载消息
  3261. }, 300);
  3262. }
  3263. // 为新创建的消息添加复制按钮
  3264. if (typeof window.setupCopyButtons === 'function') {
  3265. window.setupCopyButtons();
  3266. }
  3267. forceScrollToBottom();
  3268. }
  3269. function updateUIOnError () {
  3270. if (currentEditMessageElement) {
  3271. const sendBtn = currentEditMessageElement.querySelector('.edit-send-btn');
  3272. if (sendBtn) {
  3273. sendBtn.textContent = '发送';
  3274. sendBtn.disabled = false;
  3275. }
  3276. }
  3277. if (userInput && sendButton) {
  3278. userInput.classList.remove('input-loading');
  3279. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  3280. userInput.disabled = false;
  3281. sendButton.innerHTML = `
  3282. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  3283. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  3284. </svg>`;
  3285. sendButton.classList.remove('stopping');
  3286. }
  3287. currentEditMessageElement = null;
  3288. currentEditMessageId = null;
  3289. window.isEditingMessage = false;
  3290. }
  3291. function forceScrollToBottom () {
  3292. const chatMessages = document.getElementById('chat-messages');
  3293. if (chatMessages) {
  3294. chatMessages.scrollTop = chatMessages.scrollHeight;
  3295. }
  3296. }
  3297. function isUserNearBottom () {
  3298. const chatMessages = document.getElementById('chat-messages');
  3299. if (!chatMessages) return true;
  3300. const scrollThreshold = 50;
  3301. return chatMessages.scrollHeight - chatMessages.scrollTop - chatMessages.clientHeight < scrollThreshold;
  3302. }
  3303. readStream();
  3304. })
  3305. .catch(error => {
  3306. // 确保在错误时也更新状态
  3307. if (error.name !== 'AbortError') {
  3308. state.isStreaming = false;
  3309. if (typeof window.updateConversationItemStatus === 'function') {
  3310. window.updateConversationItemStatus(conversationId, 'stopped');
  3311. }
  3312. conversationStates.set(conversationId, state);
  3313. }
  3314. console.error('编辑消息时发生错误:', error);
  3315. showMessage('编辑消息时发生错误: ' + error.message, 'error');
  3316. // 恢复UI状态
  3317. if (currentEditMessageElement) {
  3318. const sendBtn = currentEditMessageElement.querySelector('.edit-send-btn');
  3319. if (sendBtn) {
  3320. sendBtn.textContent = '发送';
  3321. sendBtn.disabled = false;
  3322. }
  3323. }
  3324. if (userInput && sendButton) {
  3325. userInput.classList.remove('input-loading');
  3326. userInput.placeholder = '请输入需要撰写的品类名和要求...';
  3327. userInput.disabled = false;
  3328. sendButton.innerHTML = `
  3329. <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  3330. <path d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9L22 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  3331. </svg>`;
  3332. sendButton.classList.remove('stopping');
  3333. }
  3334. currentEditMessageElement = null;
  3335. currentEditMessageId = null;
  3336. window.isEditingMessage = false;
  3337. });
  3338. }
  3339. </script>
  3340. </body>
  3341. </html>