| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069 |
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>煤矿通风智能解读系统</title>
- <style>
- /* ============================================================
- CSS Variables & Reset — Zcode/Codex Dark Theme
- ============================================================ */
- :root {
- --bg-primary: #1e1e2e;
- --bg-secondary: #181825;
- --bg-tertiary: #11111b;
- --bg-surface: #242438;
- --bg-hover: #2a2a40;
- --border: #313244;
- --text-primary: #cdd6f4;
- --text-secondary: #a6adc8;
- --text-muted: #6c7086;
- --accent: #89b4fa;
- --accent-dim: #74a0e0;
- --green: #a6e3a1;
- --yellow: #f9e2af;
- --red: #f38ba8;
- --orange: #fab387;
- --purple: #cba6f7;
- --font-mono: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace;
- --font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
- --radius: 8px;
- --radius-sm: 4px;
- }
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
- html, body { height: 100%; overflow: hidden; }
- body {
- font-family: var(--font-sans);
- font-size: 14px;
- background: var(--bg-primary);
- color: var(--text-primary);
- display: flex; flex-direction: column;
- }
- /* ============================================================
- Layout
- ============================================================ */
- .app { display: flex; height: 100vh; overflow: hidden; }
- /* Sidebar — Session List */
- .sidebar {
- width: 260px; min-width: 260px;
- background: var(--bg-secondary);
- border-right: 1px solid var(--border);
- display: flex; flex-direction: column;
- overflow: hidden;
- }
- .sidebar-header {
- padding: 16px; border-bottom: 1px solid var(--border);
- display: flex; align-items: center; justify-content: space-between;
- }
- .sidebar-header h2 { font-size: 15px; font-weight: 600; color: var(--accent); }
- .btn-new {
- width: 32px; height: 32px; border-radius: var(--radius-sm);
- background: var(--accent); color: var(--bg-tertiary); border: none;
- font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center;
- transition: background .15s;
- }
- .btn-new:hover { background: var(--accent-dim); }
- .session-list {
- flex: 1; overflow-y: auto; padding: 8px;
- }
- .session-item {
- padding: 10px 12px; border-radius: var(--radius-sm);
- cursor: pointer; margin-bottom: 4px; font-size: 13px;
- display: flex; align-items: center; justify-content: space-between;
- color: var(--text-secondary); transition: background .1s;
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- }
- .session-item:hover { background: var(--bg-hover); }
- .session-item.active { background: var(--bg-surface); color: var(--text-primary); }
- .session-item .title { flex: 1; overflow: hidden; text-overflow: ellipsis; }
- .session-item .count { font-size: 11px; color: var(--text-muted); margin-left: 8px; }
- .btn-delete {
- background: none; border: none; color: var(--text-muted); cursor: pointer;
- font-size: 16px; padding: 0 4px; opacity: 0; transition: opacity .1s;
- }
- .session-item:hover .btn-delete { opacity: 1; }
- .btn-delete:hover { color: var(--red); }
- .btn-pin {
- background: none; border: none; color: var(--text-muted); cursor: pointer;
- font-size: 13px; padding: 0 2px; opacity: 0; transition: opacity .1s, color .15s;
- }
- .session-item:hover .btn-pin { opacity: 1; }
- .btn-pin:hover { color: var(--yellow); }
- .btn-pin.pinned { opacity: 1; color: var(--yellow); }
- /* Main Chat Area */
- .main {
- flex: 1; display: flex; flex-direction: column;
- min-width: 0; background: var(--bg-primary);
- }
- .chat-header {
- padding: 12px 20px; border-bottom: 1px solid var(--border);
- font-size: 14px; font-weight: 600; color: var(--text-secondary);
- display: flex; align-items: center; gap: 8px;
- }
- .chat-header .status-dot {
- width: 8px; height: 8px; border-radius: 50%; background: var(--green);
- }
- .chat-header .status-dot.streaming { background: var(--yellow); animation: pulse 1s infinite; }
- @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.3} }
- .messages {
- flex: 1; overflow-y: auto; padding: 20px;
- display: flex; flex-direction: column; gap: 16px;
- }
- /* Message bubbles */
- .msg { max-width: 85%; animation: fadeIn .2s ease; }
- @keyframes fadeIn { from{opacity:0;transform:translateY(4px)} to{opacity:1;transform:translateY(0)} }
- .msg.user { align-self: flex-end; }
- .msg.assistant { align-self: flex-start; }
- .msg .role {
- font-size: 11px; font-weight: 600; text-transform: uppercase;
- margin-bottom: 4px; color: var(--text-muted);
- }
- .msg.user .role { text-align: right; }
- .msg .bubble {
- padding: 12px 16px; border-radius: var(--radius); line-height: 1.6;
- word-break: break-word;
- }
- .msg.user .bubble { background: var(--bg-surface); border: 1px solid var(--border); }
- .msg.assistant .bubble { background: transparent; padding: 0; }
- /* Markdown inside assistant bubble */
- .msg.assistant .bubble h1,.msg.assistant .bubble h2,.msg.assistant .bubble h3 {
- margin: 16px 0 8px; font-weight: 600; color: var(--accent);
- }
- .msg.assistant .bubble h1 { font-size: 1.3em; }
- .msg.assistant .bubble h2 { font-size: 1.15em; }
- .msg.assistant .bubble h3 { font-size: 1em; }
- .msg.assistant .bubble h4 { font-size: 0.95em; font-weight: 600; margin: 12px 0 6px; }
- .msg.assistant .bubble h5 { font-size: 0.9em; font-weight: 600; margin: 10px 0 4px; color: var(--text-secondary); }
- .msg.assistant .bubble h6 { font-size: 0.85em; font-weight: 600; margin: 8px 0 4px; color: var(--text-muted); }
- .msg.assistant .bubble p { margin: 4px 0; }
- .msg.assistant .bubble ul,.msg.assistant .bubble ol { padding-left: 20px; margin: 8px 0; }
- .msg.assistant .bubble li { margin: 2px 0; }
- .msg.assistant .bubble code {
- font-family: var(--font-mono); font-size: 0.9em;
- background: var(--bg-tertiary); padding: 2px 6px; border-radius: var(--radius-sm);
- }
- .msg.assistant .bubble pre {
- background: var(--bg-tertiary); border: 1px solid var(--border);
- border-radius: var(--radius); padding: 12px 16px; overflow-x: auto;
- margin: 8px 0; font-size: 13px; line-height: 1.5;
- }
- .msg.assistant .bubble pre code { background: none; padding: 0; }
- .msg.assistant .bubble table {
- border-collapse: collapse; width: 100%; margin: 8px 0; font-size: 13px;
- }
- .msg.assistant .bubble th,.msg.assistant .bubble td {
- border: 1px solid var(--border); padding: 6px 10px; text-align: left;
- }
- .msg.assistant .bubble th { background: var(--bg-surface); font-weight: 600; }
- .msg.assistant .bubble strong { color: var(--yellow); }
- .msg.assistant .bubble blockquote {
- border-left: 3px solid var(--accent); padding-left: 12px;
- color: var(--text-secondary); margin: 8px 0;
- }
- /* Thinking block */
- .think-block {
- margin: 8px 0; border: 1px solid var(--border);
- border-radius: var(--radius); overflow: hidden;
- background: var(--bg-surface);
- }
- .think-block summary {
- padding: 8px 12px; cursor: pointer; font-size: 12px;
- color: var(--text-muted); background: var(--bg-tertiary);
- user-select: none; display: flex; align-items: center; gap: 6px;
- transition: color .15s;
- }
- .think-block summary:hover { color: var(--accent); }
- .think-block summary::marker { font-size: 10px; }
- .think-block .think-content {
- padding: 10px 14px; font-size: 12px; color: var(--text-muted);
- line-height: 1.6; max-height: 300px; overflow-y: auto;
- font-family: var(--font-sans); white-space: pre-wrap;
- border-top: 1px solid var(--border);
- background: var(--bg-surface);
- }
- .think-block summary .think-icon { animation: spin 2s linear infinite; display: inline-block; }
- .think-block[open] summary .think-icon { animation: none; }
- /* Duration badge */
- .msg-duration {
- font-size: 11px; color: var(--text-muted); margin-top: 4px;
- display: flex; align-items: center; gap: 4px;
- }
- /* Agent card — container for sub-agent tools + progress */
- .agent-card {
- margin: 6px 0; border: 1px solid var(--border);
- border-radius: var(--radius); overflow: hidden;
- background: var(--bg-surface); font-size: 12px;
- border-left: 3px solid var(--accent);
- transition: border-color .3s;
- }
- .agent-card.running { border-left-color: var(--yellow); }
- .agent-card.done { border-left-color: var(--green); }
- .agent-card.error { border-left-color: var(--red); }
- .agent-card .agent-header {
- display: flex; align-items: center; gap: 8px;
- padding: 8px 12px; background: var(--bg-tertiary);
- }
- .agent-card .agent-icon {
- width: 16px; height: 16px; flex-shrink: 0;
- display: inline-flex; align-items: center; justify-content: center;
- font-size: 12px; line-height: 1;
- }
- /* 运行中:环形旋转 spinner */
- .agent-card.running .agent-icon {
- width: 14px; height: 14px;
- border: 2px solid var(--border);
- border-top-color: var(--yellow);
- border-radius: 50%;
- animation: spin 0.8s linear infinite;
- font-size: 0;
- }
- /* 完成/错误:emoji 居中 */
- .agent-card.done .agent-icon,
- .agent-card.error .agent-icon {
- border: none; width: 16px; height: 16px;
- animation: none; font-size: 12px;
- }
- .agent-card .agent-name { color: var(--text-secondary); flex: 1; font-weight: 500; }
- .agent-card .agent-status { font-size: 11px; color: var(--text-muted); }
- .agent-card .agent-body {
- padding: 2px 0;
- max-height: 250px; overflow-y: auto;
- }
- /* ── 工具翻页动画(仅显示当前正在执行的一个工具)── */
- .agent-body .tool-flipper {
- perspective: 600px;
- min-height: 30px;
- overflow: hidden;
- }
- .agent-body .current-tool {
- padding: 5px 12px; font-size: 11px;
- display: flex; align-items: center; gap: 6px;
- color: var(--text-muted);
- transform-origin: center center;
- backface-visibility: hidden;
- }
- .agent-body .current-tool.flip-out {
- animation: toolFlipOut 0.28s ease forwards;
- pointer-events: none;
- }
- .agent-body .current-tool.flip-in {
- animation: toolFlipIn 0.32s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
- }
- @keyframes toolFlipIn {
- from { transform: rotateX(100deg); opacity: 0; }
- to { transform: rotateX(0deg); opacity: 1; }
- }
- @keyframes toolFlipOut {
- from { transform: rotateX(0deg); opacity: 1; }
- to { transform: rotateX(-100deg); opacity: 0; }
- }
- .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; }
- .agent-body .current-tool .mt-name { flex: 1; color: var(--yellow); }
- .agent-body .current-tool.done .mt-name { color: var(--text-secondary); }
- /* 工具执行中的环形旋转 spinner */
- .spin-icon-sm {
- display: inline-block;
- width: 10px; height: 10px;
- border: 2px solid var(--border);
- border-top-color: var(--yellow);
- border-radius: 50%;
- animation: spin 0.7s linear infinite;
- flex-shrink: 0;
- vertical-align: middle;
- }
- /* Nested mini todo inside agent body */
- .agent-body .mini-todo {
- display: flex; align-items: center; gap: 4px;
- padding: 3px 12px; font-size: 11px; color: var(--text-muted);
- border-bottom: 1px solid var(--border);
- }
- .agent-body .mini-todo .mt-check {
- width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0;
- border: 2px solid var(--border);
- }
- .agent-body .mini-todo.completed .mt-check { background: var(--green); border-color: var(--green); }
- .agent-body .mini-todo.in_progress .mt-check { border-color: var(--yellow); background: var(--yellow); }
- .agent-body .mini-todo .mt-label { flex: 1; font-size: 11px; }
- .agent-body .mini-todo.completed .mt-label { text-decoration: line-through; }
- /* Tool call card (standalone, outside agent) */
- .tool-card {
- margin: 6px 0; padding: 8px 12px; border-radius: var(--radius-sm);
- background: var(--bg-surface); border-left: 3px solid var(--accent);
- font-size: 12px; display: flex; align-items: center; gap: 8px;
- }
- .tool-card.pending { border-left-color: var(--yellow); }
- .tool-card.done { border-left-color: var(--green); }
- .tool-card .tool-icon { font-size: 14px; }
- .tool-card .tool-name { color: var(--text-secondary); flex: 1; }
- .tool-card .tool-status { font-size: 11px; color: var(--text-muted); }
- /* Status bar (agent thinking/executing) */
- .status-bar {
- padding: 6px 16px; font-size: 12px; color: var(--text-muted);
- border-top: 1px solid var(--border); display: flex; align-items: center; gap: 8px;
- min-height: 32px;
- }
- .status-bar .spinner {
- width: 12px; height: 12px; border: 2px solid var(--border);
- border-top-color: var(--accent); border-radius: 50%; animation: spin .6s linear infinite;
- }
- @keyframes spin { to{transform:rotate(360deg)} }
- /* Input area */
- .input-area {
- padding: 12px 20px; border-top: 1px solid var(--border);
- display: flex; gap: 10px; align-items: center;
- }
- .input-area textarea {
- flex: 1; background: var(--bg-surface); border: 1px solid var(--border);
- border-radius: var(--radius); color: var(--text-primary); padding: 10px 14px;
- font-family: var(--font-sans); font-size: 14px; resize: none; outline: none;
- min-height: 44px; max-height: 150px; line-height: 1.4;
- transition: border-color .15s;
- }
- .input-area textarea:focus { border-color: var(--accent); }
- .btn-send {
- width: 44px; height: 44px; border-radius: var(--radius);
- background: var(--accent); color: var(--bg-tertiary); border: none;
- font-size: 18px; cursor: pointer; transition: background .15s;
- display: flex; align-items: center; justify-content: center; flex-shrink: 0;
- }
- .btn-send:hover { background: var(--accent-dim); }
- .btn-send:disabled { background: var(--border); cursor: not-allowed; }
- .btn-attach {
- width: 44px; height: 44px; border-radius: var(--radius);
- background: var(--bg-surface); border: 1px solid var(--border);
- color: var(--text-secondary); font-size: 18px; cursor: pointer;
- display: flex; align-items: center; justify-content: center; flex-shrink: 0;
- transition: background .1s, border-color .1s;
- }
- .btn-attach:hover { border-color: var(--accent); color: var(--accent); }
- .btn-attach.has-file { border-color: var(--green); color: var(--green); }
- #file-input { display: none; }
- /* Detail Panel (right) */
- .detail-panel {
- width: 280px; min-width: 280px;
- background: var(--bg-secondary); border-left: 1px solid var(--border);
- display: flex; flex-direction: column; overflow: hidden;
- }
- .detail-panel h3 {
- padding: 16px; font-size: 13px; font-weight: 600;
- color: var(--text-muted); text-transform: uppercase;
- letter-spacing: 0.5px; border-bottom: 1px solid var(--border);
- }
- .detail-content { flex: 1; overflow-y: auto; padding: 12px; }
- .detail-content .section { margin-bottom: 16px; }
- .detail-content .section-title {
- font-size: 11px; font-weight: 600; color: var(--text-muted);
- text-transform: uppercase; margin-bottom: 8px;
- }
- .todo-item {
- display: flex; align-items: center; gap: 8px; padding: 4px 0; font-size: 12px;
- }
- .todo-item .todo-check {
- width: 14px; height: 14px; border-radius: 50%;
- border: 2px solid var(--border); flex-shrink: 0;
- }
- .todo-item.completed .todo-check { background: var(--green); border-color: var(--green); }
- .todo-item.in_progress .todo-check { border-color: var(--yellow); background: var(--yellow); }
- .todo-item .todo-label { color: var(--text-secondary); }
- .todo-item.completed .todo-label { text-decoration: line-through; color: var(--text-muted); }
- .tool-log-item {
- font-size: 11px; padding: 4px 0; color: var(--text-muted);
- border-bottom: 1px solid var(--border); display: flex; gap: 6px;
- }
- .tool-log-item .tl-icon { flex-shrink: 0; }
- .tool-log-item .tl-name { color: var(--text-secondary); }
- /* Toast */
- .toast {
- position: fixed; top: 16px; right: 16px; padding: 10px 16px;
- border-radius: var(--radius); font-size: 13px; z-index: 1000;
- animation: slideIn .2s ease; max-width: 400px;
- }
- .toast.error { background: var(--red); color: #fff; }
- .toast.info { background: var(--accent); color: var(--bg-tertiary); }
- @keyframes slideIn { from{transform:translateX(100%)} to{transform:translateX(0)} }
- /* Download Button */
- .download-btn {
- display: inline-flex; align-items: center; gap: 8px;
- padding: 10px 20px; margin: 12px 0;
- background: var(--green); color: var(--bg-tertiary);
- border: none; border-radius: var(--radius);
- font-size: 14px; font-weight: 600; cursor: pointer;
- text-decoration: none; transition: background .15s, transform .1s;
- }
- .download-btn:hover { background: #8fd98f; transform: translateY(-1px); }
- .download-btn:active { transform: translateY(0); }
- .download-btn .dl-icon { font-size: 18px; }
- /* Empty state */
- .empty-state {
- flex: 1; display: flex; flex-direction: column; align-items: center;
- justify-content: center; color: var(--text-muted); gap: 12px;
- }
- .empty-state .big-icon { font-size: 48px; opacity: .3; }
- /* Scrollbar */
- ::-webkit-scrollbar { width: 6px; }
- ::-webkit-scrollbar-track { background: transparent; }
- ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
- ::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
- /* Responsive: hide detail panel on small screens */
- @media (max-width: 1000px) { .detail-panel { display: none; } }
- @media (max-width: 700px) { .sidebar { display: none; } }
- /* ============================================================
- Model Selector — dropdown in chat header
- ============================================================ */
- .model-selector {
- position: relative; margin-left: auto; font-size: 12px;
- user-select: none; z-index: 100;
- }
- .model-selector .current {
- display: flex; align-items: center; gap: 6px;
- padding: 5px 10px; border-radius: var(--radius-sm);
- background: var(--bg-surface); border: 1px solid var(--border);
- cursor: pointer; color: var(--text-secondary);
- transition: border-color .15s, background .15s;
- white-space: nowrap;
- }
- .model-selector .current:hover {
- border-color: var(--accent); background: var(--bg-hover);
- }
- .model-selector .current .model-icon { font-size: 13px; }
- .model-selector .current .model-name { font-weight: 500; }
- .model-selector .current .model-arrow {
- font-size: 9px; color: var(--text-muted); transition: transform .2s;
- }
- .model-selector.open .current .model-arrow { transform: rotate(180deg); }
- .model-selector .dropdown {
- position: absolute; top: calc(100% + 4px); right: 0;
- min-width: 200px; background: var(--bg-secondary);
- border: 1px solid var(--border); border-radius: var(--radius);
- box-shadow: 0 8px 24px rgba(0,0,0,.4); overflow: hidden;
- animation: dropdownIn .15s ease;
- }
- @keyframes dropdownIn { from{opacity:0;transform:translateY(-4px)} to{opacity:1;transform:translateY(0)} }
- .model-selector .dropdown .model-option {
- display: flex; align-items: center; gap: 8px;
- padding: 9px 14px; cursor: pointer; color: var(--text-secondary);
- transition: background .1s; border-bottom: 1px solid var(--border);
- }
- .model-selector .dropdown .model-option:last-child { border-bottom: none; }
- .model-selector .dropdown .model-option:hover { background: var(--bg-hover); }
- .model-selector .dropdown .model-option.active { color: var(--accent); background: var(--bg-surface); }
- .model-selector .dropdown .model-option .opt-tag {
- font-size: 10px; padding: 2px 6px; border-radius: 3px;
- font-weight: 600; text-transform: uppercase; flex-shrink: 0;
- }
- .model-selector .dropdown .model-option .opt-tag.pro { background: rgba(203,166,247,.2); color: var(--purple); }
- .model-selector .dropdown .model-option .opt-tag.flash { background: rgba(166,227,161,.2); color: var(--green); }
- .model-selector .dropdown .model-option .opt-name { flex: 1; }
- .model-selector .dropdown .model-option .opt-check { color: var(--accent); font-size: 12px; }
- /* Thinking Level Toggle — button group */
- .thinking-toggle {
- display: flex; align-items: center; gap: 2px;
- background: var(--bg-surface); border: 1px solid var(--border);
- border-radius: var(--radius-sm); padding: 2px;
- font-size: 11px; user-select: none;
- }
- .thinking-toggle .thinking-label {
- padding: 0 6px; color: var(--text-muted); font-size: 12px;
- }
- .thinking-toggle button {
- padding: 3px 8px; border: none; border-radius: 3px;
- background: transparent; color: var(--text-muted);
- font-family: var(--font-sans); font-size: 11px; cursor: pointer;
- transition: background .12s, color .12s;
- }
- .thinking-toggle button:hover { color: var(--text-primary); }
- .thinking-toggle button.active {
- background: var(--accent); color: var(--bg-tertiary); font-weight: 600;
- }
- /* ============================================================
- Skill Manager Modal
- ============================================================ */
- .modal-overlay {
- position: fixed; inset: 0; z-index: 2000;
- background: rgba(0,0,0,.6); display: flex; align-items: center; justify-content: center;
- animation: fadeIn .15s ease;
- }
- .modal {
- background: var(--bg-secondary); border: 1px solid var(--border);
- border-radius: var(--radius); width: 720px; max-width: 95vw;
- max-height: 82vh; display: flex; flex-direction: column;
- box-shadow: 0 16px 48px rgba(0,0,0,.5);
- }
- .modal-header {
- display: flex; align-items: center; justify-content: space-between;
- padding: 14px 18px; border-bottom: 1px solid var(--border);
- }
- .modal-header h3 { font-size: 15px; font-weight: 600; color: var(--accent); }
- .modal-header .modal-actions { display: flex; gap: 8px; }
- .modal-body {
- flex: 1; overflow-y: auto; padding: 16px 18px;
- }
- .modal-body .skill-table { width: 100%; border-collapse: collapse; font-size: 12px; }
- .modal-body .skill-table th, .modal-body .skill-table td {
- padding: 8px 10px; text-align: left; border-bottom: 1px solid var(--border);
- vertical-align: middle;
- }
- .modal-body .skill-table th { color: var(--text-muted); font-weight: 600; font-size: 11px; text-transform: uppercase; }
- .modal-body .skill-table td { color: var(--text-secondary); }
- .modal-body .skill-table .skill-desc { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .modal-body .skill-table .skill-agents { font-size: 10px; color: var(--text-muted); }
- .modal-body .skill-table .skill-name { color: var(--accent); font-weight: 500; cursor: pointer; }
- .modal-body .skill-table .skill-name:hover { text-decoration: underline; }
- .modal-body .status-badge {
- display: inline-block; padding: 2px 8px; border-radius: 3px;
- font-size: 10px; font-weight: 600; text-transform: uppercase;
- }
- .modal-body .status-badge.enabled { background: rgba(166,227,161,.2); color: var(--green); }
- .modal-body .status-badge.disabled { background: rgba(243,139,168,.2); color: var(--red); }
- .modal-body .skill-detail {
- margin-top: 12px; border: 1px solid var(--border); border-radius: var(--radius);
- background: var(--bg-surface); padding: 14px 18px; font-size: 12px;
- max-height: 300px; overflow-y: auto; line-height: 1.6;
- display: none;
- }
- .modal-body .skill-detail h1,.modal-body .skill-detail h2,.modal-body .skill-detail h3 { color: var(--accent); margin: 12px 0 6px; }
- .modal-body .skill-detail code {
- font-family: var(--font-mono); background: var(--bg-tertiary); padding: 1px 5px; border-radius: 3px; font-size: 11px;
- }
- .upload-zone {
- margin-top: 12px; border: 2px dashed var(--border); border-radius: var(--radius);
- padding: 20px; text-align: center; color: var(--text-muted); font-size: 12px;
- cursor: pointer; transition: border-color .15s, background .15s;
- }
- .upload-zone:hover { border-color: var(--accent); background: var(--bg-surface); }
- .upload-zone.dragover { border-color: var(--green); background: rgba(166,227,161,.05); }
- .upload-zone input[type="file"] { display: none; }
- /* ============================================================
- Mode Selector — permission mode dropdown
- ============================================================ */
- .mode-selector {
- position: relative; font-size: 11px; user-select: none; z-index: 99;
- }
- .mode-selector .mode-current {
- display: flex; align-items: center; gap: 5px;
- padding: 4px 8px; border-radius: var(--radius-sm);
- background: var(--bg-surface); border: 1px solid var(--border);
- cursor: pointer; color: var(--text-secondary); white-space: nowrap;
- transition: border-color .15s, background .15s;
- }
- .mode-selector .mode-current:hover { border-color: var(--accent); }
- .mode-selector .mode-dot {
- width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0;
- }
- .mode-selector .mode-dot.plan { background: var(--purple); }
- .mode-selector .mode-dot.full { background: var(--red); }
- .mode-selector .mode-dropdown {
- display: none; position: absolute; top: calc(100% + 4px); right: 0;
- min-width: 180px; background: var(--bg-secondary);
- border: 1px solid var(--border); border-radius: var(--radius);
- box-shadow: 0 8px 24px rgba(0,0,0,.4); overflow: hidden;
- animation: dropdownIn .15s ease;
- }
- .mode-selector.open .mode-dropdown { display: block; }
- .mode-selector .mode-option {
- display: flex; align-items: center; gap: 8px;
- padding: 9px 14px; cursor: pointer; color: var(--text-secondary);
- transition: background .1s; border-bottom: 1px solid var(--border);
- font-size: 12px;
- }
- .mode-selector .mode-option:last-child { border-bottom: none; }
- .mode-selector .mode-option:hover { background: var(--bg-hover); }
- .mode-selector .mode-option.active { color: var(--accent); background: var(--bg-surface); }
- .mode-selector .mode-option .mode-opt-name { flex: 1; font-weight: 500; }
- .mode-selector .mode-option .mode-opt-desc { font-size: 10px; color: var(--text-muted); }
- .mode-selector .mode-option .mode-opt-check { color: var(--accent); font-size: 11px; }
- /* Interrupt approval card */
- .interrupt-card {
- margin: 8px 0; padding: 12px 16px; border-radius: var(--radius);
- border: 1px solid var(--yellow); background: rgba(249,226,175,.06);
- display: flex; align-items: center; gap: 12px; font-size: 12px;
- }
- .interrupt-card .interrupt-msg { flex: 1; color: var(--yellow); }
- .interrupt-card button {
- padding: 5px 14px; border-radius: var(--radius-sm);
- border: none; font-size: 12px; cursor: pointer; font-weight: 500;
- transition: background .15s;
- }
- .interrupt-card .btn-approve { background: var(--green); color: var(--bg-tertiary); }
- .interrupt-card .btn-approve:hover { background: #8fd98f; }
- .interrupt-card .btn-reject { background: var(--red); color: #fff; }
- .interrupt-card .btn-reject:hover { background: #e06c80; }
- /* ============================================================
- Context Capacity Meter — detail panel
- ============================================================ */
- .context-meter { margin-bottom: 12px; }
- .context-meter .cm-header {
- display: flex; align-items: center; justify-content: space-between;
- margin-bottom: 4px; font-size: 11px;
- }
- .context-meter .cm-header .cm-label { color: var(--text-muted); text-transform: uppercase; font-weight: 600; }
- .context-meter .cm-header .cm-value { color: var(--text-secondary); font-weight: 500; }
- .context-meter .cm-bar-outer {
- height: 6px; background: var(--bg-tertiary); border-radius: 3px; overflow: hidden; margin-bottom: 8px;
- }
- .context-meter .cm-bar-inner {
- height: 100%; border-radius: 3px; transition: width .4s ease, background .4s ease;
- }
- .context-meter .cm-bar-inner.low { background: var(--green); }
- .context-meter .cm-bar-inner.medium { background: var(--yellow); }
- .context-meter .cm-bar-inner.high { background: var(--orange); }
- .context-meter .cm-bar-inner.crit { background: var(--red); }
- .context-meter .cm-breakdown {
- display: grid; grid-template-columns: 1fr 1fr; gap: 2px 12px; font-size: 10px;
- }
- .context-meter .cm-breakdown .cm-item {
- display: flex; justify-content: space-between; color: var(--text-muted);
- }
- .context-meter .cm-breakdown .cm-item .cm-cat { flex: 1; }
- .context-meter .cm-breakdown .cm-item .cm-num { font-weight: 500; color: var(--text-secondary); }
- .context-meter .cm-empty {
- font-size: 10px; color: var(--text-muted); text-align: center; padding: 8px 0;
- }
- </style>
- </head>
- <body>
- <div class="app">
- <!-- ============ Sidebar: Session List ============ -->
- <aside class="sidebar">
- <div class="sidebar-header">
- <h2>💨 通风智能助手</h2>
- <div style="display:flex;gap:6px;">
- <button class="btn-new" onclick="openSkillManager()" title="技能管理" style="font-size:14px;">📋</button>
- <button class="btn-new" onclick="newSession()" title="新建会话">+</button>
- </div>
- </div>
- <div class="session-list" id="session-list"></div>
- </aside>
- <!-- ============ Main Chat Area ============ -->
- <main class="main">
- <div class="chat-header">
- <span class="status-dot" id="status-dot"></span>
- <span id="chat-title">新会话</span>
- <!-- Model Selector -->
- <div class="model-selector" id="model-selector">
- <div class="current" onclick="toggleModelDropdown()">
- <span class="model-icon">🧠</span>
- <span class="model-name" id="current-model-label">deepseek-v4-pro</span>
- <span class="model-arrow">▼</span>
- </div>
- <div class="dropdown" id="model-dropdown" style="display:none"></div>
- </div>
- <!-- Thinking Level Toggle -->
- <div class="thinking-toggle" id="thinking-toggle">
- <span class="thinking-label">💭</span>
- <button data-level="off" class="active" onclick="switchThinking('off')">关闭</button>
- <button data-level="high" onclick="switchThinking('high')">高</button>
- <button data-level="highest" onclick="switchThinking('highest')">最高</button>
- </div>
- <!-- Mode Selector -->
- <div class="mode-selector" id="mode-selector">
- <div class="mode-current" onclick="toggleModeDropdown()">
- <span class="mode-dot plan" id="mode-dot"></span>
- <span id="mode-label">计划模式</span>
- <span style="font-size:9px;color:var(--text-muted)">▼</span>
- </div>
- <div class="mode-dropdown" id="mode-dropdown"></div>
- </div>
- </div>
- <div class="messages" id="messages">
- <div class="empty-state">
- <div class="big-icon">⛏️</div>
- <div>煤矿通风数据智能解读系统</div>
- <div style="font-size:12px">输入问题或上传配风计划 PDF 开始分析</div>
- </div>
- </div>
- <div class="status-bar" id="status-bar"></div>
- <div class="input-area">
- <button class="btn-attach" id="btn-attach" onclick="document.getElementById('file-input').click()" title="上传附件">📎</button>
- <input type="file" id="file-input" accept=".pdf,.doc,.docx,.txt" onchange="onFileSelected(this)">
- <textarea id="input" placeholder="输入您的问题..." rows="1" onkeydown="onInputKey(event)"></textarea>
- <button class="btn-send" id="btn-send" onclick="sendMessage()" title="发送">↑</button>
- </div>
- </main>
- <!-- ============ Detail Panel ============ -->
- <aside class="detail-panel" id="detail-panel">
- <h3>📋 任务详情</h3>
- <div class="detail-content" id="detail-content">
- <div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">
- 发送消息后<br>此处显示任务进度和工具调用
- </div>
- </div>
- </aside>
- </div>
- <!-- Toast container -->
- <div id="toast-container"></div>
- <!-- ============ Skill Manager Modal ============ -->
- <div class="modal-overlay" id="skill-modal" style="display:none;" onclick="if(event.target===this) closeSkillModal()">
- <div class="modal">
- <div class="modal-header">
- <h3>📋 技能管理</h3>
- <div class="modal-actions">
- <button class="btn-send" onclick="document.getElementById('skill-upload-input').click()" style="width:auto;padding:6px 14px;font-size:12px;">📤 上传技能</button>
- <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>
- </div>
- </div>
- <div class="modal-body" id="skill-modal-body">
- <div style="text-align:center;color:var(--text-muted);padding:40px;">加载中...</div>
- </div>
- <!-- Hidden upload input -->
- <input type="file" id="skill-upload-input" accept=".zip" onchange="uploadSkill(this)" style="display:none;">
- </div>
- </div>
- <script>
- // ============================================================
- // State
- // ============================================================
- const API = '/api';
- let currentSessionId = localStorage.getItem('vent_session_id') || null;
- let currentAbortController = null;
- let todoItems = [];
- let toolLogs = [];
- let activeThinkBlock = null;
- let pendingDownloadUrl = null;
- // ── 认证令牌 ──
- // 支持从 localStorage(key: x-access-token)或 URL 参数获取
- function getAccessToken() {
- const fromStorage = localStorage.getItem('x-access-token');
- if (fromStorage) return fromStorage;
- const params = new URLSearchParams(window.location.search);
- return params.get('token') || '';
- }
- function authHeaders(extra = {}) {
- const token = getAccessToken();
- const headers = { ...extra };
- if (token) headers['x-access-token'] = token;
- return headers;
- }
- // ============================================================
- // Init
- // ============================================================
- document.addEventListener('DOMContentLoaded', () => {
- loadSessions();
- if (currentSessionId) loadHistory(currentSessionId);
- fetchModels();
- if (currentSessionId) fetchSessionMode();
- });
- // ============================================================
- // Model Switching
- // ============================================================
- const MODEL_TAGS = {
- 'deepseek-v4-pro': { tag: 'PRO', cls: 'pro', desc: '深度推理 · 高精度' },
- 'deepseek-v4-flash': { tag: 'FLASH', cls: 'flash', desc: '快速响应 · 低延迟' },
- };
- async function fetchModels() {
- try {
- const res = await fetch(`${API}/model`);
- const data = await res.json();
- const current = data.current || 'deepseek-v4-pro';
- const available = data.available || ['deepseek-v4-pro', 'deepseek-v4-flash'];
- const thinkLevel = data.thinking_level || 'off';
- // Update current display
- document.getElementById('current-model-label').textContent = current;
- // Update thinking toggle buttons
- document.querySelectorAll('#thinking-toggle button').forEach(btn => {
- btn.classList.toggle('active', btn.dataset.level === thinkLevel);
- });
- // Render dropdown options
- const dropdown = document.getElementById('model-dropdown');
- dropdown.innerHTML = available.map(m => {
- const info = MODEL_TAGS[m] || { tag: m, cls: '', desc: '' };
- const isActive = m === current;
- return `<div class="model-option${isActive ? ' active' : ''}" onclick="switchModel('${m}')">
- <span class="opt-tag ${info.cls}">${info.tag}</span>
- <span class="opt-name">${m}</span>
- ${isActive ? '<span class="opt-check">✓</span>' : ''}
- <span style="font-size:10px;color:var(--text-muted)">${info.desc}</span>
- </div>`;
- }).join('');
- } catch(e) {
- console.error('获取模型列表失败', e);
- }
- }
- function toggleModelDropdown() {
- const selector = document.getElementById('model-selector');
- const dropdown = document.getElementById('model-dropdown');
- const isOpen = dropdown.style.display !== 'none';
- if (isOpen) {
- dropdown.style.display = 'none';
- selector.classList.remove('open');
- } else {
- dropdown.style.display = 'block';
- selector.classList.add('open');
- }
- }
- async function switchModel(modelName) {
- try {
- const res = await fetch(`${API}/model/switch`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ model: modelName }),
- });
- const data = await res.json();
- if (data.error) {
- showToast(data.error, 'error');
- return;
- }
- // Update display
- document.getElementById('current-model-label').textContent = data.current;
- document.getElementById('model-dropdown').style.display = 'none';
- document.getElementById('model-selector').classList.remove('open');
- // Refresh dropdown state
- await fetchModels();
- showToast(data.message || `已切换到 ${modelName}`, 'info');
- } catch(e) {
- showToast(`切换失败: ${e.message}`, 'error');
- console.error(e);
- }
- }
- // Click outside to close dropdown
- document.addEventListener('click', (e) => {
- const selector = document.getElementById('model-selector');
- if (selector && !selector.contains(e.target)) {
- document.getElementById('model-dropdown').style.display = 'none';
- selector.classList.remove('open');
- }
- });
- async function switchThinking(level) {
- try {
- const res = await fetch(`${API}/model/thinking`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ level: level }),
- });
- const data = await res.json();
- if (data.error) {
- showToast(data.error, 'error');
- return;
- }
- // Update button states
- document.querySelectorAll('#thinking-toggle button').forEach(btn => {
- btn.classList.toggle('active', btn.dataset.level === level);
- });
- showToast(data.message || `思考级别已切换为「${level}」`, 'info');
- } catch(e) {
- showToast(`切换失败: ${e.message}`, 'error');
- console.error(e);
- }
- }
- // ============================================================
- // Permission Mode
- // ============================================================
- const MODES = {
- plan: { label: '计划模式', dot: 'plan', desc: '先生成计划,确认后执行' },
- full: { label: '完全访问', dot: 'full', desc: '无限制自动执行' },
- };
- let currentMode = 'plan';
- let pendingInterruptSession = null;
- async function fetchSessionMode() {
- if (!currentSessionId) { currentMode = 'plan'; updateModeUI(); return; }
- try {
- const res = await fetch(`${API}/sessions/${currentSessionId}/mode`, {
- headers: authHeaders(),
- });
- const data = await res.json();
- currentMode = data.mode || 'plan';
- updateModeUI();
- renderModeDropdown();
- } catch(e) { console.error('获取会话模式失败', e); }
- }
- function updateModeUI() {
- const info = MODES[currentMode] || MODES['plan'];
- document.getElementById('mode-label').textContent = info.label;
- const dot = document.getElementById('mode-dot');
- dot.className = 'mode-dot ' + info.dot;
- }
- function renderModeDropdown() {
- const dd = document.getElementById('mode-dropdown');
- dd.innerHTML = Object.entries(MODES).map(([k, v]) => {
- const active = k === currentMode;
- return `<div class="mode-option${active ? ' active' : ''}" onclick="switchMode('${k}')">
- <span class="mode-dot ${v.dot}"></span>
- <span class="mode-opt-name">${v.label}</span>
- <span class="mode-opt-desc">${v.desc}</span>
- ${active ? '<span class="mode-opt-check">✓</span>' : ''}
- </div>`;
- }).join('');
- }
- function toggleModeDropdown() {
- const sel = document.getElementById('mode-selector');
- sel.classList.toggle('open');
- if (sel.classList.contains('open')) renderModeDropdown();
- }
- async function switchMode(mode) {
- // 无会话时仅更新本地 UI 状态,模式会在首次 /chat 时随请求传入
- if (!currentSessionId) {
- currentMode = mode;
- updateModeUI();
- renderModeDropdown();
- document.getElementById('mode-selector').classList.remove('open');
- return;
- }
- try {
- const res = await fetch(`${API}/sessions/${currentSessionId}/mode`, {
- method: 'PUT',
- headers: authHeaders({ 'Content-Type': 'application/json' }),
- body: JSON.stringify({ mode: mode }),
- });
- const data = await res.json();
- if (data.error) { showToast(data.error, 'error'); return; }
- currentMode = mode;
- updateModeUI();
- renderModeDropdown();
- document.getElementById('mode-selector').classList.remove('open');
- showToast(data.message || `已切换为「${MODES[mode]?.label || mode}」`, 'info');
- } catch(e) { showToast(`切换失败: ${e.message}`, 'error'); }
- }
- // Close mode dropdown on outside click
- document.addEventListener('click', (e) => {
- const sel = document.getElementById('mode-selector');
- if (sel && !sel.contains(e.target)) sel.classList.remove('open');
- });
- // ── Interrupt handling ──
- function showInterruptCard(message, node) {
- const bubble = getOrCreateAssistantMsg();
- // Remove any existing interrupt card
- bubble.querySelectorAll('.interrupt-card').forEach(el => el.remove());
- const card = document.createElement('div');
- card.className = 'interrupt-card';
- const nodeLabel = node === 'tools' ? '工具执行' : '继续执行';
- card.innerHTML = `<span class="interrupt-msg">⚠️ ${message || nodeLabel + '等待审批'}</span>
- <button class="btn-approve" onclick="resumeAfterInterrupt('approve')">✓ 批准</button>
- <button class="btn-reject" onclick="resumeAfterInterrupt('reject')">✕ 拒绝</button>`;
- bubble.appendChild(card);
- scrollToBottom();
- }
- async function resumeAfterInterrupt(action) {
- if (!pendingInterruptSession) return;
- const sid = pendingInterruptSession;
- pendingInterruptSession = null;
- // Remove interrupt card
- document.querySelectorAll('.interrupt-card').forEach(el => el.remove());
- if (action === 'reject') {
- showToast('已拒绝执行', 'info');
- clearStatus();
- return;
- }
- setStatus('已批准,继续执行...');
- document.getElementById('status-dot').classList.add('streaming');
- try {
- const res = await fetch(`${API}/chat/resume`, {
- method: 'POST',
- headers: authHeaders({ 'Content-Type': 'application/json' }),
- body: JSON.stringify({ session_id: sid, action: 'approve' }),
- });
- if (!res.ok) {
- const errText = await res.text();
- throw new Error(`HTTP ${res.status}: ${errText}`);
- }
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
- for (const line of lines) {
- if (!line.startsWith('data: ')) continue;
- try {
- const event = JSON.parse(line.slice(6));
- handleSSEEvent(event);
- } catch(e) {}
- }
- }
- } catch(e) {
- if (e.name !== 'AbortError') {
- showToast(`恢复执行失败: ${e.message}`, 'error');
- }
- } finally {
- document.getElementById('status-dot').classList.remove('streaming');
- clearStatus();
- }
- }
- // ============================================================
- // Session Management
- // ============================================================
- async function loadSessions() {
- try {
- const res = await fetch(`${API}/sessions`, { headers: authHeaders() });
- const data = await res.json();
- renderSessionList(data.sessions || []);
- } catch(e) { console.error('加载会话列表失败', e); }
- }
- function renderSessionList(sessions) {
- const el = document.getElementById('session-list');
- if (!sessions.length) {
- el.innerHTML = '<div style="color:var(--text-muted);font-size:12px;padding:16px;text-align:center">暂无会话</div>';
- return;
- }
- el.innerHTML = sessions.map(s => `
- <div class="session-item ${s.session_id === currentSessionId ? 'active' : ''}"
- onclick="switchSession('${s.session_id}')">
- <span class="title">${escHtml(s.title || s.session_id?.slice(0,8) || '新会话')}</span>
- <span class="count">${s.message_count || 0}</span>
- <button class="btn-pin ${s.sort_order > 0 ? 'pinned' : ''}" onclick="event.stopPropagation();togglePin('${s.session_id}')" title="${s.sort_order > 0 ? '取消置顶' : '置顶'}">📌</button>
- <button class="btn-delete" onclick="event.stopPropagation();deleteSession('${s.session_id}')">×</button>
- </div>
- `).join('');
- }
- function newSession() {
- abortStream();
- currentSessionId = null;
- localStorage.removeItem('vent_session_id');
- document.getElementById('messages').innerHTML = `
- <div class="empty-state">
- <div class="big-icon">⛏️</div>
- <div>煤矿通风数据智能解读系统</div>
- <div style="font-size:12px">输入问题或上传配风计划 PDF 开始分析</div>
- </div>`;
- document.getElementById('chat-title').textContent = '新会话';
- document.getElementById('status-bar').innerHTML = '';
- document.getElementById('detail-content').innerHTML = '<div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">发送消息后<br>此处显示任务进度和工具调用</div>';
- todoItems = [];
- toolLogs = [];
- contextData = null;
- pendingDownloadUrl = null;
- loadSessions();
- currentMode = 'plan';
- updateModeUI();
- renderModeDropdown();
- }
- async function switchSession(sid) {
- if (sid === currentSessionId) return;
- abortStream();
- currentSessionId = sid;
- localStorage.setItem('vent_session_id', sid);
- document.getElementById('chat-title').textContent = sid.slice(0,8) + '...';
- loadSessions();
- await loadHistory(sid);
- fetchSessionMode();
- fetchContextUsage();
- }
- async function deleteSession(sid) {
- abortStream();
- await fetch(`${API}/sessions/${sid}`, {
- method: 'DELETE',
- headers: authHeaders(),
- });
- if (currentSessionId === sid) newSession();
- else loadSessions();
- }
- async function togglePin(sid) {
- try {
- const res = await fetch(`${API}/sessions/${sid}/pin`, {
- method: 'PUT',
- headers: authHeaders({ 'Content-Type': 'application/json' }),
- });
- if (!res.ok) return;
- await loadSessions();
- } catch(e) { /* 静默 */ }
- }
- async function loadHistory(sid) {
- try {
- const res = await fetch(`${API}/chat/history/${sid}`, { headers: authHeaders() });
- const data = await res.json();
- const msgsEl = document.getElementById('messages');
- msgsEl.innerHTML = '';
- if (!data.messages || !data.messages.length) {
- msgsEl.innerHTML = '<div class="empty-state"><div class="big-icon">💬</div><div>开始对话吧</div></div>';
- return;
- }
- let lastRole = null;
- data.messages.forEach(m => {
- if (m.role === 'user') {
- addMessage('user', m.content);
- lastRole = 'user';
- } else if (m.role === 'assistant' && m.content) {
- addMessage('assistant', m.content);
- lastRole = 'assistant';
- }
- });
- document.getElementById('chat-title').textContent = data.messages[0]?.content?.slice(0,30) || sid.slice(0,8);
- scrollToBottom();
- } catch(e) { console.error('加载历史失败', e); }
- }
- // ============================================================
- // Message Rendering
- // ============================================================
- function addMessage(role, content) {
- const msgs = document.getElementById('messages');
- // Remove empty state
- const empty = msgs.querySelector('.empty-state');
- if (empty) empty.remove();
- const div = document.createElement('div');
- div.className = `msg ${role}`;
- div.innerHTML = `
- <div class="role">${role === 'user' ? 'YOU' : 'ASSISTANT'}</div>
- <div class="bubble">${role === 'assistant' ? renderMarkdown(content) : escHtml(content)}</div>`;
- msgs.appendChild(div);
- scrollToBottom();
- return div;
- }
- function getOrCreateAssistantMsg() {
- const msgs = document.getElementById('messages');
- const empty = msgs.querySelector('.empty-state');
- if (empty) empty.remove();
- // Find last assistant message
- let last = msgs.querySelector('.msg.assistant:last-child');
- if (!last) {
- last = document.createElement('div');
- last.className = 'msg assistant';
- last.innerHTML = '<div class="role">ASSISTANT</div><div class="bubble"></div>';
- msgs.appendChild(last);
- activeThinkBlock = null;
- }
- const bubble = last.querySelector('.bubble');
- // 确保 markdown 文本容器存在(与 Agent 卡片/工具卡片隔离)
- if (!bubble.querySelector('.msg-markdown')) {
- const md = document.createElement('div');
- md.className = 'msg-markdown';
- bubble.appendChild(md);
- }
- return bubble;
- }
- function appendToken(text) {
- const bubble = getOrCreateAssistantMsg();
- const md = bubble.querySelector('.msg-markdown');
- // 累积原始 markdown 文本
- const existing = md.getAttribute('data-raw') || '';
- md.setAttribute('data-raw', existing + text);
- // 实时追加 token 文本
- const span = document.createElement('span');
- span.textContent = text;
- md.appendChild(span);
- // 每积累约 128 字符时重新渲染(保持表格/标题等格式实时可见)
- const raw = md.getAttribute('data-raw');
- if (raw && raw.length % 128 < text.length) {
- md.innerHTML = renderMarkdown(raw);
- md.setAttribute('data-raw', raw);
- }
- scrollToBottom();
- }
- function appendThinking(text) {
- const bubble = getOrCreateAssistantMsg();
- if (!activeThinkBlock || !bubble.contains(activeThinkBlock)) {
- activeThinkBlock = document.createElement('details');
- activeThinkBlock.className = 'think-block';
- activeThinkBlock.open = true; // 默认展开
- activeThinkBlock.innerHTML = '<summary><span class="think-icon">💭</span> 思考过程</summary><div class="think-content"></div>';
- // Insert at beginning of bubble, before any existing content
- bubble.insertBefore(activeThinkBlock, bubble.firstChild);
- }
- const content = activeThinkBlock.querySelector('.think-content');
- content.textContent += text;
- // Auto-scroll the think content
- content.scrollTop = content.scrollHeight;
- scrollToBottom();
- }
- function addToolCard(name, cnName, status, agentCn) {
- const displayName = cnName || name;
- // ── Agent 内工具:翻页动画,仅显示当前正在执行的一个 ──
- if (agentCn && agentCards[agentCn]) {
- const body = agentCards[agentCn].querySelector('.agent-body');
- if (!body) return;
- // 获取或创建翻页容器,始终保持在 body 的最底部
- let flipper = body.querySelector('.tool-flipper');
- if (!flipper) {
- flipper = document.createElement('div');
- flipper.className = 'tool-flipper';
- }
- body.appendChild(flipper);
- // 当前显示的工具元素
- let current = flipper.querySelector('.current-tool');
- if (!current) {
- current = document.createElement('div');
- current.className = 'current-tool';
- current.innerHTML = `<span class="mt-icon spin-icon-sm"></span><span class="mt-name"></span>`;
- flipper.appendChild(current);
- }
- // ── 取消所有进行中的动画,干净重置 ──
- current.getAnimations().forEach(a => a.cancel());
- if (current._fadeTimer) { clearTimeout(current._fadeTimer); current._fadeTimer = null; }
- // 清除动画残留的 inline style(animation fill 可能留下的 transform/opacity)
- current.style.transform = '';
- current.style.opacity = '';
- if (status === 'done') {
- // 工具完成:显示 ✅,1.2s 后翻出消失
- current.className = 'current-tool done';
- const iconEl = current.querySelector('.mt-icon');
- iconEl.className = 'mt-icon';
- iconEl.textContent = '✅';
- current.querySelector('.mt-name').textContent = displayName;
- current._fadeTimer = setTimeout(() => {
- if (current.parentNode) {
- // 取消可能在进行中的动画,然后翻出
- current.getAnimations().forEach(a => a.cancel());
- current.style.transform = '';
- current.style.opacity = '';
- current.className = 'current-tool flip-out';
- current._fadeTimer = null;
- }
- }, 1200);
- } else {
- // 新工具开始:直接翻入替换
- current.className = 'current-tool';
- const iconEl = current.querySelector('.mt-icon');
- iconEl.className = 'mt-icon spin-icon-sm';
- iconEl.textContent = '';
- current.querySelector('.mt-name').textContent = displayName;
- // 强制回流后启动翻入动画
- void current.offsetWidth;
- current.classList.add('flip-in');
- }
- body.scrollTop = body.scrollHeight;
- scrollToBottom();
- toolLogs.push({ name: displayName, status, time: new Date().toLocaleTimeString() });
- updateDetailPanel();
- return;
- }
- // ── 独立工具卡片(无 Agent 上下文,保留列表模式)──
- const bubble = getOrCreateAssistantMsg();
- const card = document.createElement('div');
- card.className = `tool-card ${status}`;
- if (status === 'done') {
- card.innerHTML = `<span class="tool-icon">✅</span>
- <span class="tool-name">${escHtml(displayName)}</span>
- <span class="tool-status">完成</span>`;
- } else {
- card.innerHTML = `<span class="tool-icon spin-icon-sm"></span>
- <span class="tool-name">${escHtml(displayName)}</span>
- <span class="tool-status">执行中...</span>`;
- }
- // 插入到 markdown 之前
- const md = bubble.querySelector('.msg-markdown');
- if (md) { bubble.insertBefore(card, md); }
- else { bubble.appendChild(card); }
- scrollToBottom();
- toolLogs.push({ name: displayName, status, time: new Date().toLocaleTimeString() });
- updateDetailPanel();
- }
- // ── Agent Card: container for sub-agent tools + progress ──
- let agentCards = {};
- function addAgentCard(cnName, status, durationMs, progress) {
- const bubble = getOrCreateAssistantMsg();
- const key = cnName;
- if (agentCards[key]) {
- const card = agentCards[key];
- card.className = `agent-card ${status}`;
- const iconEl = card.querySelector('.agent-icon');
- if (status === 'done') {
- iconEl.textContent = '✅';
- } else if (status === 'error') {
- iconEl.textContent = '❌';
- } else {
- iconEl.textContent = ''; // CSS spinner handles the running icon
- }
- const durText = durationMs ? ` (${(durationMs/1000).toFixed(1)}s)` : '';
- const progText = progress ? ` [${progress}]` : '';
- card.querySelector('.agent-status').textContent = status === 'done' ? `完成${durText}${progText}` : '运行中...';
- } else {
- const card = document.createElement('div');
- card.className = `agent-card ${status}`;
- card.innerHTML = `<div class="agent-header">
- <span class="agent-icon"></span>
- <span class="agent-name">${escHtml(cnName)}</span>
- <span class="agent-status">启动...</span>
- </div>
- <div class="agent-body"></div>`;
- // 插入到 markdown 文本容器之前,确保 Agent 卡片在 token 输出上方
- const md = bubble.querySelector('.msg-markdown');
- if (md) {
- bubble.insertBefore(card, md);
- } else {
- bubble.appendChild(card);
- }
- agentCards[key] = card;
- }
- scrollToBottom();
- }
- // ── Add mini todos inside an agent card ──
- function addAgentTodos(agentCn, todos) {
- if (!agentCn || !agentCards[agentCn]) return;
- const body = agentCards[agentCn].querySelector('.agent-body');
- if (!body) return;
- // Remove old mini-todos
- body.querySelectorAll('.mini-todo').forEach(el => el.remove());
- todos.forEach(t => {
- const cls = t.status === 'completed' ? 'completed' : t.status === 'in_progress' ? 'in_progress' : '';
- const mt = document.createElement('div');
- mt.className = `mini-todo ${cls}`;
- mt.innerHTML = `<span class="mt-check"></span><span class="mt-label">${escHtml(t.content || '')}</span>`;
- body.appendChild(mt);
- });
- // 确保工具翻页始终在最底部可见
- const flipper = body.querySelector('.tool-flipper');
- if (flipper) body.appendChild(flipper);
- body.scrollTop = body.scrollHeight;
- scrollToBottom();
- }
- function addDuration(durationMs, cnAgent) {
- const bubble = getOrCreateAssistantMsg();
- const dur = document.createElement('div');
- dur.className = 'msg-duration';
- const sec = (durationMs / 1000).toFixed(1);
- const agentLabel = cnAgent ? ` · ${cnAgent}` : '';
- dur.innerHTML = `⏱️ ${sec}s${agentLabel}`;
- bubble.appendChild(dur);
- }
- function updateTodoList(todos) {
- todoItems = todos || [];
- updateDetailPanel();
- }
- // ── 上下文容量 ──
- let contextData = null;
- async function fetchContextUsage() {
- if (!currentSessionId) { contextData = null; updateDetailPanel(); return; }
- try {
- const res = await fetch(`${API}/sessions/${currentSessionId}/context`, {
- headers: authHeaders(),
- });
- if (!res.ok) return;
- contextData = await res.json();
- updateDetailPanel();
- } catch(e) { /* 静默 */ }
- }
- function renderContextMeter() {
- if (!contextData || contextData.total_limit == null) {
- return '<div class="context-meter"><div class="cm-empty">📊 暂无上下文数据<br><span style="font-size:9px">发送消息后自动统计</span></div></div>';
- }
- const pct = contextData.usage_pct || 0;
- const limit = contextData.total_limit;
- const used = contextData.current_usage;
- const bd = contextData.breakdown || {};
- let cls = 'low';
- if (pct > 75) cls = 'crit';
- else if (pct > 50) cls = 'high';
- else if (pct > 25) cls = 'medium';
- const fmt = (n) => n != null ? (n >= 1000 ? (n/1000).toFixed(1)+'K' : n) : '—';
- return `<div class="context-meter">
- <div class="cm-header">
- <span class="cm-label">🧠 上下文容量</span>
- <span class="cm-value">${fmt(used)} / ${fmt(limit)} (${pct}%)</span>
- </div>
- <div class="cm-bar-outer">
- <div class="cm-bar-inner ${cls}" style="width:${Math.min(pct,100)}%"></div>
- </div>
- <div class="cm-breakdown">
- <div class="cm-item"><span class="cm-cat">💬 消息</span><span class="cm-num">${fmt(bd.messages)}</span></div>
- <div class="cm-item"><span class="cm-cat">🔧 系统工具</span><span class="cm-num">${fmt(bd.tools)}</span></div>
- <div class="cm-item"><span class="cm-cat">📋 技能</span><span class="cm-num">${fmt(bd.skills)}</span></div>
- <div class="cm-item"><span class="cm-cat">🔌 MCP</span><span class="cm-num">${fmt(bd.mcp)}</span></div>
- <div class="cm-item"><span class="cm-cat">📝 系统提示</span><span class="cm-num">${fmt(bd.system_prompt)}</span></div>
- <div class="cm-item"><span class="cm-cat">📦 其他</span><span class="cm-num">${fmt(bd.other)}</span></div>
- </div>
- </div>`;
- }
- function updateDetailPanel() {
- const el = document.getElementById('detail-content');
- let html = '';
- // ── 上下文容量(始终在最上方)──
- html += renderContextMeter();
- if (todoItems.length) {
- html += '<div class="section"><div class="section-title">📝 任务进度</div>';
- todoItems.forEach(t => {
- const cls = t.status === 'completed' ? 'completed' : t.status === 'in_progress' ? 'in_progress' : '';
- html += `<div class="todo-item ${cls}">
- <span class="todo-check"></span>
- <span class="todo-label">${escHtml(t.content || '')}</span>
- </div>`;
- });
- html += '</div>';
- }
- if (toolLogs.length) {
- html += '<div class="section"><div class="section-title">🔧 工具调用</div>';
- toolLogs.slice(-20).reverse().forEach(t => {
- html += `<div class="tool-log-item">
- <span class="tl-icon">${t.status === 'done' ? '✅' : '⏳'}</span>
- <span class="tl-name">${escHtml(t.name)}</span>
- </div>`;
- });
- html += '</div>';
- }
- if (!html) {
- html = '<div style="color:var(--text-muted);font-size:12px;text-align:center;margin-top:40px;">暂无任务数据</div>';
- }
- el.innerHTML = html;
- }
- function setStatus(text) {
- document.getElementById('status-bar').innerHTML = `
- <span class="spinner"></span><span>${escHtml(text)}</span>`;
- }
- function clearStatus() {
- document.getElementById('status-bar').innerHTML = '';
- }
- // ============================================================
- // Markdown Rendering (simple built-in, no CDN dependency)
- // ============================================================
- function renderMarkdown(text) {
- if (!text) return '';
- let html = text;
- // Escape HTML
- html = html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
- // Code blocks (```...```)
- html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) =>
- `<pre><code class="language-${lang}">${code.trim()}</code></pre>`);
- // Inline code (`...`)
- html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
- // Bold (**...**)
- html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
- // Headers (longest first to avoid partial matches)
- html = html.replace(/^###### (.+)$/gm, '<h6>$1</h6>');
- html = html.replace(/^##### (.+)$/gm, '<h5>$1</h5>');
- html = html.replace(/^#### (.+)$/gm, '<h4>$1</h4>');
- html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
- html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
- html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
- // Blockquote
- html = html.replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>');
- // Unordered lists
- html = html.replace(/^[\-\*] (.+)$/gm, '<li>$1</li>');
- html = html.replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>');
- // Ordered lists
- html = html.replace(/^\d+\. (.+)$/gm, '<li>$1</li>');
- // Tables
- html = html.replace(/^\|(.+)\|$/gm, (line) => {
- const cells = line.split('|').filter(c => c.trim());
- const isHeader = /^[\-\s:]+$/.test(cells.join(''));
- if (isHeader) return '';
- const tag = line.match(/^\|[\s\-:]+\|$/) ? '' : (line.includes('---') ? '' : '');
- return '<tr>' + cells.map(c => {
- const t = isHeader ? 'th' : 'td';
- return `<${t}>${c.trim()}</${t}>`;
- }).join('') + '</tr>';
- });
- html = html.replace(/(<tr>.*<\/tr>\n?)+/g, '<table>$&</table>');
- // Horizontal rules
- html = html.replace(/^---$/gm, '<hr>');
- // Paragraphs (double newline)
- const parts = html.split(/\n\n+/);
- html = parts.map(p => {
- p = p.trim();
- if (!p) return '';
- if (p.startsWith('<h') || p.startsWith('<pre') || p.startsWith('<table')
- || p.startsWith('<ul') || p.startsWith('<blockquote') || p.startsWith('<hr')) return p;
- return `<p>${p.replace(/\n/g, '<br>')}</p>`;
- }).join('\n');
- return html;
- }
- // ============================================================
- // SSE Streaming
- // ============================================================
- async function sendMessage() {
- const input = document.getElementById('input');
- const message = input.value.trim();
- const fileInput = document.getElementById('file-input');
- const file = fileInput.files[0];
- if (!message && !file) return;
- // Abort previous stream
- abortStream();
- // Reset state
- todoItems = [];
- toolLogs = [];
- activeThinkBlock = null;
- agentCards = {};
- pendingDownloadUrl = null;
- updateDetailPanel();
- // Build FormData
- const fd = new FormData();
- fd.append('message', message || (file ? '请审查这份文件' : ''));
- if (currentSessionId) fd.append('session_id', currentSessionId);
- fd.append('mode', currentMode);
- if (file) {
- fd.append('file', file);
- document.getElementById('btn-attach').classList.add('has-file');
- }
- // Add user message to UI
- if (message) addMessage('user', message);
- if (file) {
- addMessage('user', `📎 上传文件: ${file.name}\n${message || '请审查这份文件'}`);
- }
- // Clear input
- input.value = '';
- fileInput.value = '';
- document.getElementById('btn-attach').classList.remove('has-file');
- input.style.height = 'auto';
- // UI state
- setStatus('正在分析...');
- document.getElementById('status-dot').classList.add('streaming');
- document.getElementById('btn-send').disabled = true;
- currentAbortController = new AbortController();
- try {
- const res = await fetch(`${API}/chat`, {
- method: 'POST',
- body: fd,
- headers: authHeaders(),
- signal: currentAbortController.signal,
- });
- if (!res.ok) {
- const errText = await res.text();
- throw new Error(`HTTP ${res.status}: ${errText}`);
- }
- // Get session_id from header
- const sid = res.headers.get('X-Session-Id');
- if (sid && sid !== currentSessionId) {
- currentSessionId = sid;
- localStorage.setItem('vent_session_id', sid);
- loadSessions();
- fetchSessionMode();
- }
- // Stream reader
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- let assistantContent = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- // Process complete SSE events
- const lines = buffer.split('\n');
- buffer = lines.pop() || ''; // keep incomplete line in buffer
- for (const line of lines) {
- if (!line.startsWith('data: ')) continue;
- const json = line.slice(6);
- try {
- const event = JSON.parse(json);
- handleSSEEvent(event);
- if (event.type === 'token' && event.content) {
- assistantContent += event.content;
- }
- } catch(e) {
- // Skip malformed JSON
- }
- }
- }
- // Finalize
- if (assistantContent && !currentSessionId) {
- // Session was created server-side
- loadSessions();
- }
- } catch(e) {
- if (e.name !== 'AbortError') {
- showToast(`请求失败: ${e.message}`, 'error');
- console.error(e);
- }
- } finally {
- document.getElementById('status-dot').classList.remove('streaming');
- document.getElementById('btn-send').disabled = false;
- clearStatus();
- currentAbortController = null;
- }
- }
- function handleSSEEvent(event) {
- switch(event.type) {
- case 'thinking':
- case 'agent_thinking':
- setStatus(event.cn_agent ? `${event.cn_agent}:分析中...` : (event.message || '正在分析...'));
- break;
- case 'thinking_token':
- case 'agent_thinking_token':
- if (event.content) appendThinking(event.content);
- break;
- case 'executing':
- case 'agent_executing':
- {
- const label = event.cn_agent ? `${event.cn_agent}:${event.message}` : event.message;
- setStatus(label || '正在执行工具...');
- if (event.tools && event.tools.length > 0) {
- const cnTools = event.cn_tools || event.tools;
- // 翻页模式:仅展示最后一条(最新执行的工具)
- const lastIdx = event.tools.length - 1;
- addToolCard(event.tools[lastIdx], cnTools[lastIdx], 'pending', event.cn_agent);
- }
- }
- break;
- case 'tool_call':
- addToolCard(event.tool, event.cn_tool, 'pending', event.cn_agent);
- break;
- case 'tool_result':
- case 'agent_tool_result':
- addToolCard(event.tool || '工具', event.cn_tool, 'done', event.cn_agent);
- break;
- case 'token':
- if (event.content) appendToken(event.content);
- break;
- case 'updated_todo_list':
- case 'agent_todos':
- if (event.todos) {
- // If agent context, show mini todos inside agent card
- if (event.cn_agent) {
- addAgentTodos(event.cn_agent, event.todos);
- }
- updateTodoList(event.todos);
- }
- break;
- case 'progress':
- setStatus(event.message || '处理中...');
- if (event.download_url) {
- pendingDownloadUrl = event.download_url;
- // Immediately show the download button
- const bubble = getOrCreateAssistantMsg();
- // Remove any previous download button
- bubble.querySelectorAll('.download-btn').forEach(el => el.remove());
- bubble.appendChild(createDownloadBtn(event.download_url));
- }
- break;
- case 'agent_start':
- {
- // 在聊天区显示子智能体启动卡片(体现并行感)
- const cn = event.cn_agent || event.agent;
- addAgentCard(cn, 'running');
- setStatus(`${cn} 启动...`);
- }
- break;
- case 'agent_done':
- {
- const cn = event.cn_agent || event.agent;
- addAgentCard(cn, 'done', event.duration_ms, event.progress);
- setStatus(`✅ ${cn} 完成 (${event.progress || ''})`);
- // Agent 结束 → 无论工具处于什么状态,一律翻出清理
- if (agentCards[cn]) {
- const flipper = agentCards[cn].querySelector('.tool-flipper');
- if (flipper) {
- const ct = flipper.querySelector('.current-tool');
- if (ct) {
- if (ct._fadeTimer) { clearTimeout(ct._fadeTimer); ct._fadeTimer = null; }
- ct.getAnimations().forEach(a => a.cancel());
- ct.style.transform = '';
- ct.style.opacity = '';
- ct.className = 'current-tool flip-out';
- }
- }
- }
- }
- break;
- case 'agent_error':
- showToast(event.message || '子智能体出错', 'error');
- break;
- case 'done':
- clearStatus();
- if (event.duration_ms) {
- addDuration(event.duration_ms, '');
- }
- if (event.download_url) {
- pendingDownloadUrl = event.download_url;
- }
- // 最终渲染 markdown ……
- {
- const bubble = getOrCreateAssistantMsg();
- if (bubble) {
- const md = bubble.querySelector('.msg-markdown');
- if (md) {
- const raw = md.getAttribute('data-raw');
- if (raw) {
- md.innerHTML = renderMarkdown(raw);
- md.removeAttribute('data-raw');
- }
- }
- // 兜底清理:所有 Agent 卡内残留的工具翻页
- bubble.querySelectorAll('.tool-flipper .current-tool').forEach(ct => {
- if (ct._fadeTimer) { clearTimeout(ct._fadeTimer); ct._fadeTimer = null; }
- ct.getAnimations().forEach(a => a.cancel());
- ct.style.transform = '';
- ct.style.opacity = '';
- ct.className = 'current-tool flip-out';
- });
- if (pendingDownloadUrl) {
- bubble.querySelectorAll('.download-btn').forEach(el => el.remove());
- bubble.appendChild(createDownloadBtn(pendingDownloadUrl));
- }
- }
- }
- activeThinkBlock = null;
- loadSessions();
- fetchContextUsage();
- break;
- case 'error':
- showToast(event.message || '出错了', 'error');
- clearStatus();
- break;
- case 'generating':
- setStatus('正在生成报告...');
- break;
- case 'interrupt':
- // LangGraph 中断:需要用户审批
- pendingInterruptSession = currentSessionId;
- showInterruptCard(event.message || '智能体暂停,等待审批...', event.node);
- break;
- }
- }
- function abortStream() {
- if (currentAbortController) {
- currentAbortController.abort();
- currentAbortController = null;
- }
- document.getElementById('status-dot').classList.remove('streaming');
- document.getElementById('btn-send').disabled = false;
- clearStatus();
- }
- // ============================================================
- // Helpers
- // ============================================================
- function escHtml(s) {
- if (!s) return '';
- return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
- }
- function scrollToBottom() {
- requestAnimationFrame(() => {
- const msgs = document.getElementById('messages');
- msgs.scrollTop = msgs.scrollHeight;
- });
- }
- function onInputKey(e) {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- sendMessage();
- }
- }
- function onFileSelected(input) {
- const btn = document.getElementById('btn-attach');
- if (input.files.length) {
- btn.classList.add('has-file');
- btn.title = input.files[0].name;
- } else {
- btn.classList.remove('has-file');
- btn.title = '上传附件';
- }
- }
- function showToast(msg, type) {
- const container = document.getElementById('toast-container');
- const el = document.createElement('div');
- el.className = `toast ${type}`;
- el.textContent = msg;
- container.appendChild(el);
- setTimeout(() => { el.remove(); }, 4000);
- }
- function createDownloadBtn(url) {
- const btn = document.createElement('a');
- btn.className = 'download-btn';
- btn.href = url;
- btn.target = '_blank';
- btn.rel = 'noopener';
- btn.innerHTML = '<span class="dl-icon">📥</span> 下载审查报告 (Word)';
- return btn;
- }
- // Auto-resize textarea
- document.addEventListener('DOMContentLoaded', () => {
- const input = document.getElementById('input');
- input.addEventListener('input', () => {
- input.style.height = 'auto';
- input.style.height = Math.min(input.scrollHeight, 150) + 'px';
- });
- });
- // ============================================================
- // Skill Manager
- // ============================================================
- async function openSkillManager() {
- document.getElementById('skill-modal').style.display = 'flex';
- await refreshSkillList();
- }
- function closeSkillModal() {
- document.getElementById('skill-modal').style.display = 'none';
- }
- // ESC to close
- document.addEventListener('keydown', (e) => {
- if (e.key === 'Escape') closeSkillModal();
- });
- async function refreshSkillList() {
- const body = document.getElementById('skill-modal-body');
- body.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:40px;">加载中...</div>';
- try {
- const res = await fetch(`${API}/skills`);
- const data = await res.json();
- const skills = data.skills || [];
- if (!skills.length) {
- body.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:40px;">暂无技能</div>';
- return;
- }
- let html = `<table class="skill-table">
- <thead><tr>
- <th>技能名称</th><th>描述</th><th>所属智能体</th><th>状态</th><th>操作</th>
- </tr></thead><tbody>`;
- skills.forEach(s => {
- const statusCls = s.enabled ? 'enabled' : 'disabled';
- const statusText = s.enabled ? '启用' : '禁用';
- const toggleLabel = s.enabled ? '停用' : '启用';
- html += `<tr>
- <td><span class="skill-name" onclick="viewSkill('${s.name}')">${escHtml(s.display_name || s.name)}</span></td>
- <td class="skill-desc" title="${escHtml(s.description)}">${escHtml(s.description) || '—'}</td>
- <td class="skill-agents">${s.agents.map(a => escHtml(a)).join('<br>')}</td>
- <td><span class="status-badge ${statusCls}">${statusText}</span></td>
- <td>
- <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>
- <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>
- </td>
- </tr>`;
- });
- html += '</tbody></table>';
- // Upload zone
- html += `<div class="upload-zone" id="skill-upload-zone" onclick="document.getElementById('skill-upload-input').click()">
- 📤 点击上传新技能(.zip 格式)
- </div>`;
- // Detail section
- html += '<div class="skill-detail" id="skill-detail"></div>';
- body.innerHTML = html;
- } catch(e) {
- body.innerHTML = `<div style="text-align:center;color:var(--red);padding:40px;">加载失败: ${escHtml(e.message)}</div>`;
- console.error(e);
- }
- }
- async function viewSkill(name) {
- const detail = document.getElementById('skill-detail');
- if (!detail) return;
- detail.style.display = 'block';
- detail.innerHTML = '<div style="text-align:center;color:var(--text-muted);padding:20px;">加载中...</div>';
- try {
- const res = await fetch(`${API}/skills/${name}`);
- if (!res.ok) {
- const err = await res.json();
- detail.innerHTML = `<div style="color:var(--red);padding:20px;">${escHtml(err.error || '加载失败')}</div>`;
- return;
- }
- const data = await res.json();
- // Strip YAML frontmatter before rendering
- let content = data.content || '';
- content = content.replace(/^---[\s\S]*?---\n*/, '');
- detail.innerHTML = `<div style="margin-bottom:8px;color:var(--accent);font-weight:600;">📄 ${escHtml(name)} / SKILL.md</div>
- <div>${renderMarkdown(content)}</div>`;
- } catch(e) {
- detail.innerHTML = `<div style="color:var(--red);padding:20px;">加载失败: ${escHtml(e.message)}</div>`;
- console.error(e);
- }
- }
- async function toggleSkill(name) {
- try {
- const res = await fetch(`${API}/skills/${name}/toggle`, { method: 'POST' });
- const data = await res.json();
- if (data.error) {
- showToast(data.error, 'error');
- return;
- }
- showToast(data.message, 'info');
- await refreshSkillList();
- } catch(e) {
- showToast(`操作失败: ${e.message}`, 'error');
- console.error(e);
- }
- }
- async function uploadSkill(input) {
- const file = input.files[0];
- if (!file) return;
- const fd = new FormData();
- fd.append('file', file);
- try {
- showToast('正在上传技能...', 'info');
- const res = await fetch(`${API}/skills/upload`, {
- method: 'POST',
- body: fd,
- });
- const data = await res.json();
- if (!res.ok) {
- showToast(data.error || '上传失败', 'error');
- return;
- }
- showToast(data.message, 'info');
- input.value = '';
- await refreshSkillList();
- } catch(e) {
- showToast(`上传失败: ${e.message}`, 'error');
- console.error(e);
- }
- }
- </script>
- </body>
- </html>
|