index.html 82 KB

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