index.html 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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. /* Main Chat Area */
  87. .main {
  88. flex: 1; display: flex; flex-direction: column;
  89. min-width: 0; background: var(--bg-primary);
  90. }
  91. .chat-header {
  92. padding: 12px 20px; border-bottom: 1px solid var(--border);
  93. font-size: 14px; font-weight: 600; color: var(--text-secondary);
  94. display: flex; align-items: center; gap: 8px;
  95. }
  96. .chat-header .status-dot {
  97. width: 8px; height: 8px; border-radius: 50%; background: var(--green);
  98. }
  99. .chat-header .status-dot.streaming { background: var(--yellow); animation: pulse 1s infinite; }
  100. @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.3} }
  101. .messages {
  102. flex: 1; overflow-y: auto; padding: 20px;
  103. display: flex; flex-direction: column; gap: 16px;
  104. }
  105. /* Message bubbles */
  106. .msg { max-width: 85%; animation: fadeIn .2s ease; }
  107. @keyframes fadeIn { from{opacity:0;transform:translateY(4px)} to{opacity:1;transform:translateY(0)} }
  108. .msg.user { align-self: flex-end; }
  109. .msg.assistant { align-self: flex-start; }
  110. .msg .role {
  111. font-size: 11px; font-weight: 600; text-transform: uppercase;
  112. margin-bottom: 4px; color: var(--text-muted);
  113. }
  114. .msg.user .role { text-align: right; }
  115. .msg .bubble {
  116. padding: 12px 16px; border-radius: var(--radius); line-height: 1.6;
  117. word-break: break-word;
  118. }
  119. .msg.user .bubble { background: var(--bg-surface); border: 1px solid var(--border); }
  120. .msg.assistant .bubble { background: transparent; padding: 0; }
  121. /* Markdown inside assistant bubble */
  122. .msg.assistant .bubble h1,.msg.assistant .bubble h2,.msg.assistant .bubble h3 {
  123. margin: 16px 0 8px; font-weight: 600; color: var(--accent);
  124. }
  125. .msg.assistant .bubble h1 { font-size: 1.3em; }
  126. .msg.assistant .bubble h2 { font-size: 1.15em; }
  127. .msg.assistant .bubble h3 { font-size: 1em; }
  128. .msg.assistant .bubble h4 { font-size: 0.95em; font-weight: 600; margin: 12px 0 6px; }
  129. .msg.assistant .bubble h5 { font-size: 0.9em; font-weight: 600; margin: 10px 0 4px; color: var(--text-secondary); }
  130. .msg.assistant .bubble h6 { font-size: 0.85em; font-weight: 600; margin: 8px 0 4px; color: var(--text-muted); }
  131. .msg.assistant .bubble p { margin: 4px 0; }
  132. .msg.assistant .bubble ul,.msg.assistant .bubble ol { padding-left: 20px; margin: 8px 0; }
  133. .msg.assistant .bubble li { margin: 2px 0; }
  134. .msg.assistant .bubble code {
  135. font-family: var(--font-mono); font-size: 0.9em;
  136. background: var(--bg-tertiary); padding: 2px 6px; border-radius: var(--radius-sm);
  137. }
  138. .msg.assistant .bubble pre {
  139. background: var(--bg-tertiary); border: 1px solid var(--border);
  140. border-radius: var(--radius); padding: 12px 16px; overflow-x: auto;
  141. margin: 8px 0; font-size: 13px; line-height: 1.5;
  142. }
  143. .msg.assistant .bubble pre code { background: none; padding: 0; }
  144. .msg.assistant .bubble table {
  145. border-collapse: collapse; width: 100%; margin: 8px 0; font-size: 13px;
  146. }
  147. .msg.assistant .bubble th,.msg.assistant .bubble td {
  148. border: 1px solid var(--border); padding: 6px 10px; text-align: left;
  149. }
  150. .msg.assistant .bubble th { background: var(--bg-surface); font-weight: 600; }
  151. .msg.assistant .bubble strong { color: var(--yellow); }
  152. .msg.assistant .bubble blockquote {
  153. border-left: 3px solid var(--accent); padding-left: 12px;
  154. color: var(--text-secondary); margin: 8px 0;
  155. }
  156. /* Thinking block */
  157. .think-block {
  158. margin: 8px 0; border: 1px solid var(--border);
  159. border-radius: var(--radius); overflow: hidden;
  160. background: var(--bg-surface);
  161. }
  162. .think-block summary {
  163. padding: 8px 12px; cursor: pointer; font-size: 12px;
  164. color: var(--text-muted); background: var(--bg-tertiary);
  165. user-select: none; display: flex; align-items: center; gap: 6px;
  166. transition: color .15s;
  167. }
  168. .think-block summary:hover { color: var(--accent); }
  169. .think-block summary::marker { font-size: 10px; }
  170. .think-block .think-content {
  171. padding: 10px 14px; font-size: 12px; color: var(--text-muted);
  172. line-height: 1.6; max-height: 300px; overflow-y: auto;
  173. font-family: var(--font-sans); white-space: pre-wrap;
  174. border-top: 1px solid var(--border);
  175. background: var(--bg-surface);
  176. }
  177. .think-block summary .think-icon { animation: spin 2s linear infinite; display: inline-block; }
  178. .think-block[open] summary .think-icon { animation: none; }
  179. /* Duration badge */
  180. .msg-duration {
  181. font-size: 11px; color: var(--text-muted); margin-top: 4px;
  182. display: flex; align-items: center; gap: 4px;
  183. }
  184. /* Agent card — container for sub-agent tools + progress */
  185. .agent-card {
  186. margin: 6px 0; border: 1px solid var(--border);
  187. border-radius: var(--radius); overflow: hidden;
  188. background: var(--bg-surface); font-size: 12px;
  189. border-left: 3px solid var(--accent);
  190. transition: border-color .3s;
  191. }
  192. .agent-card.running { border-left-color: var(--yellow); }
  193. .agent-card.done { border-left-color: var(--green); }
  194. .agent-card.error { border-left-color: var(--red); }
  195. .agent-card .agent-header {
  196. display: flex; align-items: center; gap: 8px;
  197. padding: 8px 12px; background: var(--bg-tertiary);
  198. }
  199. .agent-card .agent-icon {
  200. width: 16px; height: 16px; flex-shrink: 0;
  201. display: inline-flex; align-items: center; justify-content: center;
  202. font-size: 12px; line-height: 1;
  203. }
  204. /* 运行中:环形旋转 spinner */
  205. .agent-card.running .agent-icon {
  206. width: 14px; height: 14px;
  207. border: 2px solid var(--border);
  208. border-top-color: var(--yellow);
  209. border-radius: 50%;
  210. animation: spin 0.8s linear infinite;
  211. font-size: 0;
  212. }
  213. /* 完成/错误:emoji 居中 */
  214. .agent-card.done .agent-icon,
  215. .agent-card.error .agent-icon {
  216. border: none; width: 16px; height: 16px;
  217. animation: none; font-size: 12px;
  218. }
  219. .agent-card .agent-name { color: var(--text-secondary); flex: 1; font-weight: 500; }
  220. .agent-card .agent-status { font-size: 11px; color: var(--text-muted); }
  221. .agent-card .agent-body {
  222. padding: 2px 0;
  223. max-height: 250px; overflow-y: auto;
  224. }
  225. /* ── 工具翻页动画(仅显示当前正在执行的一个工具)── */
  226. .agent-body .tool-flipper {
  227. perspective: 600px;
  228. min-height: 30px;
  229. overflow: hidden;
  230. }
  231. .agent-body .current-tool {
  232. padding: 5px 12px; font-size: 11px;
  233. display: flex; align-items: center; gap: 6px;
  234. color: var(--text-muted);
  235. transform-origin: center center;
  236. backface-visibility: hidden;
  237. }
  238. .agent-body .current-tool.flip-out {
  239. animation: toolFlipOut 0.28s ease forwards;
  240. pointer-events: none;
  241. }
  242. .agent-body .current-tool.flip-in {
  243. animation: toolFlipIn 0.32s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  244. }
  245. @keyframes toolFlipIn {
  246. from { transform: rotateX(100deg); opacity: 0; }
  247. to { transform: rotateX(0deg); opacity: 1; }
  248. }
  249. @keyframes toolFlipOut {
  250. from { transform: rotateX(0deg); opacity: 1; }
  251. to { transform: rotateX(-100deg); opacity: 0; }
  252. }
  253. .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; }
  254. .agent-body .current-tool .mt-name { flex: 1; color: var(--yellow); }
  255. .agent-body .current-tool.done .mt-name { color: var(--text-secondary); }
  256. /* 工具执行中的环形旋转 spinner */
  257. .spin-icon-sm {
  258. display: inline-block;
  259. width: 10px; height: 10px;
  260. border: 2px solid var(--border);
  261. border-top-color: var(--yellow);
  262. border-radius: 50%;
  263. animation: spin 0.7s linear infinite;
  264. flex-shrink: 0;
  265. vertical-align: middle;
  266. }
  267. /* Nested mini todo inside agent body */
  268. .agent-body .mini-todo {
  269. display: flex; align-items: center; gap: 4px;
  270. padding: 3px 12px; font-size: 11px; color: var(--text-muted);
  271. border-bottom: 1px solid var(--border);
  272. }
  273. .agent-body .mini-todo .mt-check {
  274. width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0;
  275. border: 2px solid var(--border);
  276. }
  277. .agent-body .mini-todo.completed .mt-check { background: var(--green); border-color: var(--green); }
  278. .agent-body .mini-todo.in_progress .mt-check { border-color: var(--yellow); background: var(--yellow); }
  279. .agent-body .mini-todo .mt-label { flex: 1; font-size: 11px; }
  280. .agent-body .mini-todo.completed .mt-label { text-decoration: line-through; }
  281. /* Tool call card (standalone, outside agent) */
  282. .tool-card {
  283. margin: 6px 0; padding: 8px 12px; border-radius: var(--radius-sm);
  284. background: var(--bg-surface); border-left: 3px solid var(--accent);
  285. font-size: 12px; display: flex; align-items: center; gap: 8px;
  286. }
  287. .tool-card.pending { border-left-color: var(--yellow); }
  288. .tool-card.done { border-left-color: var(--green); }
  289. .tool-card .tool-icon { font-size: 14px; }
  290. .tool-card .tool-name { color: var(--text-secondary); flex: 1; }
  291. .tool-card .tool-status { font-size: 11px; color: var(--text-muted); }
  292. /* Status bar (agent thinking/executing) */
  293. .status-bar {
  294. padding: 6px 16px; font-size: 12px; color: var(--text-muted);
  295. border-top: 1px solid var(--border); display: flex; align-items: center; gap: 8px;
  296. min-height: 32px;
  297. }
  298. .status-bar .spinner {
  299. width: 12px; height: 12px; border: 2px solid var(--border);
  300. border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite;
  301. }
  302. @keyframes spin { to{transform:rotate(360deg)} }
  303. /* Input area */
  304. .input-area {
  305. padding: 12px 20px; border-top: 1px solid var(--border);
  306. display: flex; gap: 10px; align-items: center;
  307. }
  308. .input-area textarea {
  309. flex: 1; background: var(--bg-surface); border: 1px solid var(--border);
  310. border-radius: var(--radius); color: var(--text-primary); padding: 10px 14px;
  311. font-family: var(--font-sans); font-size: 14px; resize: none; outline: none;
  312. min-height: 44px; max-height: 150px; line-height: 1.4;
  313. transition: border-color .15s;
  314. }
  315. .input-area textarea:focus { border-color: var(--accent); }
  316. .btn-send {
  317. width: 44px; height: 44px; border-radius: var(--radius);
  318. background: var(--accent); color: var(--bg-tertiary); border: none;
  319. font-size: 18px; cursor: pointer; transition: background .15s;
  320. display: flex; align-items: center; justify-content: center; flex-shrink: 0;
  321. }
  322. .btn-send:hover { background: var(--accent-dim); }
  323. .btn-send:disabled { background: var(--border); cursor: not-allowed; }
  324. .btn-attach {
  325. width: 44px; height: 44px; border-radius: var(--radius);
  326. background: var(--bg-surface); border: 1px solid var(--border);
  327. color: var(--text-secondary); font-size: 18px; cursor: pointer;
  328. display: flex; align-items: center; justify-content: center; flex-shrink: 0;
  329. transition: background .1s, border-color .1s;
  330. }
  331. .btn-attach:hover { border-color: var(--accent); color: var(--accent); }
  332. .btn-attach.has-file { border-color: var(--green); color: var(--green); }
  333. #file-input { display: none; }
  334. /* Detail Panel (right) */
  335. .detail-panel {
  336. width: 280px; min-width: 280px;
  337. background: var(--bg-secondary); border-left: 1px solid var(--border);
  338. display: flex; flex-direction: column; overflow: hidden;
  339. }
  340. .detail-panel h3 {
  341. padding: 16px; font-size: 13px; font-weight: 600;
  342. color: var(--text-muted); text-transform: uppercase;
  343. letter-spacing: 0.5px; border-bottom: 1px solid var(--border);
  344. }
  345. .detail-content { flex: 1; overflow-y: auto; padding: 12px; }
  346. .detail-content .section { margin-bottom: 16px; }
  347. .detail-content .section-title {
  348. font-size: 11px; font-weight: 600; color: var(--text-muted);
  349. text-transform: uppercase; margin-bottom: 8px;
  350. }
  351. .todo-item {
  352. display: flex; align-items: center; gap: 8px; padding: 4px 0; font-size: 12px;
  353. }
  354. .todo-item .todo-check {
  355. width: 14px; height: 14px; border-radius: 50%;
  356. border: 2px solid var(--border); flex-shrink: 0;
  357. }
  358. .todo-item.completed .todo-check { background: var(--green); border-color: var(--green); }
  359. .todo-item.in_progress .todo-check { border-color: var(--yellow); background: var(--yellow); }
  360. .todo-item .todo-label { color: var(--text-secondary); }
  361. .todo-item.completed .todo-label { text-decoration: line-through; color: var(--text-muted); }
  362. .tool-log-item {
  363. font-size: 11px; padding: 4px 0; color: var(--text-muted);
  364. border-bottom: 1px solid var(--border); display: flex; gap: 6px;
  365. }
  366. .tool-log-item .tl-icon { flex-shrink: 0; }
  367. .tool-log-item .tl-name { color: var(--text-secondary); }
  368. /* Toast */
  369. .toast {
  370. position: fixed; top: 16px; right: 16px; padding: 10px 16px;
  371. border-radius: var(--radius); font-size: 13px; z-index: 1000;
  372. animation: slideIn .2s ease; max-width: 400px;
  373. }
  374. .toast.error { background: var(--red); color: #fff; }
  375. .toast.info { background: var(--accent); color: var(--bg-tertiary); }
  376. @keyframes slideIn { from{transform:translateX(100%)} to{transform:translateX(0)} }
  377. /* Download Button */
  378. .download-btn {
  379. display: inline-flex; align-items: center; gap: 8px;
  380. padding: 10px 20px; margin: 12px 0;
  381. background: var(--green); color: var(--bg-tertiary);
  382. border: none; border-radius: var(--radius);
  383. font-size: 14px; font-weight: 600; cursor: pointer;
  384. text-decoration: none; transition: background .15s, transform .1s;
  385. }
  386. .download-btn:hover { background: #8fd98f; transform: translateY(-1px); }
  387. .download-btn:active { transform: translateY(0); }
  388. .download-btn .dl-icon { font-size: 18px; }
  389. /* Empty state */
  390. .empty-state {
  391. flex: 1; display: flex; flex-direction: column; align-items: center;
  392. justify-content: center; color: var(--text-muted); gap: 12px;
  393. }
  394. .empty-state .big-icon { font-size: 48px; opacity: .3; }
  395. /* Scrollbar */
  396. ::-webkit-scrollbar { width: 6px; }
  397. ::-webkit-scrollbar-track { background: transparent; }
  398. ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
  399. ::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
  400. /* Responsive: hide detail panel on small screens */
  401. @media (max-width: 1000px) { .detail-panel { display: none; } }
  402. @media (max-width: 700px) { .sidebar { display: none; } }
  403. </style>
  404. </head>
  405. <body>
  406. <div class="app">
  407. <!-- ============ Sidebar: Session List ============ -->
  408. <aside class="sidebar">
  409. <div class="sidebar-header">
  410. <h2>💨 通风智能助手</h2>
  411. <button class="btn-new" onclick="newSession()" title="新建会话">+</button>
  412. </div>
  413. <div class="session-list" id="session-list"></div>
  414. </aside>
  415. <!-- ============ Main Chat Area ============ -->
  416. <main class="main">
  417. <div class="chat-header">
  418. <span class="status-dot" id="status-dot"></span>
  419. <span id="chat-title">新会话</span>
  420. </div>
  421. <div class="messages" id="messages">
  422. <div class="empty-state">
  423. <div class="big-icon">⛏️</div>
  424. <div>煤矿通风数据智能解读系统</div>
  425. <div style="font-size:12px">输入问题或上传配风计划 PDF 开始分析</div>
  426. </div>
  427. </div>
  428. <div class="status-bar" id="status-bar"></div>
  429. <div class="input-area">
  430. <button class="btn-attach" id="btn-attach" onclick="document.getElementById('file-input').click()" title="上传附件">📎</button>
  431. <input type="file" id="file-input" accept=".pdf,.doc,.docx,.txt" onchange="onFileSelected(this)">
  432. <textarea id="input" placeholder="输入您的问题..." rows="1" onkeydown="onInputKey(event)"></textarea>
  433. <button class="btn-send" id="btn-send" onclick="sendMessage()" title="发送">↑</button>
  434. </div>
  435. </main>
  436. <!-- ============ Detail Panel ============ -->
  437. <aside class="detail-panel" id="detail-panel">
  438. <h3>📋 任务详情</h3>
  439. <div class="detail-content" id="detail-content">
  440. <div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">
  441. 发送消息后<br>此处显示任务进度和工具调用
  442. </div>
  443. </div>
  444. </aside>
  445. </div>
  446. <!-- Toast container -->
  447. <div id="toast-container"></div>
  448. <script>
  449. // ============================================================
  450. // State
  451. // ============================================================
  452. const API = '/api';
  453. let currentSessionId = localStorage.getItem('vent_session_id') || null;
  454. let currentAbortController = null;
  455. let todoItems = [];
  456. let toolLogs = [];
  457. let activeThinkBlock = null;
  458. let pendingDownloadUrl = null;
  459. // ============================================================
  460. // Init
  461. // ============================================================
  462. document.addEventListener('DOMContentLoaded', () => {
  463. loadSessions();
  464. if (currentSessionId) loadHistory(currentSessionId);
  465. });
  466. // ============================================================
  467. // Session Management
  468. // ============================================================
  469. async function loadSessions() {
  470. try {
  471. const res = await fetch(`${API}/sessions`);
  472. const data = await res.json();
  473. renderSessionList(data.sessions || []);
  474. } catch(e) { console.error('加载会话列表失败', e); }
  475. }
  476. function renderSessionList(sessions) {
  477. const el = document.getElementById('session-list');
  478. if (!sessions.length) {
  479. el.innerHTML = '<div style="color:var(--text-muted);font-size:12px;padding:16px;text-align:center">暂无会话</div>';
  480. return;
  481. }
  482. el.innerHTML = sessions.map(s => `
  483. <div class="session-item ${s.session_id === currentSessionId ? 'active' : ''}"
  484. onclick="switchSession('${s.session_id}')">
  485. <span class="title">${escHtml(s.title || s.session_id?.slice(0,8) || '新会话')}</span>
  486. <span class="count">${s.message_count || 0}</span>
  487. <button class="btn-delete" onclick="event.stopPropagation();deleteSession('${s.session_id}')">×</button>
  488. </div>
  489. `).join('');
  490. }
  491. function newSession() {
  492. abortStream();
  493. currentSessionId = null;
  494. localStorage.removeItem('vent_session_id');
  495. document.getElementById('messages').innerHTML = `
  496. <div class="empty-state">
  497. <div class="big-icon">⛏️</div>
  498. <div>煤矿通风数据智能解读系统</div>
  499. <div style="font-size:12px">输入问题或上传配风计划 PDF 开始分析</div>
  500. </div>`;
  501. document.getElementById('chat-title').textContent = '新会话';
  502. document.getElementById('status-bar').innerHTML = '';
  503. document.getElementById('detail-content').innerHTML = '<div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">发送消息后<br>此处显示任务进度和工具调用</div>';
  504. todoItems = [];
  505. toolLogs = [];
  506. pendingDownloadUrl = null;
  507. loadSessions();
  508. }
  509. async function switchSession(sid) {
  510. if (sid === currentSessionId) return;
  511. abortStream();
  512. currentSessionId = sid;
  513. localStorage.setItem('vent_session_id', sid);
  514. document.getElementById('chat-title').textContent = sid.slice(0,8) + '...';
  515. loadSessions();
  516. await loadHistory(sid);
  517. }
  518. async function deleteSession(sid) {
  519. abortStream();
  520. await fetch(`${API}/sessions/${sid}`, { method: 'DELETE' });
  521. if (currentSessionId === sid) newSession();
  522. else loadSessions();
  523. }
  524. async function loadHistory(sid) {
  525. try {
  526. const res = await fetch(`${API}/chat/history/${sid}`);
  527. const data = await res.json();
  528. const msgsEl = document.getElementById('messages');
  529. msgsEl.innerHTML = '';
  530. if (!data.messages || !data.messages.length) {
  531. msgsEl.innerHTML = '<div class="empty-state"><div class="big-icon">💬</div><div>开始对话吧</div></div>';
  532. return;
  533. }
  534. let lastRole = null;
  535. data.messages.forEach(m => {
  536. if (m.role === 'user') {
  537. addMessage('user', m.content);
  538. lastRole = 'user';
  539. } else if (m.role === 'assistant' && m.content) {
  540. addMessage('assistant', m.content);
  541. lastRole = 'assistant';
  542. }
  543. });
  544. document.getElementById('chat-title').textContent = data.messages[0]?.content?.slice(0,30) || sid.slice(0,8);
  545. scrollToBottom();
  546. } catch(e) { console.error('加载历史失败', e); }
  547. }
  548. // ============================================================
  549. // Message Rendering
  550. // ============================================================
  551. function addMessage(role, content) {
  552. const msgs = document.getElementById('messages');
  553. // Remove empty state
  554. const empty = msgs.querySelector('.empty-state');
  555. if (empty) empty.remove();
  556. const div = document.createElement('div');
  557. div.className = `msg ${role}`;
  558. div.innerHTML = `
  559. <div class="role">${role === 'user' ? 'YOU' : 'ASSISTANT'}</div>
  560. <div class="bubble">${role === 'assistant' ? renderMarkdown(content) : escHtml(content)}</div>`;
  561. msgs.appendChild(div);
  562. scrollToBottom();
  563. return div;
  564. }
  565. function getOrCreateAssistantMsg() {
  566. const msgs = document.getElementById('messages');
  567. const empty = msgs.querySelector('.empty-state');
  568. if (empty) empty.remove();
  569. // Find last assistant message
  570. let last = msgs.querySelector('.msg.assistant:last-child');
  571. if (!last) {
  572. last = document.createElement('div');
  573. last.className = 'msg assistant';
  574. last.innerHTML = '<div class="role">ASSISTANT</div><div class="bubble"></div>';
  575. msgs.appendChild(last);
  576. activeThinkBlock = null;
  577. }
  578. const bubble = last.querySelector('.bubble');
  579. // 确保 markdown 文本容器存在(与 Agent 卡片/工具卡片隔离)
  580. if (!bubble.querySelector('.msg-markdown')) {
  581. const md = document.createElement('div');
  582. md.className = 'msg-markdown';
  583. bubble.appendChild(md);
  584. }
  585. return bubble;
  586. }
  587. function appendToken(text) {
  588. const bubble = getOrCreateAssistantMsg();
  589. const md = bubble.querySelector('.msg-markdown');
  590. // 累积原始 markdown 文本
  591. const existing = md.getAttribute('data-raw') || '';
  592. md.setAttribute('data-raw', existing + text);
  593. // 实时追加 token 文本
  594. const span = document.createElement('span');
  595. span.textContent = text;
  596. md.appendChild(span);
  597. // 每积累约 128 字符时重新渲染(保持表格/标题等格式实时可见)
  598. const raw = md.getAttribute('data-raw');
  599. if (raw && raw.length % 128 < text.length) {
  600. md.innerHTML = renderMarkdown(raw);
  601. md.setAttribute('data-raw', raw);
  602. }
  603. scrollToBottom();
  604. }
  605. function appendThinking(text) {
  606. const bubble = getOrCreateAssistantMsg();
  607. if (!activeThinkBlock || !bubble.contains(activeThinkBlock)) {
  608. activeThinkBlock = document.createElement('details');
  609. activeThinkBlock.className = 'think-block';
  610. activeThinkBlock.open = true; // 默认展开
  611. activeThinkBlock.innerHTML = '<summary><span class="think-icon">💭</span> 思考过程</summary><div class="think-content"></div>';
  612. // Insert at beginning of bubble, before any existing content
  613. bubble.insertBefore(activeThinkBlock, bubble.firstChild);
  614. }
  615. const content = activeThinkBlock.querySelector('.think-content');
  616. content.textContent += text;
  617. // Auto-scroll the think content
  618. content.scrollTop = content.scrollHeight;
  619. scrollToBottom();
  620. }
  621. function addToolCard(name, cnName, status, agentCn) {
  622. const displayName = cnName || name;
  623. // ── Agent 内工具:翻页动画,仅显示当前正在执行的一个 ──
  624. if (agentCn && agentCards[agentCn]) {
  625. const body = agentCards[agentCn].querySelector('.agent-body');
  626. if (!body) return;
  627. // 获取或创建翻页容器,始终保持在 body 的最底部
  628. let flipper = body.querySelector('.tool-flipper');
  629. if (!flipper) {
  630. flipper = document.createElement('div');
  631. flipper.className = 'tool-flipper';
  632. }
  633. body.appendChild(flipper);
  634. // 当前显示的工具元素
  635. let current = flipper.querySelector('.current-tool');
  636. if (!current) {
  637. current = document.createElement('div');
  638. current.className = 'current-tool';
  639. current.innerHTML = `<span class="mt-icon spin-icon-sm"></span><span class="mt-name"></span>`;
  640. flipper.appendChild(current);
  641. }
  642. // ── 取消所有进行中的动画,干净重置 ──
  643. current.getAnimations().forEach(a => a.cancel());
  644. if (current._fadeTimer) { clearTimeout(current._fadeTimer); current._fadeTimer = null; }
  645. // 清除动画残留的 inline style(animation fill 可能留下的 transform/opacity)
  646. current.style.transform = '';
  647. current.style.opacity = '';
  648. if (status === 'done') {
  649. // 工具完成:显示 ✅,1.2s 后翻出消失
  650. current.className = 'current-tool done';
  651. const iconEl = current.querySelector('.mt-icon');
  652. iconEl.className = 'mt-icon';
  653. iconEl.textContent = '✅';
  654. current.querySelector('.mt-name').textContent = displayName;
  655. current._fadeTimer = setTimeout(() => {
  656. if (current.parentNode) {
  657. // 取消可能在进行中的动画,然后翻出
  658. current.getAnimations().forEach(a => a.cancel());
  659. current.style.transform = '';
  660. current.style.opacity = '';
  661. current.className = 'current-tool flip-out';
  662. current._fadeTimer = null;
  663. }
  664. }, 1200);
  665. } else {
  666. // 新工具开始:直接翻入替换
  667. current.className = 'current-tool';
  668. const iconEl = current.querySelector('.mt-icon');
  669. iconEl.className = 'mt-icon spin-icon-sm';
  670. iconEl.textContent = '';
  671. current.querySelector('.mt-name').textContent = displayName;
  672. // 强制回流后启动翻入动画
  673. void current.offsetWidth;
  674. current.classList.add('flip-in');
  675. }
  676. body.scrollTop = body.scrollHeight;
  677. scrollToBottom();
  678. toolLogs.push({ name: displayName, status, time: new Date().toLocaleTimeString() });
  679. updateDetailPanel();
  680. return;
  681. }
  682. // ── 独立工具卡片(无 Agent 上下文,保留列表模式)──
  683. const bubble = getOrCreateAssistantMsg();
  684. const card = document.createElement('div');
  685. card.className = `tool-card ${status}`;
  686. if (status === 'done') {
  687. card.innerHTML = `<span class="tool-icon">✅</span>
  688. <span class="tool-name">${escHtml(displayName)}</span>
  689. <span class="tool-status">完成</span>`;
  690. } else {
  691. card.innerHTML = `<span class="tool-icon spin-icon-sm"></span>
  692. <span class="tool-name">${escHtml(displayName)}</span>
  693. <span class="tool-status">执行中...</span>`;
  694. }
  695. // 插入到 markdown 之前
  696. const md = bubble.querySelector('.msg-markdown');
  697. if (md) { bubble.insertBefore(card, md); }
  698. else { bubble.appendChild(card); }
  699. scrollToBottom();
  700. toolLogs.push({ name: displayName, status, time: new Date().toLocaleTimeString() });
  701. updateDetailPanel();
  702. }
  703. // ── Agent Card: container for sub-agent tools + progress ──
  704. let agentCards = {};
  705. function addAgentCard(cnName, status, durationMs, progress) {
  706. const bubble = getOrCreateAssistantMsg();
  707. const key = cnName;
  708. if (agentCards[key]) {
  709. const card = agentCards[key];
  710. card.className = `agent-card ${status}`;
  711. const iconEl = card.querySelector('.agent-icon');
  712. if (status === 'done') {
  713. iconEl.textContent = '✅';
  714. } else if (status === 'error') {
  715. iconEl.textContent = '❌';
  716. } else {
  717. iconEl.textContent = ''; // CSS spinner handles the running icon
  718. }
  719. const durText = durationMs ? ` (${(durationMs/1000).toFixed(1)}s)` : '';
  720. const progText = progress ? ` [${progress}]` : '';
  721. card.querySelector('.agent-status').textContent = status === 'done' ? `完成${durText}${progText}` : '运行中...';
  722. } else {
  723. const card = document.createElement('div');
  724. card.className = `agent-card ${status}`;
  725. card.innerHTML = `<div class="agent-header">
  726. <span class="agent-icon"></span>
  727. <span class="agent-name">${escHtml(cnName)}</span>
  728. <span class="agent-status">启动...</span>
  729. </div>
  730. <div class="agent-body"></div>`;
  731. // 插入到 markdown 文本容器之前,确保 Agent 卡片在 token 输出上方
  732. const md = bubble.querySelector('.msg-markdown');
  733. if (md) {
  734. bubble.insertBefore(card, md);
  735. } else {
  736. bubble.appendChild(card);
  737. }
  738. agentCards[key] = card;
  739. }
  740. scrollToBottom();
  741. }
  742. // ── Add mini todos inside an agent card ──
  743. function addAgentTodos(agentCn, todos) {
  744. if (!agentCn || !agentCards[agentCn]) return;
  745. const body = agentCards[agentCn].querySelector('.agent-body');
  746. if (!body) return;
  747. // Remove old mini-todos
  748. body.querySelectorAll('.mini-todo').forEach(el => el.remove());
  749. todos.forEach(t => {
  750. const cls = t.status === 'completed' ? 'completed' : t.status === 'in_progress' ? 'in_progress' : '';
  751. const mt = document.createElement('div');
  752. mt.className = `mini-todo ${cls}`;
  753. mt.innerHTML = `<span class="mt-check"></span><span class="mt-label">${escHtml(t.content || '')}</span>`;
  754. body.appendChild(mt);
  755. });
  756. // 确保工具翻页始终在最底部可见
  757. const flipper = body.querySelector('.tool-flipper');
  758. if (flipper) body.appendChild(flipper);
  759. body.scrollTop = body.scrollHeight;
  760. scrollToBottom();
  761. }
  762. function addDuration(durationMs, cnAgent) {
  763. const bubble = getOrCreateAssistantMsg();
  764. const dur = document.createElement('div');
  765. dur.className = 'msg-duration';
  766. const sec = (durationMs / 1000).toFixed(1);
  767. const agentLabel = cnAgent ? ` · ${cnAgent}` : '';
  768. dur.innerHTML = `⏱️ ${sec}s${agentLabel}`;
  769. bubble.appendChild(dur);
  770. }
  771. function updateTodoList(todos) {
  772. todoItems = todos || [];
  773. updateDetailPanel();
  774. }
  775. function updateDetailPanel() {
  776. const el = document.getElementById('detail-content');
  777. let html = '';
  778. if (todoItems.length) {
  779. html += '<div class="section"><div class="section-title">📝 任务进度</div>';
  780. todoItems.forEach(t => {
  781. const cls = t.status === 'completed' ? 'completed' : t.status === 'in_progress' ? 'in_progress' : '';
  782. html += `<div class="todo-item ${cls}">
  783. <span class="todo-check"></span>
  784. <span class="todo-label">${escHtml(t.content || '')}</span>
  785. </div>`;
  786. });
  787. html += '</div>';
  788. }
  789. if (toolLogs.length) {
  790. html += '<div class="section"><div class="section-title">🔧 工具调用</div>';
  791. toolLogs.slice(-20).reverse().forEach(t => {
  792. html += `<div class="tool-log-item">
  793. <span class="tl-icon">${t.status === 'done' ? '✅' : '⏳'}</span>
  794. <span class="tl-name">${escHtml(t.name)}</span>
  795. </div>`;
  796. });
  797. html += '</div>';
  798. }
  799. if (!html) {
  800. html = '<div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">暂无任务数据</div>';
  801. }
  802. el.innerHTML = html;
  803. }
  804. function setStatus(text) {
  805. document.getElementById('status-bar').innerHTML = `
  806. <span class="spinner"></span><span>${escHtml(text)}</span>`;
  807. }
  808. function clearStatus() {
  809. document.getElementById('status-bar').innerHTML = '';
  810. }
  811. // ============================================================
  812. // Markdown Rendering (simple built-in, no CDN dependency)
  813. // ============================================================
  814. function renderMarkdown(text) {
  815. if (!text) return '';
  816. let html = text;
  817. // Escape HTML
  818. html = html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  819. // Code blocks (```...```)
  820. html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) =>
  821. `<pre><code class="language-${lang}">${code.trim()}</code></pre>`);
  822. // Inline code (`...`)
  823. html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
  824. // Bold (**...**)
  825. html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  826. // Headers (longest first to avoid partial matches)
  827. html = html.replace(/^###### (.+)$/gm, '<h6>$1</h6>');
  828. html = html.replace(/^##### (.+)$/gm, '<h5>$1</h5>');
  829. html = html.replace(/^#### (.+)$/gm, '<h4>$1</h4>');
  830. html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
  831. html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
  832. html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
  833. // Blockquote
  834. html = html.replace(/^&gt; (.+)$/gm, '<blockquote>$1</blockquote>');
  835. // Unordered lists
  836. html = html.replace(/^[\-\*] (.+)$/gm, '<li>$1</li>');
  837. html = html.replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>');
  838. // Ordered lists
  839. html = html.replace(/^\d+\. (.+)$/gm, '<li>$1</li>');
  840. // Tables
  841. html = html.replace(/^\|(.+)\|$/gm, (line) => {
  842. const cells = line.split('|').filter(c => c.trim());
  843. const isHeader = /^[\-\s:]+$/.test(cells.join(''));
  844. if (isHeader) return '';
  845. const tag = line.match(/^\|[\s\-:]+\|$/) ? '' : (line.includes('---') ? '' : '');
  846. return '<tr>' + cells.map(c => {
  847. const t = isHeader ? 'th' : 'td';
  848. return `<${t}>${c.trim()}</${t}>`;
  849. }).join('') + '</tr>';
  850. });
  851. html = html.replace(/(<tr>.*<\/tr>\n?)+/g, '<table>$&</table>');
  852. // Horizontal rules
  853. html = html.replace(/^---$/gm, '<hr>');
  854. // Paragraphs (double newline)
  855. const parts = html.split(/\n\n+/);
  856. html = parts.map(p => {
  857. p = p.trim();
  858. if (!p) return '';
  859. if (p.startsWith('<h') || p.startsWith('<pre') || p.startsWith('<table')
  860. || p.startsWith('<ul') || p.startsWith('<blockquote') || p.startsWith('<hr')) return p;
  861. return `<p>${p.replace(/\n/g, '<br>')}</p>`;
  862. }).join('\n');
  863. return html;
  864. }
  865. // ============================================================
  866. // SSE Streaming
  867. // ============================================================
  868. async function sendMessage() {
  869. const input = document.getElementById('input');
  870. const message = input.value.trim();
  871. const fileInput = document.getElementById('file-input');
  872. const file = fileInput.files[0];
  873. if (!message && !file) return;
  874. // Abort previous stream
  875. abortStream();
  876. // Reset state
  877. todoItems = [];
  878. toolLogs = [];
  879. activeThinkBlock = null;
  880. agentCards = {};
  881. pendingDownloadUrl = null;
  882. updateDetailPanel();
  883. // Build FormData
  884. const fd = new FormData();
  885. fd.append('message', message || (file ? '请审查这份文件' : ''));
  886. if (currentSessionId) fd.append('session_id', currentSessionId);
  887. if (file) {
  888. fd.append('file', file);
  889. document.getElementById('btn-attach').classList.add('has-file');
  890. }
  891. // Add user message to UI
  892. if (message) addMessage('user', message);
  893. if (file) {
  894. addMessage('user', `📎 上传文件: ${file.name}\n${message || '请审查这份文件'}`);
  895. }
  896. // Clear input
  897. input.value = '';
  898. fileInput.value = '';
  899. document.getElementById('btn-attach').classList.remove('has-file');
  900. input.style.height = 'auto';
  901. // UI state
  902. setStatus('正在分析...');
  903. document.getElementById('status-dot').classList.add('streaming');
  904. document.getElementById('btn-send').disabled = true;
  905. currentAbortController = new AbortController();
  906. try {
  907. const res = await fetch(`${API}/chat`, {
  908. method: 'POST',
  909. body: fd,
  910. signal: currentAbortController.signal,
  911. });
  912. if (!res.ok) {
  913. const errText = await res.text();
  914. throw new Error(`HTTP ${res.status}: ${errText}`);
  915. }
  916. // Get session_id from header
  917. const sid = res.headers.get('X-Session-Id');
  918. if (sid && sid !== currentSessionId) {
  919. currentSessionId = sid;
  920. localStorage.setItem('vent_session_id', sid);
  921. loadSessions();
  922. }
  923. // Stream reader
  924. const reader = res.body.getReader();
  925. const decoder = new TextDecoder();
  926. let buffer = '';
  927. let assistantContent = '';
  928. while (true) {
  929. const { done, value } = await reader.read();
  930. if (done) break;
  931. buffer += decoder.decode(value, { stream: true });
  932. // Process complete SSE events
  933. const lines = buffer.split('\n');
  934. buffer = lines.pop() || ''; // keep incomplete line in buffer
  935. for (const line of lines) {
  936. if (!line.startsWith('data: ')) continue;
  937. const json = line.slice(6);
  938. try {
  939. const event = JSON.parse(json);
  940. handleSSEEvent(event);
  941. if (event.type === 'token' && event.content) {
  942. assistantContent += event.content;
  943. }
  944. } catch(e) {
  945. // Skip malformed JSON
  946. }
  947. }
  948. }
  949. // Finalize
  950. if (assistantContent && !currentSessionId) {
  951. // Session was created server-side
  952. loadSessions();
  953. }
  954. } catch(e) {
  955. if (e.name !== 'AbortError') {
  956. showToast(`请求失败: ${e.message}`, 'error');
  957. console.error(e);
  958. }
  959. } finally {
  960. document.getElementById('status-dot').classList.remove('streaming');
  961. document.getElementById('btn-send').disabled = false;
  962. clearStatus();
  963. currentAbortController = null;
  964. }
  965. }
  966. function handleSSEEvent(event) {
  967. switch(event.type) {
  968. case 'thinking':
  969. case 'agent_thinking':
  970. setStatus(event.cn_agent ? `${event.cn_agent}:分析中...` : (event.message || '正在分析...'));
  971. break;
  972. case 'thinking_token':
  973. case 'agent_thinking_token':
  974. if (event.content) appendThinking(event.content);
  975. break;
  976. case 'executing':
  977. case 'agent_executing':
  978. {
  979. const label = event.cn_agent ? `${event.cn_agent}:${event.message}` : event.message;
  980. setStatus(label || '正在执行工具...');
  981. if (event.tools && event.tools.length > 0) {
  982. const cnTools = event.cn_tools || event.tools;
  983. // 翻页模式:仅展示最后一条(最新执行的工具)
  984. const lastIdx = event.tools.length - 1;
  985. addToolCard(event.tools[lastIdx], cnTools[lastIdx], 'pending', event.cn_agent);
  986. }
  987. }
  988. break;
  989. case 'tool_call':
  990. addToolCard(event.tool, event.cn_tool, 'pending', event.cn_agent);
  991. break;
  992. case 'tool_result':
  993. case 'agent_tool_result':
  994. addToolCard(event.tool || '工具', event.cn_tool, 'done', event.cn_agent);
  995. break;
  996. case 'token':
  997. if (event.content) appendToken(event.content);
  998. break;
  999. case 'updated_todo_list':
  1000. case 'agent_todos':
  1001. if (event.todos) {
  1002. // If agent context, show mini todos inside agent card
  1003. if (event.cn_agent) {
  1004. addAgentTodos(event.cn_agent, event.todos);
  1005. }
  1006. updateTodoList(event.todos);
  1007. }
  1008. break;
  1009. case 'progress':
  1010. setStatus(event.message || '处理中...');
  1011. if (event.download_url) {
  1012. pendingDownloadUrl = event.download_url;
  1013. // Immediately show the download button
  1014. const bubble = getOrCreateAssistantMsg();
  1015. // Remove any previous download button
  1016. bubble.querySelectorAll('.download-btn').forEach(el => el.remove());
  1017. bubble.appendChild(createDownloadBtn(event.download_url));
  1018. }
  1019. break;
  1020. case 'agent_start':
  1021. {
  1022. // 在聊天区显示子智能体启动卡片(体现并行感)
  1023. const cn = event.cn_agent || event.agent;
  1024. addAgentCard(cn, 'running');
  1025. setStatus(`${cn} 启动...`);
  1026. }
  1027. break;
  1028. case 'agent_done':
  1029. {
  1030. const cn = event.cn_agent || event.agent;
  1031. addAgentCard(cn, 'done', event.duration_ms, event.progress);
  1032. setStatus(`✅ ${cn} 完成 (${event.progress || ''})`);
  1033. // Agent 结束 → 无论工具处于什么状态,一律翻出清理
  1034. if (agentCards[cn]) {
  1035. const flipper = agentCards[cn].querySelector('.tool-flipper');
  1036. if (flipper) {
  1037. const ct = flipper.querySelector('.current-tool');
  1038. if (ct) {
  1039. if (ct._fadeTimer) { clearTimeout(ct._fadeTimer); ct._fadeTimer = null; }
  1040. ct.getAnimations().forEach(a => a.cancel());
  1041. ct.style.transform = '';
  1042. ct.style.opacity = '';
  1043. ct.className = 'current-tool flip-out';
  1044. }
  1045. }
  1046. }
  1047. }
  1048. break;
  1049. case 'agent_error':
  1050. showToast(event.message || '子智能体出错', 'error');
  1051. break;
  1052. case 'done':
  1053. clearStatus();
  1054. if (event.duration_ms) {
  1055. addDuration(event.duration_ms, '');
  1056. }
  1057. if (event.download_url) {
  1058. pendingDownloadUrl = event.download_url;
  1059. }
  1060. // 最终渲染 markdown(仅更新 .msg-markdown,保留 Agent 卡片和工具卡片)
  1061. {
  1062. const bubble = getOrCreateAssistantMsg();
  1063. if (bubble) {
  1064. const md = bubble.querySelector('.msg-markdown');
  1065. if (md) {
  1066. const raw = md.getAttribute('data-raw');
  1067. if (raw) {
  1068. md.innerHTML = renderMarkdown(raw);
  1069. md.removeAttribute('data-raw');
  1070. }
  1071. }
  1072. // 兜底清理:所有 Agent 卡内残留的工具翻页
  1073. bubble.querySelectorAll('.tool-flipper .current-tool').forEach(ct => {
  1074. if (ct._fadeTimer) { clearTimeout(ct._fadeTimer); ct._fadeTimer = null; }
  1075. ct.getAnimations().forEach(a => a.cancel());
  1076. ct.style.transform = '';
  1077. ct.style.opacity = '';
  1078. ct.className = 'current-tool flip-out';
  1079. });
  1080. if (pendingDownloadUrl) {
  1081. bubble.querySelectorAll('.download-btn').forEach(el => el.remove());
  1082. bubble.appendChild(createDownloadBtn(pendingDownloadUrl));
  1083. }
  1084. }
  1085. }
  1086. activeThinkBlock = null;
  1087. loadSessions();
  1088. break;
  1089. case 'error':
  1090. showToast(event.message || '出错了', 'error');
  1091. clearStatus();
  1092. break;
  1093. case 'generating':
  1094. setStatus('正在生成报告...');
  1095. break;
  1096. }
  1097. }
  1098. function abortStream() {
  1099. if (currentAbortController) {
  1100. currentAbortController.abort();
  1101. currentAbortController = null;
  1102. }
  1103. document.getElementById('status-dot').classList.remove('streaming');
  1104. document.getElementById('btn-send').disabled = false;
  1105. clearStatus();
  1106. }
  1107. // ============================================================
  1108. // Helpers
  1109. // ============================================================
  1110. function escHtml(s) {
  1111. if (!s) return '';
  1112. return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  1113. }
  1114. function scrollToBottom() {
  1115. requestAnimationFrame(() => {
  1116. const msgs = document.getElementById('messages');
  1117. msgs.scrollTop = msgs.scrollHeight;
  1118. });
  1119. }
  1120. function onInputKey(e) {
  1121. if (e.key === 'Enter' && !e.shiftKey) {
  1122. e.preventDefault();
  1123. sendMessage();
  1124. }
  1125. }
  1126. function onFileSelected(input) {
  1127. const btn = document.getElementById('btn-attach');
  1128. if (input.files.length) {
  1129. btn.classList.add('has-file');
  1130. btn.title = input.files[0].name;
  1131. } else {
  1132. btn.classList.remove('has-file');
  1133. btn.title = '上传附件';
  1134. }
  1135. }
  1136. function showToast(msg, type) {
  1137. const container = document.getElementById('toast-container');
  1138. const el = document.createElement('div');
  1139. el.className = `toast ${type}`;
  1140. el.textContent = msg;
  1141. container.appendChild(el);
  1142. setTimeout(() => { el.remove(); }, 4000);
  1143. }
  1144. function createDownloadBtn(url) {
  1145. const btn = document.createElement('a');
  1146. btn.className = 'download-btn';
  1147. btn.href = url;
  1148. btn.target = '_blank';
  1149. btn.rel = 'noopener';
  1150. btn.innerHTML = '<span class="dl-icon">📥</span> 下载审查报告 (Word)';
  1151. return btn;
  1152. }
  1153. // Auto-resize textarea
  1154. document.addEventListener('DOMContentLoaded', () => {
  1155. const input = document.getElementById('input');
  1156. input.addEventListener('input', () => {
  1157. input.style.height = 'auto';
  1158. input.style.height = Math.min(input.scrollHeight, 150) + 'px';
  1159. });
  1160. });
  1161. </script>
  1162. </body>
  1163. </html>