index.html 169 KB

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