| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238 |
- <!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; position: relative;
- flex-wrap: wrap;
- }
- .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); }
- .btn-insert-session {
- 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-insert-session:hover { border-color: var(--accent); color: var(--accent); }
- .btn-insert-session.active { border-color: var(--accent); color: var(--accent); background: var(--accent-dim); }
- /* Session reference chip */
- .session-ref-chip {
- display: flex; align-items: center; gap: 6px;
- background: var(--accent-dim); border: 1px solid var(--accent);
- border-radius: 6px; padding: 4px 10px; font-size: 12px;
- color: var(--accent); width: 100%; flex-shrink: 0;
- }
- .session-ref-chip .chip-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .session-ref-chip .chip-remove {
- background: none; border: none; color: var(--text-muted); cursor: pointer;
- font-size: 16px; padding: 0 2px; line-height: 1;
- }
- .session-ref-chip .chip-remove:hover { color: var(--red); }
- /* Session picker panel */
- .session-picker {
- position: absolute; bottom: 100%; left: 12px; right: 12px;
- background: var(--bg-secondary); border: 1px solid var(--border);
- border-radius: var(--radius); box-shadow: 0 8px 24px rgba(0,0,0,0.4);
- z-index: 100; max-height: 320px; display: flex; flex-direction: column;
- margin-bottom: 8px;
- }
- .picker-search { padding: 10px; border-bottom: 1px solid var(--border); flex-shrink: 0; }
- .picker-search input {
- width: 100%; background: var(--bg-tertiary); border: 1px solid var(--border);
- border-radius: 6px; color: var(--text-primary); padding: 8px 12px;
- font-size: 13px; outline: none; box-sizing: border-box;
- }
- .picker-search input:focus { border-color: var(--accent); }
- .picker-search input::placeholder { color: var(--text-muted); }
- .picker-list { flex: 1; overflow-y: auto; padding: 6px 0; }
- .picker-item {
- padding: 10px 14px; cursor: pointer; font-size: 13px;
- color: var(--text-primary); transition: background .1s;
- display: flex; justify-content: space-between; align-items: center;
- gap: 8px;
- }
- .picker-item:hover { background: var(--bg-hover); }
- .picker-item .picker-title {
- flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
- }
- .picker-item .picker-meta {
- font-size: 11px; color: var(--text-muted); flex-shrink: 0;
- }
- .picker-empty {
- padding: 20px; text-align: center; color: var(--text-muted); font-size: 13px;
- }
- #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" id="input-area">
- <button class="btn-attach" id="btn-attach" onclick="document.getElementById('file-input').click()" title="上传附件">📎</button>
- <button class="btn-insert-session" id="btn-insert-session" onclick="toggleSessionPicker()" title="插入会话">📋</button>
- <input type="file" id="file-input" accept=".pdf,.doc,.docx,.txt" onchange="onFileSelected(this)">
- <!-- 引用会话 chip -->
- <div class="session-ref-chip" id="session-ref-chip" style="display:none;">
- <span class="chip-label">📋 引用: <span id="chip-title"></span></span>
- <button class="chip-remove" onclick="removeSessionRef()" title="取消引用">×</button>
- </div>
- <textarea id="input" placeholder="输入您的问题..." rows="1" onkeydown="onInputKey(event)"></textarea>
- <button class="btn-send" id="btn-send" onclick="sendMessage()" title="发送">↑</button>
- <!-- 会话选择面板 -->
- <div class="session-picker" id="session-picker" style="display:none;">
- <div class="picker-search">
- <input type="text" id="picker-search-input" placeholder="搜索会话标题..." oninput="onPickerSearch(this.value)">
- </div>
- <div class="picker-list" id="picker-list"></div>
- </div>
- </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;
- let referencedSessionId = null; // 引用的会话 ID
- let referencedSessionTitle = ''; // 引用的会话标题
- let pickerDebounceTimer = 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) { /* 静默 */ }
- }
- // ============================================================
- // Session Picker (插入会话)
- // ============================================================
- function toggleSessionPicker() {
- const picker = document.getElementById('session-picker');
- const btn = document.getElementById('btn-insert-session');
- if (picker.style.display === 'none') {
- picker.style.display = 'flex';
- btn.classList.add('active');
- loadPickerSessions('');
- } else {
- picker.style.display = 'none';
- btn.classList.remove('active');
- }
- }
- async function loadPickerSessions(keyword) {
- const listEl = document.getElementById('picker-list');
- try {
- const params = keyword ? `?q=${encodeURIComponent(keyword)}` : '';
- const res = await fetch(`${API}/sessions/search${params}`, { headers: authHeaders() });
- const data = await res.json();
- const sessions = data.sessions || [];
- // 过滤掉当前会话
- const filtered = sessions.filter(s => s.session_id !== currentSessionId);
- if (!filtered.length) {
- listEl.innerHTML = '<div class="picker-empty">' + (keyword ? '无匹配会话' : '暂无其他会话') + '</div>';
- return;
- }
- listEl.innerHTML = filtered.map(s => {
- const safeId = s.session_id.replace(/'/g, "\\'");
- const safeTitle = escHtml(s.title || s.session_id.slice(0,8)).replace(/'/g, "'");
- return `
- <div class="picker-item" onclick="selectSession('${safeId}', '${safeTitle}')">
- <span class="picker-title">${escHtml(s.title || s.session_id.slice(0,8))}</span>
- <span class="picker-meta">${s.message_count || 0}条</span>
- </div>`;
- }).join('');
- } catch(e) {
- listEl.innerHTML = '<div class="picker-empty">加载失败</div>';
- }
- }
- function onPickerSearch(val) {
- clearTimeout(pickerDebounceTimer);
- pickerDebounceTimer = setTimeout(() => loadPickerSessions(val.trim()), 200);
- }
- function selectSession(id, title) {
- referencedSessionId = id;
- referencedSessionTitle = title;
- // 显示引用 chip
- const chip = document.getElementById('session-ref-chip');
- document.getElementById('chip-title').textContent = title;
- chip.style.display = 'flex';
- // 关闭面板
- document.getElementById('session-picker').style.display = 'none';
- document.getElementById('btn-insert-session').classList.remove('active');
- // 聚焦输入框
- document.getElementById('input').focus();
- }
- function removeSessionRef() {
- referencedSessionId = null;
- referencedSessionTitle = '';
- document.getElementById('session-ref-chip').style.display = 'none';
- document.getElementById('input').focus();
- }
- // 点击面板外关闭
- document.addEventListener('click', function(e) {
- const picker = document.getElementById('session-picker');
- const btn = document.getElementById('btn-insert-session');
- if (picker.style.display !== 'none' && !picker.contains(e.target) && e.target !== btn) {
- picker.style.display = 'none';
- btn.classList.remove('active');
- }
- });
- 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 && !referencedSessionId) return;
- // Abort previous stream
- abortStream();
- // Reset state
- todoItems = [];
- toolLogs = [];
- activeThinkBlock = null;
- agentCards = {};
- pendingDownloadUrl = null;
- updateDetailPanel();
- // 构建发送给后端的消息(含会话引用前缀)
- let sendMessage = message || (file ? '请审查这份文件' : '');
- if (referencedSessionId) {
- sendMessage = `#session:${referencedSessionId} ${sendMessage}`.trim();
- }
- // Build FormData
- const fd = new FormData();
- fd.append('message', sendMessage);
- 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
- let displayMsg = message || '';
- if (referencedSessionId) {
- displayMsg = `📋 引用会话「${referencedSessionTitle}」` + (displayMsg ? `\n${displayMsg}` : '');
- }
- if (file) {
- displayMsg = `📎 上传文件: ${file.name}` + (displayMsg ? `\n${displayMsg}` : '');
- }
- if (displayMsg) {
- addMessage('user', displayMsg);
- }
- // Clear input and session reference
- input.value = '';
- fileInput.value = '';
- document.getElementById('btn-attach').classList.remove('has-file');
- removeSessionRef();
- 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>
|