index.html 164 KB

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