index.html 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  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>煤矿通风智能解读系统</title>
  7. <style>
  8. /* ============================================================
  9. CSS Variables & Reset — Zcode/Codex Dark Theme
  10. ============================================================ */
  11. :root {
  12. --bg-primary: #1e1e2e;
  13. --bg-secondary: #181825;
  14. --bg-tertiary: #11111b;
  15. --bg-surface: #242438;
  16. --bg-hover: #2a2a40;
  17. --border: #313244;
  18. --text-primary: #cdd6f4;
  19. --text-secondary: #a6adc8;
  20. --text-muted: #6c7086;
  21. --accent: #89b4fa;
  22. --accent-dim: #74a0e0;
  23. --green: #a6e3a1;
  24. --yellow: #f9e2af;
  25. --red: #f38ba8;
  26. --orange: #fab387;
  27. --purple: #cba6f7;
  28. --font-mono: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace;
  29. --font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
  30. --radius: 8px;
  31. --radius-sm: 4px;
  32. }
  33. *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  34. html, body { height: 100%; overflow: hidden; }
  35. body {
  36. font-family: var(--font-sans);
  37. font-size: 14px;
  38. background: var(--bg-primary);
  39. color: var(--text-primary);
  40. display: flex; flex-direction: column;
  41. }
  42. /* ============================================================
  43. Layout
  44. ============================================================ */
  45. .app { display: flex; height: 100vh; overflow: hidden; }
  46. /* Sidebar — Session List */
  47. .sidebar {
  48. width: 260px; min-width: 260px;
  49. background: var(--bg-secondary);
  50. border-right: 1px solid var(--border);
  51. display: flex; flex-direction: column;
  52. overflow: hidden;
  53. }
  54. .sidebar-header {
  55. padding: 16px; border-bottom: 1px solid var(--border);
  56. display: flex; align-items: center; justify-content: space-between;
  57. }
  58. .sidebar-header h2 { font-size: 15px; font-weight: 600; color: var(--accent); }
  59. .btn-new {
  60. width: 32px; height: 32px; border-radius: var(--radius-sm);
  61. background: var(--accent); color: var(--bg-tertiary); border: none;
  62. font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center;
  63. transition: background .15s;
  64. }
  65. .btn-new:hover { background: var(--accent-dim); }
  66. .session-list {
  67. flex: 1; overflow-y: auto; padding: 8px;
  68. }
  69. .session-item {
  70. padding: 10px 12px; border-radius: var(--radius-sm);
  71. cursor: pointer; margin-bottom: 4px; font-size: 13px;
  72. display: flex; align-items: center; justify-content: space-between;
  73. color: var(--text-secondary); transition: background .1s;
  74. white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
  75. }
  76. .session-item:hover { background: var(--bg-hover); }
  77. .session-item.active { background: var(--bg-surface); color: var(--text-primary); }
  78. .session-item .title { flex: 1; overflow: hidden; text-overflow: ellipsis; }
  79. .session-item .count { font-size: 11px; color: var(--text-muted); margin-left: 8px; }
  80. .btn-delete {
  81. background: none; border: none; color: var(--text-muted); cursor: pointer;
  82. font-size: 16px; padding: 0 4px; opacity: 0; transition: opacity .1s;
  83. }
  84. .session-item:hover .btn-delete { opacity: 1; }
  85. .btn-delete:hover { color: var(--red); }
  86. .btn-pin {
  87. background: none; border: none; color: var(--text-muted); cursor: pointer;
  88. font-size: 13px; padding: 0 2px; opacity: 0; transition: opacity .1s, color .15s;
  89. }
  90. .session-item:hover .btn-pin { opacity: 1; }
  91. .btn-pin:hover { color: var(--yellow); }
  92. .btn-pin.pinned { opacity: 1; color: var(--yellow); }
  93. /* Main Chat Area */
  94. .main {
  95. flex: 1; display: flex; flex-direction: column;
  96. min-width: 0; background: var(--bg-primary);
  97. }
  98. .chat-header {
  99. padding: 12px 20px; border-bottom: 1px solid var(--border);
  100. font-size: 14px; font-weight: 600; color: var(--text-secondary);
  101. display: flex; align-items: center; gap: 8px;
  102. }
  103. .chat-header .status-dot {
  104. width: 8px; height: 8px; border-radius: 50%; background: var(--green);
  105. }
  106. .chat-header .status-dot.streaming { background: var(--yellow); animation: pulse 1s infinite; }
  107. @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.3} }
  108. .messages {
  109. flex: 1; overflow-y: auto; padding: 20px;
  110. display: flex; flex-direction: column; gap: 16px;
  111. }
  112. /* Message bubbles */
  113. .msg { max-width: 85%; animation: fadeIn .2s ease; }
  114. @keyframes fadeIn { from{opacity:0;transform:translateY(4px)} to{opacity:1;transform:translateY(0)} }
  115. .msg.user { align-self: flex-end; }
  116. .msg.assistant { align-self: flex-start; }
  117. .msg .role {
  118. font-size: 11px; font-weight: 600; text-transform: uppercase;
  119. margin-bottom: 4px; color: var(--text-muted);
  120. }
  121. .msg.user .role { text-align: right; }
  122. .msg .bubble {
  123. padding: 12px 16px; border-radius: var(--radius); line-height: 1.6;
  124. word-break: break-word;
  125. }
  126. .msg.user .bubble { background: var(--bg-surface); border: 1px solid var(--border); }
  127. .msg.assistant .bubble { background: transparent; padding: 0; }
  128. /* Markdown inside assistant bubble */
  129. .msg.assistant .bubble h1,.msg.assistant .bubble h2,.msg.assistant .bubble h3 {
  130. margin: 16px 0 8px; font-weight: 600; color: var(--accent);
  131. }
  132. .msg.assistant .bubble h1 { font-size: 1.3em; }
  133. .msg.assistant .bubble h2 { font-size: 1.15em; }
  134. .msg.assistant .bubble h3 { font-size: 1em; }
  135. .msg.assistant .bubble h4 { font-size: 0.95em; font-weight: 600; margin: 12px 0 6px; }
  136. .msg.assistant .bubble h5 { font-size: 0.9em; font-weight: 600; margin: 10px 0 4px; color: var(--text-secondary); }
  137. .msg.assistant .bubble h6 { font-size: 0.85em; font-weight: 600; margin: 8px 0 4px; color: var(--text-muted); }
  138. .msg.assistant .bubble p { margin: 4px 0; }
  139. .msg.assistant .bubble ul,.msg.assistant .bubble ol { padding-left: 20px; margin: 8px 0; }
  140. .msg.assistant .bubble li { margin: 2px 0; }
  141. .msg.assistant .bubble code {
  142. font-family: var(--font-mono); font-size: 0.9em;
  143. background: var(--bg-tertiary); padding: 2px 6px; border-radius: var(--radius-sm);
  144. }
  145. .msg.assistant .bubble pre {
  146. background: var(--bg-tertiary); border: 1px solid var(--border);
  147. border-radius: var(--radius); padding: 12px 16px; overflow-x: auto;
  148. margin: 8px 0; font-size: 13px; line-height: 1.5;
  149. }
  150. .msg.assistant .bubble pre code { background: none; padding: 0; }
  151. .msg.assistant .bubble table {
  152. border-collapse: collapse; width: 100%; margin: 8px 0; font-size: 13px;
  153. }
  154. .msg.assistant .bubble th,.msg.assistant .bubble td {
  155. border: 1px solid var(--border); padding: 6px 10px; text-align: left;
  156. }
  157. .msg.assistant .bubble th { background: var(--bg-surface); font-weight: 600; }
  158. .msg.assistant .bubble strong { color: var(--yellow); }
  159. .msg.assistant .bubble blockquote {
  160. border-left: 3px solid var(--accent); padding-left: 12px;
  161. color: var(--text-secondary); margin: 8px 0;
  162. }
  163. /* Thinking block */
  164. .think-block {
  165. margin: 8px 0; border: 1px solid var(--border);
  166. border-radius: var(--radius); overflow: hidden;
  167. background: var(--bg-surface);
  168. }
  169. .think-block summary {
  170. padding: 8px 12px; cursor: pointer; font-size: 12px;
  171. color: var(--text-muted); background: var(--bg-tertiary);
  172. user-select: none; display: flex; align-items: center; gap: 6px;
  173. transition: color .15s;
  174. }
  175. .think-block summary:hover { color: var(--accent); }
  176. .think-block summary::marker { font-size: 10px; }
  177. .think-block .think-content {
  178. padding: 10px 14px; font-size: 12px; color: var(--text-muted);
  179. line-height: 1.6; max-height: 300px; overflow-y: auto;
  180. font-family: var(--font-sans); white-space: pre-wrap;
  181. border-top: 1px solid var(--border);
  182. background: var(--bg-surface);
  183. }
  184. .think-block summary .think-icon { animation: spin 2s linear infinite; display: inline-block; }
  185. .think-block[open] summary .think-icon { animation: none; }
  186. /* Duration badge */
  187. .msg-duration {
  188. font-size: 11px; color: var(--text-muted); margin-top: 4px;
  189. display: flex; align-items: center; gap: 4px;
  190. }
  191. /* Agent card — container for sub-agent tools + progress */
  192. .agent-card {
  193. margin: 6px 0; border: 1px solid var(--border);
  194. border-radius: var(--radius); overflow: hidden;
  195. background: var(--bg-surface); font-size: 12px;
  196. border-left: 3px solid var(--accent);
  197. transition: border-color .3s;
  198. }
  199. .agent-card.running { border-left-color: var(--yellow); }
  200. .agent-card.done { border-left-color: var(--green); }
  201. .agent-card.error { border-left-color: var(--red); }
  202. .agent-card .agent-header {
  203. display: flex; align-items: center; gap: 8px;
  204. padding: 8px 12px; background: var(--bg-tertiary);
  205. }
  206. .agent-card .agent-icon {
  207. width: 16px; height: 16px; flex-shrink: 0;
  208. display: inline-flex; align-items: center; justify-content: center;
  209. font-size: 12px; line-height: 1;
  210. }
  211. /* 运行中:环形旋转 spinner */
  212. .agent-card.running .agent-icon {
  213. width: 14px; height: 14px;
  214. border: 2px solid var(--border);
  215. border-top-color: var(--yellow);
  216. border-radius: 50%;
  217. animation: spin 0.8s linear infinite;
  218. font-size: 0;
  219. }
  220. /* 完成/错误:emoji 居中 */
  221. .agent-card.done .agent-icon,
  222. .agent-card.error .agent-icon {
  223. border: none; width: 16px; height: 16px;
  224. animation: none; font-size: 12px;
  225. }
  226. .agent-card .agent-name { color: var(--text-secondary); flex: 1; font-weight: 500; }
  227. .agent-card .agent-status { font-size: 11px; color: var(--text-muted); }
  228. .agent-card .agent-body {
  229. padding: 2px 0;
  230. max-height: 250px; overflow-y: auto;
  231. }
  232. /* ── 工具翻页动画(仅显示当前正在执行的一个工具)── */
  233. .agent-body .tool-flipper {
  234. perspective: 600px;
  235. min-height: 30px;
  236. overflow: hidden;
  237. }
  238. .agent-body .current-tool {
  239. padding: 5px 12px; font-size: 11px;
  240. display: flex; align-items: center; gap: 6px;
  241. color: var(--text-muted);
  242. transform-origin: center center;
  243. backface-visibility: hidden;
  244. }
  245. .agent-body .current-tool.flip-out {
  246. animation: toolFlipOut 0.28s ease forwards;
  247. pointer-events: none;
  248. }
  249. .agent-body .current-tool.flip-in {
  250. animation: toolFlipIn 0.32s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  251. }
  252. @keyframes toolFlipIn {
  253. from { transform: rotateX(100deg); opacity: 0; }
  254. to { transform: rotateX(0deg); opacity: 1; }
  255. }
  256. @keyframes toolFlipOut {
  257. from { transform: rotateX(0deg); opacity: 1; }
  258. to { transform: rotateX(-100deg); opacity: 0; }
  259. }
  260. .agent-body .current-tool .mt-icon { font-size: 12px; flex-shrink: 0; width: 14px; height: 14px; display: inline-flex; align-items: center; justify-content: center; }
  261. .agent-body .current-tool .mt-name { flex: 1; color: var(--yellow); }
  262. .agent-body .current-tool.done .mt-name { color: var(--text-secondary); }
  263. /* 工具执行中的环形旋转 spinner */
  264. .spin-icon-sm {
  265. display: inline-block;
  266. width: 10px; height: 10px;
  267. border: 2px solid var(--border);
  268. border-top-color: var(--yellow);
  269. border-radius: 50%;
  270. animation: spin 0.7s linear infinite;
  271. flex-shrink: 0;
  272. vertical-align: middle;
  273. }
  274. /* Nested mini todo inside agent body */
  275. .agent-body .mini-todo {
  276. display: flex; align-items: center; gap: 4px;
  277. padding: 3px 12px; font-size: 11px; color: var(--text-muted);
  278. border-bottom: 1px solid var(--border);
  279. }
  280. .agent-body .mini-todo .mt-check {
  281. width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0;
  282. border: 2px solid var(--border);
  283. }
  284. .agent-body .mini-todo.completed .mt-check { background: var(--green); border-color: var(--green); }
  285. .agent-body .mini-todo.in_progress .mt-check { border-color: var(--yellow); background: var(--yellow); }
  286. .agent-body .mini-todo .mt-label { flex: 1; font-size: 11px; }
  287. .agent-body .mini-todo.completed .mt-label { text-decoration: line-through; }
  288. /* Tool call card (standalone, outside agent) */
  289. .tool-card {
  290. margin: 6px 0; padding: 8px 12px; border-radius: var(--radius-sm);
  291. background: var(--bg-surface); border-left: 3px solid var(--accent);
  292. font-size: 12px; display: flex; align-items: center; gap: 8px;
  293. }
  294. .tool-card.pending { border-left-color: var(--yellow); }
  295. .tool-card.done { border-left-color: var(--green); }
  296. .tool-card .tool-icon { font-size: 14px; }
  297. .tool-card .tool-name { color: var(--text-secondary); flex: 1; }
  298. .tool-card .tool-status { font-size: 11px; color: var(--text-muted); }
  299. /* Status bar (agent thinking/executing) */
  300. .status-bar {
  301. padding: 6px 16px; font-size: 12px; color: var(--text-muted);
  302. border-top: 1px solid var(--border); display: flex; align-items: center; gap: 8px;
  303. min-height: 32px;
  304. }
  305. .status-bar .spinner {
  306. width: 12px; height: 12px; border: 2px solid var(--border);
  307. border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite;
  308. }
  309. @keyframes spin { to{transform:rotate(360deg)} }
  310. /* Input area */
  311. .input-area {
  312. padding: 12px 20px; border-top: 1px solid var(--border);
  313. display: flex; gap: 10px; align-items: center;
  314. }
  315. .input-area textarea {
  316. flex: 1; background: var(--bg-surface); border: 1px solid var(--border);
  317. border-radius: var(--radius); color: var(--text-primary); padding: 10px 14px;
  318. font-family: var(--font-sans); font-size: 14px; resize: none; outline: none;
  319. min-height: 44px; max-height: 150px; line-height: 1.4;
  320. transition: border-color .15s;
  321. }
  322. .input-area textarea:focus { border-color: var(--accent); }
  323. .btn-send {
  324. width: 44px; height: 44px; border-radius: var(--radius);
  325. background: var(--accent); color: var(--bg-tertiary); border: none;
  326. font-size: 18px; cursor: pointer; transition: background .15s;
  327. display: flex; align-items: center; justify-content: center; flex-shrink: 0;
  328. }
  329. .btn-send:hover { background: var(--accent-dim); }
  330. .btn-send:disabled { background: var(--border); cursor: not-allowed; }
  331. .btn-attach {
  332. width: 44px; height: 44px; border-radius: var(--radius);
  333. background: var(--bg-surface); border: 1px solid var(--border);
  334. color: var(--text-secondary); font-size: 18px; cursor: pointer;
  335. display: flex; align-items: center; justify-content: center; flex-shrink: 0;
  336. transition: background .1s, border-color .1s;
  337. }
  338. .btn-attach:hover { border-color: var(--accent); color: var(--accent); }
  339. .btn-attach.has-file { border-color: var(--green); color: var(--green); }
  340. #file-input { display: none; }
  341. /* Detail Panel (right) */
  342. .detail-panel {
  343. width: 280px; min-width: 280px;
  344. background: var(--bg-secondary); border-left: 1px solid var(--border);
  345. display: flex; flex-direction: column; overflow: hidden;
  346. }
  347. .detail-panel h3 {
  348. padding: 16px; font-size: 13px; font-weight: 600;
  349. color: var(--text-muted); text-transform: uppercase;
  350. letter-spacing: 0.5px; border-bottom: 1px solid var(--border);
  351. }
  352. .detail-content { flex: 1; overflow-y: auto; padding: 12px; }
  353. .detail-content .section { margin-bottom: 16px; }
  354. .detail-content .section-title {
  355. font-size: 11px; font-weight: 600; color: var(--text-muted);
  356. text-transform: uppercase; margin-bottom: 8px;
  357. }
  358. .todo-item {
  359. display: flex; align-items: center; gap: 8px; padding: 4px 0; font-size: 12px;
  360. }
  361. .todo-item .todo-check {
  362. width: 14px; height: 14px; border-radius: 50%;
  363. border: 2px solid var(--border); flex-shrink: 0;
  364. }
  365. .todo-item.completed .todo-check { background: var(--green); border-color: var(--green); }
  366. .todo-item.in_progress .todo-check { border-color: var(--yellow); background: var(--yellow); }
  367. .todo-item .todo-label { color: var(--text-secondary); }
  368. .todo-item.completed .todo-label { text-decoration: line-through; color: var(--text-muted); }
  369. .tool-log-item {
  370. font-size: 11px; padding: 4px 0; color: var(--text-muted);
  371. border-bottom: 1px solid var(--border); display: flex; gap: 6px;
  372. }
  373. .tool-log-item .tl-icon { flex-shrink: 0; }
  374. .tool-log-item .tl-name { color: var(--text-secondary); }
  375. /* Toast */
  376. .toast {
  377. position: fixed; top: 16px; right: 16px; padding: 10px 16px;
  378. border-radius: var(--radius); font-size: 13px; z-index: 1000;
  379. animation: slideIn .2s ease; max-width: 400px;
  380. }
  381. .toast.error { background: var(--red); color: #fff; }
  382. .toast.info { background: var(--accent); color: var(--bg-tertiary); }
  383. @keyframes slideIn { from{transform:translateX(100%)} to{transform:translateX(0)} }
  384. /* Download Button */
  385. .download-btn {
  386. display: inline-flex; align-items: center; gap: 8px;
  387. padding: 10px 20px; margin: 12px 0;
  388. background: var(--green); color: var(--bg-tertiary);
  389. border: none; border-radius: var(--radius);
  390. font-size: 14px; font-weight: 600; cursor: pointer;
  391. text-decoration: none; transition: background .15s, transform .1s;
  392. }
  393. .download-btn:hover { background: #8fd98f; transform: translateY(-1px); }
  394. .download-btn:active { transform: translateY(0); }
  395. .download-btn .dl-icon { font-size: 18px; }
  396. /* Empty state */
  397. .empty-state {
  398. flex: 1; display: flex; flex-direction: column; align-items: center;
  399. justify-content: center; color: var(--text-muted); gap: 12px;
  400. }
  401. .empty-state .big-icon { font-size: 48px; opacity: .3; }
  402. /* Scrollbar */
  403. ::-webkit-scrollbar { width: 6px; }
  404. ::-webkit-scrollbar-track { background: transparent; }
  405. ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
  406. ::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
  407. /* Responsive: hide detail panel on small screens */
  408. @media (max-width: 1000px) { .detail-panel { display: none; } }
  409. @media (max-width: 700px) { .sidebar { display: none; } }
  410. /* ============================================================
  411. Model Selector — dropdown in chat header
  412. ============================================================ */
  413. .model-selector {
  414. position: relative; margin-left: auto; font-size: 12px;
  415. user-select: none; z-index: 100;
  416. }
  417. .model-selector .current {
  418. display: flex; align-items: center; gap: 6px;
  419. padding: 5px 10px; border-radius: var(--radius-sm);
  420. background: var(--bg-surface); border: 1px solid var(--border);
  421. cursor: pointer; color: var(--text-secondary);
  422. transition: border-color .15s, background .15s;
  423. white-space: nowrap;
  424. }
  425. .model-selector .current:hover {
  426. border-color: var(--accent); background: var(--bg-hover);
  427. }
  428. .model-selector .current .model-icon { font-size: 13px; }
  429. .model-selector .current .model-name { font-weight: 500; }
  430. .model-selector .current .model-arrow {
  431. font-size: 9px; color: var(--text-muted); transition: transform .2s;
  432. }
  433. .model-selector.open .current .model-arrow { transform: rotate(180deg); }
  434. .model-selector .dropdown {
  435. position: absolute; top: calc(100% + 4px); right: 0;
  436. min-width: 200px; background: var(--bg-secondary);
  437. border: 1px solid var(--border); border-radius: var(--radius);
  438. box-shadow: 0 8px 24px rgba(0,0,0,.4); overflow: hidden;
  439. animation: dropdownIn .15s ease;
  440. }
  441. @keyframes dropdownIn { from{opacity:0;transform:translateY(-4px)} to{opacity:1;transform:translateY(0)} }
  442. .model-selector .dropdown .model-option {
  443. display: flex; align-items: center; gap: 8px;
  444. padding: 9px 14px; cursor: pointer; color: var(--text-secondary);
  445. transition: background .1s; border-bottom: 1px solid var(--border);
  446. }
  447. .model-selector .dropdown .model-option:last-child { border-bottom: none; }
  448. .model-selector .dropdown .model-option:hover { background: var(--bg-hover); }
  449. .model-selector .dropdown .model-option.active { color: var(--accent); background: var(--bg-surface); }
  450. .model-selector .dropdown .model-option .opt-tag {
  451. font-size: 10px; padding: 2px 6px; border-radius: 3px;
  452. font-weight: 600; text-transform: uppercase; flex-shrink: 0;
  453. }
  454. .model-selector .dropdown .model-option .opt-tag.pro { background: rgba(203,166,247,.2); color: var(--purple); }
  455. .model-selector .dropdown .model-option .opt-tag.flash { background: rgba(166,227,161,.2); color: var(--green); }
  456. .model-selector .dropdown .model-option .opt-name { flex: 1; }
  457. .model-selector .dropdown .model-option .opt-check { color: var(--accent); font-size: 12px; }
  458. /* Thinking Level Toggle — button group */
  459. .thinking-toggle {
  460. display: flex; align-items: center; gap: 2px;
  461. background: var(--bg-surface); border: 1px solid var(--border);
  462. border-radius: var(--radius-sm); padding: 2px;
  463. font-size: 11px; user-select: none;
  464. }
  465. .thinking-toggle .thinking-label {
  466. padding: 0 6px; color: var(--text-muted); font-size: 12px;
  467. }
  468. .thinking-toggle button {
  469. padding: 3px 8px; border: none; border-radius: 3px;
  470. background: transparent; color: var(--text-muted);
  471. font-family: var(--font-sans); font-size: 11px; cursor: pointer;
  472. transition: background .12s, color .12s;
  473. }
  474. .thinking-toggle button:hover { color: var(--text-primary); }
  475. .thinking-toggle button.active {
  476. background: var(--accent); color: var(--bg-tertiary); font-weight: 600;
  477. }
  478. /* ============================================================
  479. Skill Manager Modal
  480. ============================================================ */
  481. .modal-overlay {
  482. position: fixed; inset: 0; z-index: 2000;
  483. background: rgba(0,0,0,.6); display: flex; align-items: center; justify-content: center;
  484. animation: fadeIn .15s ease;
  485. }
  486. .modal {
  487. background: var(--bg-secondary); border: 1px solid var(--border);
  488. border-radius: var(--radius); width: 720px; max-width: 95vw;
  489. max-height: 82vh; display: flex; flex-direction: column;
  490. box-shadow: 0 16px 48px rgba(0,0,0,.5);
  491. }
  492. .modal-header {
  493. display: flex; align-items: center; justify-content: space-between;
  494. padding: 14px 18px; border-bottom: 1px solid var(--border);
  495. }
  496. .modal-header h3 { font-size: 15px; font-weight: 600; color: var(--accent); }
  497. .modal-header .modal-actions { display: flex; gap: 8px; }
  498. .modal-body {
  499. flex: 1; overflow-y: auto; padding: 16px 18px;
  500. }
  501. .modal-body .skill-table { width: 100%; border-collapse: collapse; font-size: 12px; }
  502. .modal-body .skill-table th, .modal-body .skill-table td {
  503. padding: 8px 10px; text-align: left; border-bottom: 1px solid var(--border);
  504. vertical-align: middle;
  505. }
  506. .modal-body .skill-table th { color: var(--text-muted); font-weight: 600; font-size: 11px; text-transform: uppercase; }
  507. .modal-body .skill-table td { color: var(--text-secondary); }
  508. .modal-body .skill-table .skill-desc { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  509. .modal-body .skill-table .skill-agents { font-size: 10px; color: var(--text-muted); }
  510. .modal-body .skill-table .skill-name { color: var(--accent); font-weight: 500; cursor: pointer; }
  511. .modal-body .skill-table .skill-name:hover { text-decoration: underline; }
  512. .modal-body .status-badge {
  513. display: inline-block; padding: 2px 8px; border-radius: 3px;
  514. font-size: 10px; font-weight: 600; text-transform: uppercase;
  515. }
  516. .modal-body .status-badge.enabled { background: rgba(166,227,161,.2); color: var(--green); }
  517. .modal-body .status-badge.disabled { background: rgba(243,139,168,.2); color: var(--red); }
  518. .modal-body .skill-detail {
  519. margin-top: 12px; border: 1px solid var(--border); border-radius: var(--radius);
  520. background: var(--bg-surface); padding: 14px 18px; font-size: 12px;
  521. max-height: 300px; overflow-y: auto; line-height: 1.6;
  522. display: none;
  523. }
  524. .modal-body .skill-detail h1,.modal-body .skill-detail h2,.modal-body .skill-detail h3 { color: var(--accent); margin: 12px 0 6px; }
  525. .modal-body .skill-detail code {
  526. font-family: var(--font-mono); background: var(--bg-tertiary); padding: 1px 5px; border-radius: 3px; font-size: 11px;
  527. }
  528. .upload-zone {
  529. margin-top: 12px; border: 2px dashed var(--border); border-radius: var(--radius);
  530. padding: 20px; text-align: center; color: var(--text-muted); font-size: 12px;
  531. cursor: pointer; transition: border-color .15s, background .15s;
  532. }
  533. .upload-zone:hover { border-color: var(--accent); background: var(--bg-surface); }
  534. .upload-zone.dragover { border-color: var(--green); background: rgba(166,227,161,.05); }
  535. .upload-zone input[type="file"] { display: none; }
  536. /* ============================================================
  537. Mode Selector — permission mode dropdown
  538. ============================================================ */
  539. .mode-selector {
  540. position: relative; font-size: 11px; user-select: none; z-index: 99;
  541. }
  542. .mode-selector .mode-current {
  543. display: flex; align-items: center; gap: 5px;
  544. padding: 4px 8px; border-radius: var(--radius-sm);
  545. background: var(--bg-surface); border: 1px solid var(--border);
  546. cursor: pointer; color: var(--text-secondary); white-space: nowrap;
  547. transition: border-color .15s, background .15s;
  548. }
  549. .mode-selector .mode-current:hover { border-color: var(--accent); }
  550. .mode-selector .mode-dot {
  551. width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0;
  552. }
  553. .mode-selector .mode-dot.plan { background: var(--purple); }
  554. .mode-selector .mode-dot.full { background: var(--red); }
  555. .mode-selector .mode-dropdown {
  556. display: none; position: absolute; top: calc(100% + 4px); right: 0;
  557. min-width: 180px; background: var(--bg-secondary);
  558. border: 1px solid var(--border); border-radius: var(--radius);
  559. box-shadow: 0 8px 24px rgba(0,0,0,.4); overflow: hidden;
  560. animation: dropdownIn .15s ease;
  561. }
  562. .mode-selector.open .mode-dropdown { display: block; }
  563. .mode-selector .mode-option {
  564. display: flex; align-items: center; gap: 8px;
  565. padding: 9px 14px; cursor: pointer; color: var(--text-secondary);
  566. transition: background .1s; border-bottom: 1px solid var(--border);
  567. font-size: 12px;
  568. }
  569. .mode-selector .mode-option:last-child { border-bottom: none; }
  570. .mode-selector .mode-option:hover { background: var(--bg-hover); }
  571. .mode-selector .mode-option.active { color: var(--accent); background: var(--bg-surface); }
  572. .mode-selector .mode-option .mode-opt-name { flex: 1; font-weight: 500; }
  573. .mode-selector .mode-option .mode-opt-desc { font-size: 10px; color: var(--text-muted); }
  574. .mode-selector .mode-option .mode-opt-check { color: var(--accent); font-size: 11px; }
  575. /* Interrupt approval card */
  576. .interrupt-card {
  577. margin: 8px 0; padding: 12px 16px; border-radius: var(--radius);
  578. border: 1px solid var(--yellow); background: rgba(249,226,175,.06);
  579. display: flex; align-items: center; gap: 12px; font-size: 12px;
  580. }
  581. .interrupt-card .interrupt-msg { flex: 1; color: var(--yellow); }
  582. .interrupt-card button {
  583. padding: 5px 14px; border-radius: var(--radius-sm);
  584. border: none; font-size: 12px; cursor: pointer; font-weight: 500;
  585. transition: background .15s;
  586. }
  587. .interrupt-card .btn-approve { background: var(--green); color: var(--bg-tertiary); }
  588. .interrupt-card .btn-approve:hover { background: #8fd98f; }
  589. .interrupt-card .btn-reject { background: var(--red); color: #fff; }
  590. .interrupt-card .btn-reject:hover { background: #e06c80; }
  591. /* ============================================================
  592. Context Capacity Meter — detail panel
  593. ============================================================ */
  594. .context-meter { margin-bottom: 12px; }
  595. .context-meter .cm-header {
  596. display: flex; align-items: center; justify-content: space-between;
  597. margin-bottom: 4px; font-size: 11px;
  598. }
  599. .context-meter .cm-header .cm-label { color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
  600. .context-meter .cm-header .cm-value { color: var(--text-secondary); font-weight: 500; }
  601. .context-meter .cm-bar-outer {
  602. height: 6px; background: var(--bg-tertiary); border-radius: 3px; overflow: hidden; margin-bottom: 8px;
  603. }
  604. .context-meter .cm-bar-inner {
  605. height: 100%; border-radius: 3px; transition: width .4s ease, background .4s ease;
  606. }
  607. .context-meter .cm-bar-inner.low { background: var(--green); }
  608. .context-meter .cm-bar-inner.medium { background: var(--yellow); }
  609. .context-meter .cm-bar-inner.high { background: var(--orange); }
  610. .context-meter .cm-bar-inner.crit { background: var(--red); }
  611. .context-meter .cm-breakdown {
  612. display: grid; grid-template-columns: 1fr 1fr; gap: 2px 12px; font-size: 10px;
  613. }
  614. .context-meter .cm-breakdown .cm-item {
  615. display: flex; justify-content: space-between; color: var(--text-muted);
  616. }
  617. .context-meter .cm-breakdown .cm-item .cm-cat { flex: 1; }
  618. .context-meter .cm-breakdown .cm-item .cm-num { font-weight: 500; color: var(--text-secondary); }
  619. .context-meter .cm-empty {
  620. font-size: 10px; color: var(--text-muted); text-align: center; padding: 8px 0;
  621. }
  622. </style>
  623. </head>
  624. <body>
  625. <div class="app">
  626. <!-- ============ Sidebar: Session List ============ -->
  627. <aside class="sidebar">
  628. <div class="sidebar-header">
  629. <h2>💨 通风智能助手</h2>
  630. <div style="display:flex;gap:6px;">
  631. <button class="btn-new" onclick="openSkillManager()" title="技能管理" style="font-size:14px;">📋</button>
  632. <button class="btn-new" onclick="newSession()" title="新建会话">+</button>
  633. </div>
  634. </div>
  635. <div class="session-list" id="session-list"></div>
  636. </aside>
  637. <!-- ============ Main Chat Area ============ -->
  638. <main class="main">
  639. <div class="chat-header">
  640. <span class="status-dot" id="status-dot"></span>
  641. <span id="chat-title">新会话</span>
  642. <!-- Model Selector -->
  643. <div class="model-selector" id="model-selector">
  644. <div class="current" onclick="toggleModelDropdown()">
  645. <span class="model-icon">🧠</span>
  646. <span class="model-name" id="current-model-label">deepseek-v4-pro</span>
  647. <span class="model-arrow">▼</span>
  648. </div>
  649. <div class="dropdown" id="model-dropdown" style="display:none"></div>
  650. </div>
  651. <!-- Thinking Level Toggle -->
  652. <div class="thinking-toggle" id="thinking-toggle">
  653. <span class="thinking-label">💭</span>
  654. <button data-level="off" class="active" onclick="switchThinking('off')">关闭</button>
  655. <button data-level="high" onclick="switchThinking('high')">高</button>
  656. <button data-level="highest" onclick="switchThinking('highest')">最高</button>
  657. </div>
  658. <!-- Mode Selector -->
  659. <div class="mode-selector" id="mode-selector">
  660. <div class="mode-current" onclick="toggleModeDropdown()">
  661. <span class="mode-dot plan" id="mode-dot"></span>
  662. <span id="mode-label">计划模式</span>
  663. <span style="font-size:9px;color:var(--text-muted)">▼</span>
  664. </div>
  665. <div class="mode-dropdown" id="mode-dropdown"></div>
  666. </div>
  667. </div>
  668. <div class="messages" id="messages">
  669. <div class="empty-state">
  670. <div class="big-icon">⛏️</div>
  671. <div>煤矿通风数据智能解读系统</div>
  672. <div style="font-size:12px">输入问题或上传配风计划 PDF 开始分析</div>
  673. </div>
  674. </div>
  675. <div class="status-bar" id="status-bar"></div>
  676. <div class="input-area">
  677. <button class="btn-attach" id="btn-attach" onclick="document.getElementById('file-input').click()" title="上传附件">📎</button>
  678. <input type="file" id="file-input" accept=".pdf,.doc,.docx,.txt" onchange="onFileSelected(this)">
  679. <textarea id="input" placeholder="输入您的问题..." rows="1" onkeydown="onInputKey(event)"></textarea>
  680. <button class="btn-send" id="btn-send" onclick="sendMessage()" title="发送">↑</button>
  681. </div>
  682. </main>
  683. <!-- ============ Detail Panel ============ -->
  684. <aside class="detail-panel" id="detail-panel">
  685. <h3>📋 任务详情</h3>
  686. <div class="detail-content" id="detail-content">
  687. <div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">
  688. 发送消息后<br>此处显示任务进度和工具调用
  689. </div>
  690. </div>
  691. </aside>
  692. </div>
  693. <!-- Toast container -->
  694. <div id="toast-container"></div>
  695. <!-- ============ Skill Manager Modal ============ -->
  696. <div class="modal-overlay" id="skill-modal" style="display:none;" onclick="if(event.target===this) closeSkillModal()">
  697. <div class="modal">
  698. <div class="modal-header">
  699. <h3>📋 技能管理</h3>
  700. <div class="modal-actions">
  701. <button class="btn-send" onclick="document.getElementById('skill-upload-input').click()" style="width:auto;padding:6px 14px;font-size:12px;">📤 上传技能</button>
  702. <button class="btn-send" onclick="closeSkillModal()" style="width:auto;padding:6px 14px;font-size:12px;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-secondary);">✕ 关闭</button>
  703. </div>
  704. </div>
  705. <div class="modal-body" id="skill-modal-body">
  706. <div style="text-align:center;color:var(--text-muted);padding:40px;">加载中...</div>
  707. </div>
  708. <!-- Hidden upload input -->
  709. <input type="file" id="skill-upload-input" accept=".zip" onchange="uploadSkill(this)" style="display:none;">
  710. </div>
  711. </div>
  712. <script>
  713. // ============================================================
  714. // State
  715. // ============================================================
  716. const API = '/api';
  717. let currentSessionId = localStorage.getItem('vent_session_id') || null;
  718. let currentAbortController = null;
  719. let todoItems = [];
  720. let toolLogs = [];
  721. let activeThinkBlock = null;
  722. let pendingDownloadUrl = null;
  723. // ── 认证令牌 ──
  724. // 支持从 localStorage(key: x-access-token)或 URL 参数获取
  725. function getAccessToken() {
  726. const fromStorage = localStorage.getItem('x-access-token');
  727. if (fromStorage) return fromStorage;
  728. const params = new URLSearchParams(window.location.search);
  729. return params.get('token') || '';
  730. }
  731. function authHeaders(extra = {}) {
  732. const token = getAccessToken();
  733. const headers = { ...extra };
  734. if (token) headers['x-access-token'] = token;
  735. return headers;
  736. }
  737. // ============================================================
  738. // Init
  739. // ============================================================
  740. document.addEventListener('DOMContentLoaded', () => {
  741. loadSessions();
  742. if (currentSessionId) loadHistory(currentSessionId);
  743. fetchModels();
  744. if (currentSessionId) fetchSessionMode();
  745. });
  746. // ============================================================
  747. // Model Switching
  748. // ============================================================
  749. const MODEL_TAGS = {
  750. 'deepseek-v4-pro': { tag: 'PRO', cls: 'pro', desc: '深度推理 · 高精度' },
  751. 'deepseek-v4-flash': { tag: 'FLASH', cls: 'flash', desc: '快速响应 · 低延迟' },
  752. };
  753. async function fetchModels() {
  754. try {
  755. const res = await fetch(`${API}/model`);
  756. const data = await res.json();
  757. const current = data.current || 'deepseek-v4-pro';
  758. const available = data.available || ['deepseek-v4-pro', 'deepseek-v4-flash'];
  759. const thinkLevel = data.thinking_level || 'off';
  760. // Update current display
  761. document.getElementById('current-model-label').textContent = current;
  762. // Update thinking toggle buttons
  763. document.querySelectorAll('#thinking-toggle button').forEach(btn => {
  764. btn.classList.toggle('active', btn.dataset.level === thinkLevel);
  765. });
  766. // Render dropdown options
  767. const dropdown = document.getElementById('model-dropdown');
  768. dropdown.innerHTML = available.map(m => {
  769. const info = MODEL_TAGS[m] || { tag: m, cls: '', desc: '' };
  770. const isActive = m === current;
  771. return `<div class="model-option${isActive ? ' active' : ''}" onclick="switchModel('${m}')">
  772. <span class="opt-tag ${info.cls}">${info.tag}</span>
  773. <span class="opt-name">${m}</span>
  774. ${isActive ? '<span class="opt-check">✓</span>' : ''}
  775. <span style="font-size:10px;color:var(--text-muted)">${info.desc}</span>
  776. </div>`;
  777. }).join('');
  778. } catch(e) {
  779. console.error('获取模型列表失败', e);
  780. }
  781. }
  782. function toggleModelDropdown() {
  783. const selector = document.getElementById('model-selector');
  784. const dropdown = document.getElementById('model-dropdown');
  785. const isOpen = dropdown.style.display !== 'none';
  786. if (isOpen) {
  787. dropdown.style.display = 'none';
  788. selector.classList.remove('open');
  789. } else {
  790. dropdown.style.display = 'block';
  791. selector.classList.add('open');
  792. }
  793. }
  794. async function switchModel(modelName) {
  795. try {
  796. const res = await fetch(`${API}/model/switch`, {
  797. method: 'POST',
  798. headers: { 'Content-Type': 'application/json' },
  799. body: JSON.stringify({ model: modelName }),
  800. });
  801. const data = await res.json();
  802. if (data.error) {
  803. showToast(data.error, 'error');
  804. return;
  805. }
  806. // Update display
  807. document.getElementById('current-model-label').textContent = data.current;
  808. document.getElementById('model-dropdown').style.display = 'none';
  809. document.getElementById('model-selector').classList.remove('open');
  810. // Refresh dropdown state
  811. await fetchModels();
  812. showToast(data.message || `已切换到 ${modelName}`, 'info');
  813. } catch(e) {
  814. showToast(`切换失败: ${e.message}`, 'error');
  815. console.error(e);
  816. }
  817. }
  818. // Click outside to close dropdown
  819. document.addEventListener('click', (e) => {
  820. const selector = document.getElementById('model-selector');
  821. if (selector && !selector.contains(e.target)) {
  822. document.getElementById('model-dropdown').style.display = 'none';
  823. selector.classList.remove('open');
  824. }
  825. });
  826. async function switchThinking(level) {
  827. try {
  828. const res = await fetch(`${API}/model/thinking`, {
  829. method: 'POST',
  830. headers: { 'Content-Type': 'application/json' },
  831. body: JSON.stringify({ level: level }),
  832. });
  833. const data = await res.json();
  834. if (data.error) {
  835. showToast(data.error, 'error');
  836. return;
  837. }
  838. // Update button states
  839. document.querySelectorAll('#thinking-toggle button').forEach(btn => {
  840. btn.classList.toggle('active', btn.dataset.level === level);
  841. });
  842. showToast(data.message || `思考级别已切换为「${level}」`, 'info');
  843. } catch(e) {
  844. showToast(`切换失败: ${e.message}`, 'error');
  845. console.error(e);
  846. }
  847. }
  848. // ============================================================
  849. // Permission Mode
  850. // ============================================================
  851. const MODES = {
  852. plan: { label: '计划模式', dot: 'plan', desc: '先生成计划,确认后执行' },
  853. full: { label: '完全访问', dot: 'full', desc: '无限制自动执行' },
  854. };
  855. let currentMode = 'plan';
  856. let pendingInterruptSession = null;
  857. async function fetchSessionMode() {
  858. if (!currentSessionId) { currentMode = 'plan'; updateModeUI(); return; }
  859. try {
  860. const res = await fetch(`${API}/sessions/${currentSessionId}/mode`, {
  861. headers: authHeaders(),
  862. });
  863. const data = await res.json();
  864. currentMode = data.mode || 'plan';
  865. updateModeUI();
  866. renderModeDropdown();
  867. } catch(e) { console.error('获取会话模式失败', e); }
  868. }
  869. function updateModeUI() {
  870. const info = MODES[currentMode] || MODES['plan'];
  871. document.getElementById('mode-label').textContent = info.label;
  872. const dot = document.getElementById('mode-dot');
  873. dot.className = 'mode-dot ' + info.dot;
  874. }
  875. function renderModeDropdown() {
  876. const dd = document.getElementById('mode-dropdown');
  877. dd.innerHTML = Object.entries(MODES).map(([k, v]) => {
  878. const active = k === currentMode;
  879. return `<div class="mode-option${active ? ' active' : ''}" onclick="switchMode('${k}')">
  880. <span class="mode-dot ${v.dot}"></span>
  881. <span class="mode-opt-name">${v.label}</span>
  882. <span class="mode-opt-desc">${v.desc}</span>
  883. ${active ? '<span class="mode-opt-check">✓</span>' : ''}
  884. </div>`;
  885. }).join('');
  886. }
  887. function toggleModeDropdown() {
  888. const sel = document.getElementById('mode-selector');
  889. sel.classList.toggle('open');
  890. if (sel.classList.contains('open')) renderModeDropdown();
  891. }
  892. async function switchMode(mode) {
  893. // 无会话时仅更新本地 UI 状态,模式会在首次 /chat 时随请求传入
  894. if (!currentSessionId) {
  895. currentMode = mode;
  896. updateModeUI();
  897. renderModeDropdown();
  898. document.getElementById('mode-selector').classList.remove('open');
  899. return;
  900. }
  901. try {
  902. const res = await fetch(`${API}/sessions/${currentSessionId}/mode`, {
  903. method: 'PUT',
  904. headers: authHeaders({ 'Content-Type': 'application/json' }),
  905. body: JSON.stringify({ mode: mode }),
  906. });
  907. const data = await res.json();
  908. if (data.error) { showToast(data.error, 'error'); return; }
  909. currentMode = mode;
  910. updateModeUI();
  911. renderModeDropdown();
  912. document.getElementById('mode-selector').classList.remove('open');
  913. showToast(data.message || `已切换为「${MODES[mode]?.label || mode}」`, 'info');
  914. } catch(e) { showToast(`切换失败: ${e.message}`, 'error'); }
  915. }
  916. // Close mode dropdown on outside click
  917. document.addEventListener('click', (e) => {
  918. const sel = document.getElementById('mode-selector');
  919. if (sel && !sel.contains(e.target)) sel.classList.remove('open');
  920. });
  921. // ── Interrupt handling ──
  922. function showInterruptCard(message, node) {
  923. const bubble = getOrCreateAssistantMsg();
  924. // Remove any existing interrupt card
  925. bubble.querySelectorAll('.interrupt-card').forEach(el => el.remove());
  926. const card = document.createElement('div');
  927. card.className = 'interrupt-card';
  928. const nodeLabel = node === 'tools' ? '工具执行' : '继续执行';
  929. card.innerHTML = `<span class="interrupt-msg">⚠️ ${message || nodeLabel + '等待审批'}</span>
  930. <button class="btn-approve" onclick="resumeAfterInterrupt('approve')">✓ 批准</button>
  931. <button class="btn-reject" onclick="resumeAfterInterrupt('reject')">✕ 拒绝</button>`;
  932. bubble.appendChild(card);
  933. scrollToBottom();
  934. }
  935. async function resumeAfterInterrupt(action) {
  936. if (!pendingInterruptSession) return;
  937. const sid = pendingInterruptSession;
  938. pendingInterruptSession = null;
  939. // Remove interrupt card
  940. document.querySelectorAll('.interrupt-card').forEach(el => el.remove());
  941. if (action === 'reject') {
  942. showToast('已拒绝执行', 'info');
  943. clearStatus();
  944. return;
  945. }
  946. setStatus('已批准,继续执行...');
  947. document.getElementById('status-dot').classList.add('streaming');
  948. try {
  949. const res = await fetch(`${API}/chat/resume`, {
  950. method: 'POST',
  951. headers: authHeaders({ 'Content-Type': 'application/json' }),
  952. body: JSON.stringify({ session_id: sid, action: 'approve' }),
  953. });
  954. if (!res.ok) {
  955. const errText = await res.text();
  956. throw new Error(`HTTP ${res.status}: ${errText}`);
  957. }
  958. const reader = res.body.getReader();
  959. const decoder = new TextDecoder();
  960. let buffer = '';
  961. while (true) {
  962. const { done, value } = await reader.read();
  963. if (done) break;
  964. buffer += decoder.decode(value, { stream: true });
  965. const lines = buffer.split('\n');
  966. buffer = lines.pop() || '';
  967. for (const line of lines) {
  968. if (!line.startsWith('data: ')) continue;
  969. try {
  970. const event = JSON.parse(line.slice(6));
  971. handleSSEEvent(event);
  972. } catch(e) {}
  973. }
  974. }
  975. } catch(e) {
  976. if (e.name !== 'AbortError') {
  977. showToast(`恢复执行失败: ${e.message}`, 'error');
  978. }
  979. } finally {
  980. document.getElementById('status-dot').classList.remove('streaming');
  981. clearStatus();
  982. }
  983. }
  984. // ============================================================
  985. // Session Management
  986. // ============================================================
  987. async function loadSessions() {
  988. try {
  989. const res = await fetch(`${API}/sessions`, { headers: authHeaders() });
  990. const data = await res.json();
  991. renderSessionList(data.sessions || []);
  992. } catch(e) { console.error('加载会话列表失败', e); }
  993. }
  994. function renderSessionList(sessions) {
  995. const el = document.getElementById('session-list');
  996. if (!sessions.length) {
  997. el.innerHTML = '<div style="color:var(--text-muted);font-size:12px;padding:16px;text-align:center">暂无会话</div>';
  998. return;
  999. }
  1000. el.innerHTML = sessions.map(s => `
  1001. <div class="session-item ${s.session_id === currentSessionId ? 'active' : ''}"
  1002. onclick="switchSession('${s.session_id}')">
  1003. <span class="title">${escHtml(s.title || s.session_id?.slice(0,8) || '新会话')}</span>
  1004. <span class="count">${s.message_count || 0}</span>
  1005. <button class="btn-pin ${s.sort_order > 0 ? 'pinned' : ''}" onclick="event.stopPropagation();togglePin('${s.session_id}')" title="${s.sort_order > 0 ? '取消置顶' : '置顶'}">📌</button>
  1006. <button class="btn-delete" onclick="event.stopPropagation();deleteSession('${s.session_id}')">×</button>
  1007. </div>
  1008. `).join('');
  1009. }
  1010. function newSession() {
  1011. abortStream();
  1012. currentSessionId = null;
  1013. localStorage.removeItem('vent_session_id');
  1014. document.getElementById('messages').innerHTML = `
  1015. <div class="empty-state">
  1016. <div class="big-icon">⛏️</div>
  1017. <div>煤矿通风数据智能解读系统</div>
  1018. <div style="font-size:12px">输入问题或上传配风计划 PDF 开始分析</div>
  1019. </div>`;
  1020. document.getElementById('chat-title').textContent = '新会话';
  1021. document.getElementById('status-bar').innerHTML = '';
  1022. document.getElementById('detail-content').innerHTML = '<div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">发送消息后<br>此处显示任务进度和工具调用</div>';
  1023. todoItems = [];
  1024. toolLogs = [];
  1025. contextData = null;
  1026. pendingDownloadUrl = null;
  1027. loadSessions();
  1028. currentMode = 'plan';
  1029. updateModeUI();
  1030. renderModeDropdown();
  1031. }
  1032. async function switchSession(sid) {
  1033. if (sid === currentSessionId) return;
  1034. abortStream();
  1035. currentSessionId = sid;
  1036. localStorage.setItem('vent_session_id', sid);
  1037. document.getElementById('chat-title').textContent = sid.slice(0,8) + '...';
  1038. loadSessions();
  1039. await loadHistory(sid);
  1040. fetchSessionMode();
  1041. fetchContextUsage();
  1042. }
  1043. async function deleteSession(sid) {
  1044. abortStream();
  1045. await fetch(`${API}/sessions/${sid}`, {
  1046. method: 'DELETE',
  1047. headers: authHeaders(),
  1048. });
  1049. if (currentSessionId === sid) newSession();
  1050. else loadSessions();
  1051. }
  1052. async function togglePin(sid) {
  1053. try {
  1054. const res = await fetch(`${API}/sessions/${sid}/pin`, {
  1055. method: 'PUT',
  1056. headers: authHeaders({ 'Content-Type': 'application/json' }),
  1057. });
  1058. if (!res.ok) return;
  1059. await loadSessions();
  1060. } catch(e) { /* 静默 */ }
  1061. }
  1062. async function loadHistory(sid) {
  1063. try {
  1064. const res = await fetch(`${API}/chat/history/${sid}`, { headers: authHeaders() });
  1065. const data = await res.json();
  1066. const msgsEl = document.getElementById('messages');
  1067. msgsEl.innerHTML = '';
  1068. if (!data.messages || !data.messages.length) {
  1069. msgsEl.innerHTML = '<div class="empty-state"><div class="big-icon">💬</div><div>开始对话吧</div></div>';
  1070. return;
  1071. }
  1072. let lastRole = null;
  1073. data.messages.forEach(m => {
  1074. if (m.role === 'user') {
  1075. addMessage('user', m.content);
  1076. lastRole = 'user';
  1077. } else if (m.role === 'assistant' && m.content) {
  1078. addMessage('assistant', m.content);
  1079. lastRole = 'assistant';
  1080. }
  1081. });
  1082. document.getElementById('chat-title').textContent = data.messages[0]?.content?.slice(0,30) || sid.slice(0,8);
  1083. scrollToBottom();
  1084. } catch(e) { console.error('加载历史失败', e); }
  1085. }
  1086. // ============================================================
  1087. // Message Rendering
  1088. // ============================================================
  1089. function addMessage(role, content) {
  1090. const msgs = document.getElementById('messages');
  1091. // Remove empty state
  1092. const empty = msgs.querySelector('.empty-state');
  1093. if (empty) empty.remove();
  1094. const div = document.createElement('div');
  1095. div.className = `msg ${role}`;
  1096. div.innerHTML = `
  1097. <div class="role">${role === 'user' ? 'YOU' : 'ASSISTANT'}</div>
  1098. <div class="bubble">${role === 'assistant' ? renderMarkdown(content) : escHtml(content)}</div>`;
  1099. msgs.appendChild(div);
  1100. scrollToBottom();
  1101. return div;
  1102. }
  1103. function getOrCreateAssistantMsg() {
  1104. const msgs = document.getElementById('messages');
  1105. const empty = msgs.querySelector('.empty-state');
  1106. if (empty) empty.remove();
  1107. // Find last assistant message
  1108. let last = msgs.querySelector('.msg.assistant:last-child');
  1109. if (!last) {
  1110. last = document.createElement('div');
  1111. last.className = 'msg assistant';
  1112. last.innerHTML = '<div class="role">ASSISTANT</div><div class="bubble"></div>';
  1113. msgs.appendChild(last);
  1114. activeThinkBlock = null;
  1115. }
  1116. const bubble = last.querySelector('.bubble');
  1117. // 确保 markdown 文本容器存在(与 Agent 卡片/工具卡片隔离)
  1118. if (!bubble.querySelector('.msg-markdown')) {
  1119. const md = document.createElement('div');
  1120. md.className = 'msg-markdown';
  1121. bubble.appendChild(md);
  1122. }
  1123. return bubble;
  1124. }
  1125. function appendToken(text) {
  1126. const bubble = getOrCreateAssistantMsg();
  1127. const md = bubble.querySelector('.msg-markdown');
  1128. // 累积原始 markdown 文本
  1129. const existing = md.getAttribute('data-raw') || '';
  1130. md.setAttribute('data-raw', existing + text);
  1131. // 实时追加 token 文本
  1132. const span = document.createElement('span');
  1133. span.textContent = text;
  1134. md.appendChild(span);
  1135. // 每积累约 128 字符时重新渲染(保持表格/标题等格式实时可见)
  1136. const raw = md.getAttribute('data-raw');
  1137. if (raw && raw.length % 128 < text.length) {
  1138. md.innerHTML = renderMarkdown(raw);
  1139. md.setAttribute('data-raw', raw);
  1140. }
  1141. scrollToBottom();
  1142. }
  1143. function appendThinking(text) {
  1144. const bubble = getOrCreateAssistantMsg();
  1145. if (!activeThinkBlock || !bubble.contains(activeThinkBlock)) {
  1146. activeThinkBlock = document.createElement('details');
  1147. activeThinkBlock.className = 'think-block';
  1148. activeThinkBlock.open = true; // 默认展开
  1149. activeThinkBlock.innerHTML = '<summary><span class="think-icon">💭</span> 思考过程</summary><div class="think-content"></div>';
  1150. // Insert at beginning of bubble, before any existing content
  1151. bubble.insertBefore(activeThinkBlock, bubble.firstChild);
  1152. }
  1153. const content = activeThinkBlock.querySelector('.think-content');
  1154. content.textContent += text;
  1155. // Auto-scroll the think content
  1156. content.scrollTop = content.scrollHeight;
  1157. scrollToBottom();
  1158. }
  1159. function addToolCard(name, cnName, status, agentCn) {
  1160. const displayName = cnName || name;
  1161. // ── Agent 内工具:翻页动画,仅显示当前正在执行的一个 ──
  1162. if (agentCn && agentCards[agentCn]) {
  1163. const body = agentCards[agentCn].querySelector('.agent-body');
  1164. if (!body) return;
  1165. // 获取或创建翻页容器,始终保持在 body 的最底部
  1166. let flipper = body.querySelector('.tool-flipper');
  1167. if (!flipper) {
  1168. flipper = document.createElement('div');
  1169. flipper.className = 'tool-flipper';
  1170. }
  1171. body.appendChild(flipper);
  1172. // 当前显示的工具元素
  1173. let current = flipper.querySelector('.current-tool');
  1174. if (!current) {
  1175. current = document.createElement('div');
  1176. current.className = 'current-tool';
  1177. current.innerHTML = `<span class="mt-icon spin-icon-sm"></span><span class="mt-name"></span>`;
  1178. flipper.appendChild(current);
  1179. }
  1180. // ── 取消所有进行中的动画,干净重置 ──
  1181. current.getAnimations().forEach(a => a.cancel());
  1182. if (current._fadeTimer) { clearTimeout(current._fadeTimer); current._fadeTimer = null; }
  1183. // 清除动画残留的 inline style(animation fill 可能留下的 transform/opacity)
  1184. current.style.transform = '';
  1185. current.style.opacity = '';
  1186. if (status === 'done') {
  1187. // 工具完成:显示 ✅,1.2s 后翻出消失
  1188. current.className = 'current-tool done';
  1189. const iconEl = current.querySelector('.mt-icon');
  1190. iconEl.className = 'mt-icon';
  1191. iconEl.textContent = '✅';
  1192. current.querySelector('.mt-name').textContent = displayName;
  1193. current._fadeTimer = setTimeout(() => {
  1194. if (current.parentNode) {
  1195. // 取消可能在进行中的动画,然后翻出
  1196. current.getAnimations().forEach(a => a.cancel());
  1197. current.style.transform = '';
  1198. current.style.opacity = '';
  1199. current.className = 'current-tool flip-out';
  1200. current._fadeTimer = null;
  1201. }
  1202. }, 1200);
  1203. } else {
  1204. // 新工具开始:直接翻入替换
  1205. current.className = 'current-tool';
  1206. const iconEl = current.querySelector('.mt-icon');
  1207. iconEl.className = 'mt-icon spin-icon-sm';
  1208. iconEl.textContent = '';
  1209. current.querySelector('.mt-name').textContent = displayName;
  1210. // 强制回流后启动翻入动画
  1211. void current.offsetWidth;
  1212. current.classList.add('flip-in');
  1213. }
  1214. body.scrollTop = body.scrollHeight;
  1215. scrollToBottom();
  1216. toolLogs.push({ name: displayName, status, time: new Date().toLocaleTimeString() });
  1217. updateDetailPanel();
  1218. return;
  1219. }
  1220. // ── 独立工具卡片(无 Agent 上下文,保留列表模式)──
  1221. const bubble = getOrCreateAssistantMsg();
  1222. const card = document.createElement('div');
  1223. card.className = `tool-card ${status}`;
  1224. if (status === 'done') {
  1225. card.innerHTML = `<span class="tool-icon">✅</span>
  1226. <span class="tool-name">${escHtml(displayName)}</span>
  1227. <span class="tool-status">完成</span>`;
  1228. } else {
  1229. card.innerHTML = `<span class="tool-icon spin-icon-sm"></span>
  1230. <span class="tool-name">${escHtml(displayName)}</span>
  1231. <span class="tool-status">执行中...</span>`;
  1232. }
  1233. // 插入到 markdown 之前
  1234. const md = bubble.querySelector('.msg-markdown');
  1235. if (md) { bubble.insertBefore(card, md); }
  1236. else { bubble.appendChild(card); }
  1237. scrollToBottom();
  1238. toolLogs.push({ name: displayName, status, time: new Date().toLocaleTimeString() });
  1239. updateDetailPanel();
  1240. }
  1241. // ── Agent Card: container for sub-agent tools + progress ──
  1242. let agentCards = {};
  1243. function addAgentCard(cnName, status, durationMs, progress) {
  1244. const bubble = getOrCreateAssistantMsg();
  1245. const key = cnName;
  1246. if (agentCards[key]) {
  1247. const card = agentCards[key];
  1248. card.className = `agent-card ${status}`;
  1249. const iconEl = card.querySelector('.agent-icon');
  1250. if (status === 'done') {
  1251. iconEl.textContent = '✅';
  1252. } else if (status === 'error') {
  1253. iconEl.textContent = '❌';
  1254. } else {
  1255. iconEl.textContent = ''; // CSS spinner handles the running icon
  1256. }
  1257. const durText = durationMs ? ` (${(durationMs/1000).toFixed(1)}s)` : '';
  1258. const progText = progress ? ` [${progress}]` : '';
  1259. card.querySelector('.agent-status').textContent = status === 'done' ? `完成${durText}${progText}` : '运行中...';
  1260. } else {
  1261. const card = document.createElement('div');
  1262. card.className = `agent-card ${status}`;
  1263. card.innerHTML = `<div class="agent-header">
  1264. <span class="agent-icon"></span>
  1265. <span class="agent-name">${escHtml(cnName)}</span>
  1266. <span class="agent-status">启动...</span>
  1267. </div>
  1268. <div class="agent-body"></div>`;
  1269. // 插入到 markdown 文本容器之前,确保 Agent 卡片在 token 输出上方
  1270. const md = bubble.querySelector('.msg-markdown');
  1271. if (md) {
  1272. bubble.insertBefore(card, md);
  1273. } else {
  1274. bubble.appendChild(card);
  1275. }
  1276. agentCards[key] = card;
  1277. }
  1278. scrollToBottom();
  1279. }
  1280. // ── Add mini todos inside an agent card ──
  1281. function addAgentTodos(agentCn, todos) {
  1282. if (!agentCn || !agentCards[agentCn]) return;
  1283. const body = agentCards[agentCn].querySelector('.agent-body');
  1284. if (!body) return;
  1285. // Remove old mini-todos
  1286. body.querySelectorAll('.mini-todo').forEach(el => el.remove());
  1287. todos.forEach(t => {
  1288. const cls = t.status === 'completed' ? 'completed' : t.status === 'in_progress' ? 'in_progress' : '';
  1289. const mt = document.createElement('div');
  1290. mt.className = `mini-todo ${cls}`;
  1291. mt.innerHTML = `<span class="mt-check"></span><span class="mt-label">${escHtml(t.content || '')}</span>`;
  1292. body.appendChild(mt);
  1293. });
  1294. // 确保工具翻页始终在最底部可见
  1295. const flipper = body.querySelector('.tool-flipper');
  1296. if (flipper) body.appendChild(flipper);
  1297. body.scrollTop = body.scrollHeight;
  1298. scrollToBottom();
  1299. }
  1300. function addDuration(durationMs, cnAgent) {
  1301. const bubble = getOrCreateAssistantMsg();
  1302. const dur = document.createElement('div');
  1303. dur.className = 'msg-duration';
  1304. const sec = (durationMs / 1000).toFixed(1);
  1305. const agentLabel = cnAgent ? ` · ${cnAgent}` : '';
  1306. dur.innerHTML = `⏱️ ${sec}s${agentLabel}`;
  1307. bubble.appendChild(dur);
  1308. }
  1309. function updateTodoList(todos) {
  1310. todoItems = todos || [];
  1311. updateDetailPanel();
  1312. }
  1313. // ── 上下文容量 ──
  1314. let contextData = null;
  1315. async function fetchContextUsage() {
  1316. if (!currentSessionId) { contextData = null; updateDetailPanel(); return; }
  1317. try {
  1318. const res = await fetch(`${API}/sessions/${currentSessionId}/context`, {
  1319. headers: authHeaders(),
  1320. });
  1321. if (!res.ok) return;
  1322. contextData = await res.json();
  1323. updateDetailPanel();
  1324. } catch(e) { /* 静默 */ }
  1325. }
  1326. function renderContextMeter() {
  1327. if (!contextData || contextData.total_limit == null) {
  1328. return '<div class="context-meter"><div class="cm-empty">📊 暂无上下文数据<br><span style="font-size:9px">发送消息后自动统计</span></div></div>';
  1329. }
  1330. const pct = contextData.usage_pct || 0;
  1331. const limit = contextData.total_limit;
  1332. const used = contextData.current_usage;
  1333. const bd = contextData.breakdown || {};
  1334. let cls = 'low';
  1335. if (pct > 75) cls = 'crit';
  1336. else if (pct > 50) cls = 'high';
  1337. else if (pct > 25) cls = 'medium';
  1338. const fmt = (n) => n != null ? (n >= 1000 ? (n/1000).toFixed(1)+'K' : n) : '—';
  1339. return `<div class="context-meter">
  1340. <div class="cm-header">
  1341. <span class="cm-label">🧠 上下文容量</span>
  1342. <span class="cm-value">${fmt(used)} / ${fmt(limit)} (${pct}%)</span>
  1343. </div>
  1344. <div class="cm-bar-outer">
  1345. <div class="cm-bar-inner ${cls}" style="width:${Math.min(pct,100)}%"></div>
  1346. </div>
  1347. <div class="cm-breakdown">
  1348. <div class="cm-item"><span class="cm-cat">💬 消息</span><span class="cm-num">${fmt(bd.messages)}</span></div>
  1349. <div class="cm-item"><span class="cm-cat">🔧 系统工具</span><span class="cm-num">${fmt(bd.tools)}</span></div>
  1350. <div class="cm-item"><span class="cm-cat">📋 技能</span><span class="cm-num">${fmt(bd.skills)}</span></div>
  1351. <div class="cm-item"><span class="cm-cat">🔌 MCP</span><span class="cm-num">${fmt(bd.mcp)}</span></div>
  1352. <div class="cm-item"><span class="cm-cat">📝 系统提示</span><span class="cm-num">${fmt(bd.system_prompt)}</span></div>
  1353. <div class="cm-item"><span class="cm-cat">📦 其他</span><span class="cm-num">${fmt(bd.other)}</span></div>
  1354. </div>
  1355. </div>`;
  1356. }
  1357. function updateDetailPanel() {
  1358. const el = document.getElementById('detail-content');
  1359. let html = '';
  1360. // ── 上下文容量(始终在最上方)──
  1361. html += renderContextMeter();
  1362. if (todoItems.length) {
  1363. html += '<div class="section"><div class="section-title">📝 任务进度</div>';
  1364. todoItems.forEach(t => {
  1365. const cls = t.status === 'completed' ? 'completed' : t.status === 'in_progress' ? 'in_progress' : '';
  1366. html += `<div class="todo-item ${cls}">
  1367. <span class="todo-check"></span>
  1368. <span class="todo-label">${escHtml(t.content || '')}</span>
  1369. </div>`;
  1370. });
  1371. html += '</div>';
  1372. }
  1373. if (toolLogs.length) {
  1374. html += '<div class="section"><div class="section-title">🔧 工具调用</div>';
  1375. toolLogs.slice(-20).reverse().forEach(t => {
  1376. html += `<div class="tool-log-item">
  1377. <span class="tl-icon">${t.status === 'done' ? '✅' : '⏳'}</span>
  1378. <span class="tl-name">${escHtml(t.name)}</span>
  1379. </div>`;
  1380. });
  1381. html += '</div>';
  1382. }
  1383. if (!html) {
  1384. html = '<div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">暂无任务数据</div>';
  1385. }
  1386. el.innerHTML = html;
  1387. }
  1388. function setStatus(text) {
  1389. document.getElementById('status-bar').innerHTML = `
  1390. <span class="spinner"></span><span>${escHtml(text)}</span>`;
  1391. }
  1392. function clearStatus() {
  1393. document.getElementById('status-bar').innerHTML = '';
  1394. }
  1395. // ============================================================
  1396. // Markdown Rendering (simple built-in, no CDN dependency)
  1397. // ============================================================
  1398. function renderMarkdown(text) {
  1399. if (!text) return '';
  1400. let html = text;
  1401. // Escape HTML
  1402. html = html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  1403. // Code blocks (```...```)
  1404. html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) =>
  1405. `<pre><code class="language-${lang}">${code.trim()}</code></pre>`);
  1406. // Inline code (`...`)
  1407. html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
  1408. // Bold (**...**)
  1409. html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  1410. // Headers (longest first to avoid partial matches)
  1411. html = html.replace(/^###### (.+)$/gm, '<h6>$1</h6>');
  1412. html = html.replace(/^##### (.+)$/gm, '<h5>$1</h5>');
  1413. html = html.replace(/^#### (.+)$/gm, '<h4>$1</h4>');
  1414. html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
  1415. html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
  1416. html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
  1417. // Blockquote
  1418. html = html.replace(/^&gt; (.+)$/gm, '<blockquote>$1</blockquote>');
  1419. // Unordered lists
  1420. html = html.replace(/^[\-\*] (.+)$/gm, '<li>$1</li>');
  1421. html = html.replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>');
  1422. // Ordered lists
  1423. html = html.replace(/^\d+\. (.+)$/gm, '<li>$1</li>');
  1424. // Tables
  1425. html = html.replace(/^\|(.+)\|$/gm, (line) => {
  1426. const cells = line.split('|').filter(c => c.trim());
  1427. const isHeader = /^[\-\s:]+$/.test(cells.join(''));
  1428. if (isHeader) return '';
  1429. const tag = line.match(/^\|[\s\-:]+\|$/) ? '' : (line.includes('---') ? '' : '');
  1430. return '<tr>' + cells.map(c => {
  1431. const t = isHeader ? 'th' : 'td';
  1432. return `<${t}>${c.trim()}</${t}>`;
  1433. }).join('') + '</tr>';
  1434. });
  1435. html = html.replace(/(<tr>.*<\/tr>\n?)+/g, '<table>$&</table>');
  1436. // Horizontal rules
  1437. html = html.replace(/^---$/gm, '<hr>');
  1438. // Paragraphs (double newline)
  1439. const parts = html.split(/\n\n+/);
  1440. html = parts.map(p => {
  1441. p = p.trim();
  1442. if (!p) return '';
  1443. if (p.startsWith('<h') || p.startsWith('<pre') || p.startsWith('<table')
  1444. || p.startsWith('<ul') || p.startsWith('<blockquote') || p.startsWith('<hr')) return p;
  1445. return `<p>${p.replace(/\n/g, '<br>')}</p>`;
  1446. }).join('\n');
  1447. return html;
  1448. }
  1449. // ============================================================
  1450. // SSE Streaming
  1451. // ============================================================
  1452. async function sendMessage() {
  1453. const input = document.getElementById('input');
  1454. const message = input.value.trim();
  1455. const fileInput = document.getElementById('file-input');
  1456. const file = fileInput.files[0];
  1457. if (!message && !file) return;
  1458. // Abort previous stream
  1459. abortStream();
  1460. // Reset state
  1461. todoItems = [];
  1462. toolLogs = [];
  1463. activeThinkBlock = null;
  1464. agentCards = {};
  1465. pendingDownloadUrl = null;
  1466. updateDetailPanel();
  1467. // Build FormData
  1468. const fd = new FormData();
  1469. fd.append('message', message || (file ? '请审查这份文件' : ''));
  1470. if (currentSessionId) fd.append('session_id', currentSessionId);
  1471. fd.append('mode', currentMode);
  1472. if (file) {
  1473. fd.append('file', file);
  1474. document.getElementById('btn-attach').classList.add('has-file');
  1475. }
  1476. // Add user message to UI
  1477. if (message) addMessage('user', message);
  1478. if (file) {
  1479. addMessage('user', `📎 上传文件: ${file.name}\n${message || '请审查这份文件'}`);
  1480. }
  1481. // Clear input
  1482. input.value = '';
  1483. fileInput.value = '';
  1484. document.getElementById('btn-attach').classList.remove('has-file');
  1485. input.style.height = 'auto';
  1486. // UI state
  1487. setStatus('正在分析...');
  1488. document.getElementById('status-dot').classList.add('streaming');
  1489. document.getElementById('btn-send').disabled = true;
  1490. currentAbortController = new AbortController();
  1491. try {
  1492. const res = await fetch(`${API}/chat`, {
  1493. method: 'POST',
  1494. body: fd,
  1495. headers: authHeaders(),
  1496. signal: currentAbortController.signal,
  1497. });
  1498. if (!res.ok) {
  1499. const errText = await res.text();
  1500. throw new Error(`HTTP ${res.status}: ${errText}`);
  1501. }
  1502. // Get session_id from header
  1503. const sid = res.headers.get('X-Session-Id');
  1504. if (sid && sid !== currentSessionId) {
  1505. currentSessionId = sid;
  1506. localStorage.setItem('vent_session_id', sid);
  1507. loadSessions();
  1508. fetchSessionMode();
  1509. }
  1510. // Stream reader
  1511. const reader = res.body.getReader();
  1512. const decoder = new TextDecoder();
  1513. let buffer = '';
  1514. let assistantContent = '';
  1515. while (true) {
  1516. const { done, value } = await reader.read();
  1517. if (done) break;
  1518. buffer += decoder.decode(value, { stream: true });
  1519. // Process complete SSE events
  1520. const lines = buffer.split('\n');
  1521. buffer = lines.pop() || ''; // keep incomplete line in buffer
  1522. for (const line of lines) {
  1523. if (!line.startsWith('data: ')) continue;
  1524. const json = line.slice(6);
  1525. try {
  1526. const event = JSON.parse(json);
  1527. handleSSEEvent(event);
  1528. if (event.type === 'token' && event.content) {
  1529. assistantContent += event.content;
  1530. }
  1531. } catch(e) {
  1532. // Skip malformed JSON
  1533. }
  1534. }
  1535. }
  1536. // Finalize
  1537. if (assistantContent && !currentSessionId) {
  1538. // Session was created server-side
  1539. loadSessions();
  1540. }
  1541. } catch(e) {
  1542. if (e.name !== 'AbortError') {
  1543. showToast(`请求失败: ${e.message}`, 'error');
  1544. console.error(e);
  1545. }
  1546. } finally {
  1547. document.getElementById('status-dot').classList.remove('streaming');
  1548. document.getElementById('btn-send').disabled = false;
  1549. clearStatus();
  1550. currentAbortController = null;
  1551. }
  1552. }
  1553. function handleSSEEvent(event) {
  1554. switch(event.type) {
  1555. case 'thinking':
  1556. case 'agent_thinking':
  1557. setStatus(event.cn_agent ? `${event.cn_agent}:分析中...` : (event.message || '正在分析...'));
  1558. break;
  1559. case 'thinking_token':
  1560. case 'agent_thinking_token':
  1561. if (event.content) appendThinking(event.content);
  1562. break;
  1563. case 'executing':
  1564. case 'agent_executing':
  1565. {
  1566. const label = event.cn_agent ? `${event.cn_agent}:${event.message}` : event.message;
  1567. setStatus(label || '正在执行工具...');
  1568. if (event.tools && event.tools.length > 0) {
  1569. const cnTools = event.cn_tools || event.tools;
  1570. // 翻页模式:仅展示最后一条(最新执行的工具)
  1571. const lastIdx = event.tools.length - 1;
  1572. addToolCard(event.tools[lastIdx], cnTools[lastIdx], 'pending', event.cn_agent);
  1573. }
  1574. }
  1575. break;
  1576. case 'tool_call':
  1577. addToolCard(event.tool, event.cn_tool, 'pending', event.cn_agent);
  1578. break;
  1579. case 'tool_result':
  1580. case 'agent_tool_result':
  1581. addToolCard(event.tool || '工具', event.cn_tool, 'done', event.cn_agent);
  1582. break;
  1583. case 'token':
  1584. if (event.content) appendToken(event.content);
  1585. break;
  1586. case 'updated_todo_list':
  1587. case 'agent_todos':
  1588. if (event.todos) {
  1589. // If agent context, show mini todos inside agent card
  1590. if (event.cn_agent) {
  1591. addAgentTodos(event.cn_agent, event.todos);
  1592. }
  1593. updateTodoList(event.todos);
  1594. }
  1595. break;
  1596. case 'progress':
  1597. setStatus(event.message || '处理中...');
  1598. if (event.download_url) {
  1599. pendingDownloadUrl = event.download_url;
  1600. // Immediately show the download button
  1601. const bubble = getOrCreateAssistantMsg();
  1602. // Remove any previous download button
  1603. bubble.querySelectorAll('.download-btn').forEach(el => el.remove());
  1604. bubble.appendChild(createDownloadBtn(event.download_url));
  1605. }
  1606. break;
  1607. case 'agent_start':
  1608. {
  1609. // 在聊天区显示子智能体启动卡片(体现并行感)
  1610. const cn = event.cn_agent || event.agent;
  1611. addAgentCard(cn, 'running');
  1612. setStatus(`${cn} 启动...`);
  1613. }
  1614. break;
  1615. case 'agent_done':
  1616. {
  1617. const cn = event.cn_agent || event.agent;
  1618. addAgentCard(cn, 'done', event.duration_ms, event.progress);
  1619. setStatus(`✅ ${cn} 完成 (${event.progress || ''})`);
  1620. // Agent 结束 → 无论工具处于什么状态,一律翻出清理
  1621. if (agentCards[cn]) {
  1622. const flipper = agentCards[cn].querySelector('.tool-flipper');
  1623. if (flipper) {
  1624. const ct = flipper.querySelector('.current-tool');
  1625. if (ct) {
  1626. if (ct._fadeTimer) { clearTimeout(ct._fadeTimer); ct._fadeTimer = null; }
  1627. ct.getAnimations().forEach(a => a.cancel());
  1628. ct.style.transform = '';
  1629. ct.style.opacity = '';
  1630. ct.className = 'current-tool flip-out';
  1631. }
  1632. }
  1633. }
  1634. }
  1635. break;
  1636. case 'agent_error':
  1637. showToast(event.message || '子智能体出错', 'error');
  1638. break;
  1639. case 'done':
  1640. clearStatus();
  1641. if (event.duration_ms) {
  1642. addDuration(event.duration_ms, '');
  1643. }
  1644. if (event.download_url) {
  1645. pendingDownloadUrl = event.download_url;
  1646. }
  1647. // 最终渲染 markdown ……
  1648. {
  1649. const bubble = getOrCreateAssistantMsg();
  1650. if (bubble) {
  1651. const md = bubble.querySelector('.msg-markdown');
  1652. if (md) {
  1653. const raw = md.getAttribute('data-raw');
  1654. if (raw) {
  1655. md.innerHTML = renderMarkdown(raw);
  1656. md.removeAttribute('data-raw');
  1657. }
  1658. }
  1659. // 兜底清理:所有 Agent 卡内残留的工具翻页
  1660. bubble.querySelectorAll('.tool-flipper .current-tool').forEach(ct => {
  1661. if (ct._fadeTimer) { clearTimeout(ct._fadeTimer); ct._fadeTimer = null; }
  1662. ct.getAnimations().forEach(a => a.cancel());
  1663. ct.style.transform = '';
  1664. ct.style.opacity = '';
  1665. ct.className = 'current-tool flip-out';
  1666. });
  1667. if (pendingDownloadUrl) {
  1668. bubble.querySelectorAll('.download-btn').forEach(el => el.remove());
  1669. bubble.appendChild(createDownloadBtn(pendingDownloadUrl));
  1670. }
  1671. }
  1672. }
  1673. activeThinkBlock = null;
  1674. loadSessions();
  1675. fetchContextUsage();
  1676. break;
  1677. case 'error':
  1678. showToast(event.message || '出错了', 'error');
  1679. clearStatus();
  1680. break;
  1681. case 'generating':
  1682. setStatus('正在生成报告...');
  1683. break;
  1684. case 'interrupt':
  1685. // LangGraph 中断:需要用户审批
  1686. pendingInterruptSession = currentSessionId;
  1687. showInterruptCard(event.message || '智能体暂停,等待审批...', event.node);
  1688. break;
  1689. }
  1690. }
  1691. function abortStream() {
  1692. if (currentAbortController) {
  1693. currentAbortController.abort();
  1694. currentAbortController = null;
  1695. }
  1696. document.getElementById('status-dot').classList.remove('streaming');
  1697. document.getElementById('btn-send').disabled = false;
  1698. clearStatus();
  1699. }
  1700. // ============================================================
  1701. // Helpers
  1702. // ============================================================
  1703. function escHtml(s) {
  1704. if (!s) return '';
  1705. return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  1706. }
  1707. function scrollToBottom() {
  1708. requestAnimationFrame(() => {
  1709. const msgs = document.getElementById('messages');
  1710. msgs.scrollTop = msgs.scrollHeight;
  1711. });
  1712. }
  1713. function onInputKey(e) {
  1714. if (e.key === 'Enter' && !e.shiftKey) {
  1715. e.preventDefault();
  1716. sendMessage();
  1717. }
  1718. }
  1719. function onFileSelected(input) {
  1720. const btn = document.getElementById('btn-attach');
  1721. if (input.files.length) {
  1722. btn.classList.add('has-file');
  1723. btn.title = input.files[0].name;
  1724. } else {
  1725. btn.classList.remove('has-file');
  1726. btn.title = '上传附件';
  1727. }
  1728. }
  1729. function showToast(msg, type) {
  1730. const container = document.getElementById('toast-container');
  1731. const el = document.createElement('div');
  1732. el.className = `toast ${type}`;
  1733. el.textContent = msg;
  1734. container.appendChild(el);
  1735. setTimeout(() => { el.remove(); }, 4000);
  1736. }
  1737. function createDownloadBtn(url) {
  1738. const btn = document.createElement('a');
  1739. btn.className = 'download-btn';
  1740. btn.href = url;
  1741. btn.target = '_blank';
  1742. btn.rel = 'noopener';
  1743. btn.innerHTML = '<span class="dl-icon">📥</span> 下载审查报告 (Word)';
  1744. return btn;
  1745. }
  1746. // Auto-resize textarea
  1747. document.addEventListener('DOMContentLoaded', () => {
  1748. const input = document.getElementById('input');
  1749. input.addEventListener('input', () => {
  1750. input.style.height = 'auto';
  1751. input.style.height = Math.min(input.scrollHeight, 150) + 'px';
  1752. });
  1753. });
  1754. // ============================================================
  1755. // Skill Manager
  1756. // ============================================================
  1757. async function openSkillManager() {
  1758. document.getElementById('skill-modal').style.display = 'flex';
  1759. await refreshSkillList();
  1760. }
  1761. function closeSkillModal() {
  1762. document.getElementById('skill-modal').style.display = 'none';
  1763. }
  1764. // ESC to close
  1765. document.addEventListener('keydown', (e) => {
  1766. if (e.key === 'Escape') closeSkillModal();
  1767. });
  1768. async function refreshSkillList() {
  1769. const body = document.getElementById('skill-modal-body');
  1770. body.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:40px;">加载中...</div>';
  1771. try {
  1772. const res = await fetch(`${API}/skills`);
  1773. const data = await res.json();
  1774. const skills = data.skills || [];
  1775. if (!skills.length) {
  1776. body.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:40px;">暂无技能</div>';
  1777. return;
  1778. }
  1779. let html = `<table class="skill-table">
  1780. <thead><tr>
  1781. <th>技能名称</th><th>描述</th><th>所属智能体</th><th>状态</th><th>操作</th>
  1782. </tr></thead><tbody>`;
  1783. skills.forEach(s => {
  1784. const statusCls = s.enabled ? 'enabled' : 'disabled';
  1785. const statusText = s.enabled ? '启用' : '禁用';
  1786. const toggleLabel = s.enabled ? '停用' : '启用';
  1787. html += `<tr>
  1788. <td><span class="skill-name" onclick="viewSkill('${s.name}')">${escHtml(s.display_name || s.name)}</span></td>
  1789. <td class="skill-desc" title="${escHtml(s.description)}">${escHtml(s.description) || '—'}</td>
  1790. <td class="skill-agents">${s.agents.map(a => escHtml(a)).join('<br>')}</td>
  1791. <td><span class="status-badge ${statusCls}">${statusText}</span></td>
  1792. <td>
  1793. <button class="btn-send" onclick="viewSkill('${s.name}')" style="width:auto;padding:3px 10px;font-size:11px;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-secondary);margin-right:4px;">查看</button>
  1794. <button class="btn-send" onclick="toggleSkill('${s.name}')" style="width:auto;padding:3px 10px;font-size:11px;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-secondary);">${toggleLabel}</button>
  1795. </td>
  1796. </tr>`;
  1797. });
  1798. html += '</tbody></table>';
  1799. // Upload zone
  1800. html += `<div class="upload-zone" id="skill-upload-zone" onclick="document.getElementById('skill-upload-input').click()">
  1801. 📤 点击上传新技能(.zip 格式)
  1802. </div>`;
  1803. // Detail section
  1804. html += '<div class="skill-detail" id="skill-detail"></div>';
  1805. body.innerHTML = html;
  1806. } catch(e) {
  1807. body.innerHTML = `<div style="text-align:center;color:var(--red);padding:40px;">加载失败: ${escHtml(e.message)}</div>`;
  1808. console.error(e);
  1809. }
  1810. }
  1811. async function viewSkill(name) {
  1812. const detail = document.getElementById('skill-detail');
  1813. if (!detail) return;
  1814. detail.style.display = 'block';
  1815. detail.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:20px;">加载中...</div>';
  1816. try {
  1817. const res = await fetch(`${API}/skills/${name}`);
  1818. if (!res.ok) {
  1819. const err = await res.json();
  1820. detail.innerHTML = `<div style="color:var(--red);padding:20px;">${escHtml(err.error || '加载失败')}</div>`;
  1821. return;
  1822. }
  1823. const data = await res.json();
  1824. // Strip YAML frontmatter before rendering
  1825. let content = data.content || '';
  1826. content = content.replace(/^---[\s\S]*?---\n*/, '');
  1827. detail.innerHTML = `<div style="margin-bottom:8px;color:var(--accent);font-weight:600;">📄 ${escHtml(name)} / SKILL.md</div>
  1828. <div>${renderMarkdown(content)}</div>`;
  1829. } catch(e) {
  1830. detail.innerHTML = `<div style="color:var(--red);padding:20px;">加载失败: ${escHtml(e.message)}</div>`;
  1831. console.error(e);
  1832. }
  1833. }
  1834. async function toggleSkill(name) {
  1835. try {
  1836. const res = await fetch(`${API}/skills/${name}/toggle`, { method: 'POST' });
  1837. const data = await res.json();
  1838. if (data.error) {
  1839. showToast(data.error, 'error');
  1840. return;
  1841. }
  1842. showToast(data.message, 'info');
  1843. await refreshSkillList();
  1844. } catch(e) {
  1845. showToast(`操作失败: ${e.message}`, 'error');
  1846. console.error(e);
  1847. }
  1848. }
  1849. async function uploadSkill(input) {
  1850. const file = input.files[0];
  1851. if (!file) return;
  1852. const fd = new FormData();
  1853. fd.append('file', file);
  1854. try {
  1855. showToast('正在上传技能...', 'info');
  1856. const res = await fetch(`${API}/skills/upload`, {
  1857. method: 'POST',
  1858. body: fd,
  1859. });
  1860. const data = await res.json();
  1861. if (!res.ok) {
  1862. showToast(data.error || '上传失败', 'error');
  1863. return;
  1864. }
  1865. showToast(data.message, 'info');
  1866. input.value = '';
  1867. await refreshSkillList();
  1868. } catch(e) {
  1869. showToast(`上传失败: ${e.message}`, 'error');
  1870. console.error(e);
  1871. }
  1872. }
  1873. </script>
  1874. </body>
  1875. </html>